如何在swift可选中创建协议方法?

时间:2015-08-20 12:22:12

标签: swift delegates protocols

如何在swift可选中创建协议方法?现在似乎需要协议中的所有方法。还有其他工作吗?

2 个答案:

答案 0 :(得分:6)

虽然您可以在Swift 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()

但是在Swift 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?()

答案 1 :(得分:5)

要使用可选方法,请使用@objc

标记协议
@objc protocol MyProtocol {

    optional func someMethod();

}

the documentation中所述。