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

Ria*_*iaz 3 delegates protocols swift

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

Qby*_*yte 6

虽然您可以@objc在Swift 2中使用,但您可以添加默认实现,而不必自己提供该方法:

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()
Run Code Online (Sandbox Code Playgroud)

但是在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?()
Run Code Online (Sandbox Code Playgroud)


Rol*_*som 5

要使用可选方法,请使用标记协议 @objc

@objc protocol MyProtocol {

    optional func someMethod();

}
Run Code Online (Sandbox Code Playgroud)

文档所述.