Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使swift中的协议方法成为可选的?_Swift_Delegates_Protocols - Fatal编程技术网

如何使swift中的协议方法成为可选的?

如何使swift中的协议方法成为可选的?,swift,delegates,protocols,Swift,Delegates,Protocols,如何使swift中的协议方法成为可选的?现在协议中的所有方法似乎都是必需的。还有其他解决方法吗?要使用可选方法,请使用@objc @objc protocol MyProtocol { optional func someMethod(); } 如。所述,虽然您可以在Swift 2中使用@objc,但您可以添加默认实现,而无需自己提供方法: protocol Creatable { func create() } extension Creatable { //

如何使swift中的协议方法成为可选的?现在协议中的所有方法似乎都是必需的。还有其他解决方法吗?

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

@objc protocol MyProtocol {

    optional func someMethod();

}

如。

所述,虽然您可以在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?()

如果我的回答对你有帮助,请投票并接受它。谢谢