kemchenj
9/13/2017 - 4:27 PM

ReadOnly

使用 KeyPath 实现 ReadOnly 的功能

https://twitter.com/chriseidhof/status/907891015973003264

extension AnyObject {
    var readOnly: ReadOnly<Self> {
        return ReadOnly(self)
    }
}
final class ReadOnly<T> {
    private let value: T
    
    init(_ value: T) {
        self.value = value
    }
    
    subscript<R>(keyPath: KeyPath<T, R>) -> R {
        return value[keyPath: keyPath]
    }
}
import UIKit

let textField = UITextField()

let readOnlyTextField = ReadOnly(textFiled)

r[\.text] // nil
r[\.text] = "Test" // Compile Error