Skip to content

Instantly share code, notes, and snippets.

@benpackard
Created November 13, 2018 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benpackard/eb723750cf9868a9c75a4884c2dd1aa9 to your computer and use it in GitHub Desktop.
Save benpackard/eb723750cf9868a9c75a4884c2dd1aa9 to your computer and use it in GitHub Desktop.
Set and get selected enum case from a `UISegmentedControl` without relying on indexes or strings.
import UIKit
protocol Segmentable: RawRepresentable & CaseIterable { }
class EnumeratedSegmentedControl<T: Segmentable>: UISegmentedControl where T.RawValue == String {
convenience init() {
let items = T.allCases.map { $0.rawValue }
self.init(items: items)
}
var selectedSegment: T? {
get {
if selectedSegmentIndex == -1 { return nil }
guard selectedSegmentIndex < T.allCases.count else { return nil }
return Array(T.allCases)[selectedSegmentIndex]
}
set {
if let newValue = newValue {
selectedSegmentIndex = T.allCases.map({ $0.rawValue }).index(of: newValue.rawValue) ?? -1
} else {
selectedSegmentIndex = -1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment