使用 KeyPath 实现 ReadOnly 的功能
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