Skip to content

Instantly share code, notes, and snippets.

@LieonShelly
Created October 29, 2020 09:33
Show Gist options
  • Save LieonShelly/837b8352c602250150a898aaae676340 to your computer and use it in GitHub Desktop.
Save LieonShelly/837b8352c602250150a898aaae676340 to your computer and use it in GitHub Desktop.
Option Pattern 在 Swift 中使用,用于改善可选项的 API 设计,向已有类型中以类型安全的方式添加“存储”属性
protocol PersonOption {
associatedtype Value
static var defaultValue: Value { get }
}
class Person {
enum Color: PersonOption {
case red
case blue
static var defaultValue: Color = .red
}
var age = 0
private var option: [ObjectIdentifier: Any] = [ObjectIdentifier: Any]()
subscript<T: PersonOption>(option type: T.Type) -> T.Value {
get { option[ObjectIdentifier(type)] as? T.Value ?? T.defaultValue }
set { option[ObjectIdentifier(type)] = newValue }
}
}
extension Int: PersonOption {
static var defaultValue: Int = 0
}
extension Person {
var color: Color {
get { self[option: Color.self] }
set { self[option: Color.self] = newValue }
}
var height: Int {
get { self[option: Int.self] }
set { self[option: Int.self] = newValue }
}
}
extension Person.Color {
var uiColor: UIColor {
switch self {
case .red:
return .red
case .blue:
return .blue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment