2015-08-20 28 views
3

如何在swift可選中創建協議方法?現在協議中的所有方法似乎都是必需的。還有其他的解決方法嗎?如何在swift可選中創建協議方法?

+0

如果我的答案幫助你,請upvote並接受它。謝謝! –

回答

5

要使用可選的方法,用@objc

@objc protocol MyProtocol { 

    optional func someMethod(); 

} 

標記你的協議作爲the documentation說明。

6

雖然你可以在斯威夫特2使用@objc你可以添加一個默認實現,你不必提供自己的方法:

protocol Creatable { 
    func create() 
} 

extension Creatable { 
    // by default a method that does nothing 
    func create() {} 
} 

struct Creator: Creatable {} 

// you get the method by default 
Creator().create() 

但是在斯威夫特1.x中,您可以添加,其保持變量一個可選的封閉

protocol Creatable { 
    var create: (()->())? { get } 
} 

struct Creator: Creatable { 
    // no implementation 
    var create: (()->())? = nil 

    var create: (()->())? = { ... } 

    // "let" behavior like normal functions with a computed property 
    var create: (()->())? { 
     return { ... } 
    } 
} 

// you have to use optional chaining now 
Creator().create?()