我只是从Android平台转移到ios,正在迅速寻找无法找到类似它的构建器模式的get和set方法。仅发现以下

var ptype : String? {
    get{
        return self.ptype
    }set (ptype) {
        self.ptype = ptype
    }
}

最佳答案

以下技巧看起来像您想要的https://github.com/vincent-pradeilles/swift-tips#implementing-the-builder-pattern-with-keypaths。我将在此处复制代码以便快速查看。


protocol With {}

extension With where Self: AnyObject {
    @discardableResult
    func with<T>(_ property: ReferenceWritableKeyPath<Self, T>, setTo value: T) -> Self {
        self[keyPath: property] = value
        return self
    }
}

extension UIView: With {}

let view = UIView()

let label = UILabel()
    .with(\.textColor, setTo: .red)
    .with(\.text, setTo: "Foo")
    .with(\.textAlignment, setTo: .right)
    .with(\.layer.cornerRadius, setTo: 5)

view.addSubview(label)

10-05 21:03
查看更多