在Swift中可以吗?如果不是,那么是否有解决方法?


当前回答

由于有一些关于如何使用可选修饰符和@objc属性来定义可选需求协议的答案,我将给出一个如何使用协议扩展定义可选协议的示例。

下面的代码是Swift 3.*。

/// Protocol has empty default implementation of the following methods making them optional to implement:
/// `cancel()`
protocol Cancelable {

    /// default implementation is empty.
    func cancel()
}

extension Cancelable {

    func cancel() {}
}

class Plane: Cancelable {
  //Since cancel() have default implementation, that is optional to class Plane
}

let plane = Plane()
plane.cancel()
// Print out *United Airlines can't cancelable*

请注意,Objective-C代码不能调用协议扩展方法,更糟糕的是Swift团队不会修复它。https://bugs.swift.org/browse/SR-492

其他回答

一种选择是将它们存储为可选函数变量:

struct MyAwesomeStruct {
    var myWonderfulFunction : Optional<(Int) -> Int> = nil
}

let squareCalculator =
    MyAwesomeStruct(myWonderfulFunction: { input in return input * input })
let thisShouldBeFour = squareCalculator.myWonderfulFunction!(2)

在Swift 3.0中

@objc protocol CounterDataSource {
    @objc optional func increment(forCount count: Int) -> Int
    @objc optional var fixedIncrement: Int { get }
}

这会节省你的时间。

如何创建可选和必需的委托方法。

@objc protocol InterViewDelegate:class {

    @objc optional func optfunc()  //    This is optional
    func requiredfunc()//     This is required 

}

与最初的问题有点偏离主题,但它建立在安托万的想法上,我想它可能会帮助到一些人。

您还可以为具有协议扩展的结构设置可选的计算属性。

您可以将协议上的属性设置为可选的

protocol SomeProtocol {
    var required: String { get }
    var optional: String? { get }
}

在协议扩展中实现虚拟计算属性

extension SomeProtocol {
    var optional: String? { return nil }
}

现在你可以使用实现或不实现可选属性的结构体

struct ConformsWithoutOptional {
    let required: String
}

struct ConformsWithOptional {
    let required: String
    let optional: String?
}

我还在我的博客上写了如何在Swift协议中执行可选属性,我会不断更新,以防Swift 2发布时情况发生变化。

在Swift 2及以后的版本中,可以添加协议的默认实现。这为协议中的可选方法提供了一种新的方式。

protocol MyProtocol {
    func doSomethingNonOptionalMethod()
    func doSomethingOptionalMethod()
}

extension MyProtocol {
    func doSomethingOptionalMethod(){ 
        // leaving this empty 
    }
}

这不是一个创建可选协议方法的好方法,但是给了你在协议回调中使用struct的可能性。

我在这里写了一个小总结: https://www.avanderlee.com/swift-2-0/optional-protocol-methods/