Swift 3必看:#selector獲取屬性的getter和setter方法

在swift中如果要獲取一個(gè)方法的selector用#selector()實(shí)現(xiàn)。我們也知道OC中的屬性其實(shí)是自動(dòng)生成了getter和setter方法。
swift 3中支持獲取屬性的getter和setter方法。語(yǔ)法就是:<code>#selector(getter: keypath )</code> 和 <code>#selector(setter: keypath )</code>。示例如下:

class Person: NSObject {
    dynamic var firstName: String
    dynamic let lastName: String
    dynamic var fullName: String {
        return "\(firstName) \(lastName)"
    }
    
    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

let firstNameGetter = #selector(getter: Person.firstName)
let firstNameSetter = #selector(setter: Person.firstName)

這兩個(gè)方法和OC中的簽名一致。set方法簽名就是<code>setFirstName:</code>。
然后就可以正常使用了:

歡迎關(guān)注我的微博:@沒(méi)故事的卓同學(xué)

相關(guān)鏈接:
SE0064-Referencing the Objective-C selector of property getters and setters

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容