[英]How to call static method provided by protocol in Swift
如何訪問實例內的static
協議方法
我有一個列表Contact
,聯系人可以是FamilyContact
從繼承Contact
和GroupStatus protocol
我想從GroupStatus
調用靜態方法但徒勞無功...
這是我的代碼
protocol GroupStatus {
static func isPrivate() -> Bool // static method that indicates the status
}
protocol IsBusy {
func wizzIt()
}
class AdresseBook {
private var contacts = [Contact]()
func addOne(c: Contact) {
contacts.append(c)
}
func listNonPrivated() -> [Contact]? {
var nonPrivateContact = [Contact]()
for contact in contacts {
// here is I should call the static method provided by the protocol
if self is GroupStatus {
let isPrivate = contact.dynamicType.isPrivate()
if !isPrivate {
nonPrivateContact.append(contact)
}
}
nonPrivateContact.append(contact)
}
return nonPrivateContact
}
}
class Contact : Printable {
var name: String
init(name: String) {
self.name = name
}
func wizz() -> Bool {
if let obj = self as? IsBusy {
obj.wizzIt()
return true
}
return false
}
var description: String {
return self.name
}
}
class FamilyContact: Contact, GroupStatus {
static func isPrivate() -> Bool {
return true
}
}
我無法編譯Contact.Type does not have a member named 'isPrivate'
我怎么稱呼它? 如果我刪除static
關鍵字,它會起作用,但我認為將其定義為 static 更合乎邏輯。
如果我更換
let isPrivate = contact.dynamicType.isPrivate()
經過
let isPrivate = FamilyContact.isPrivate()
它有效,但我可以有 1 個以上的子類
如果我刪除static
鍵工作,我可以通過這種方式做到這一點:
if let c = contact as? GroupStatus {
if !c.isPrivate() {
nonPrivateContact.append(contact)
}
}
但我想保留static
關鍵字
這看起來像是一個錯誤或不受支持的功能。 我希望以下工作:
if let gsType = contact.dynamicType as? GroupStatus.Type {
if gsType.isPrivate() {
// ...
}
}
但是,它不會編譯:
error: accessing members of protocol type value 'GroupStatus.Type' is unimplemented
它確實使用FamilyContact.Type
而不是GroupStatus.Type
編譯。 這里報告了一個類似的問題:
使isPrivate()
成為實例方法而不是類方法是我目前能想到的唯一解決方法,也許有人提出了更好的解決方案......
Swift 2 / Xcode 7 的更新:正如@Tankista 在下面提到的,這已經得到修復。 上面的代碼在 Xcode 7 beta 3 中按預期編譯和工作。
type(of: contact).isPrivate()
這應該適用於最近的 Swift。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.