在Swift中可以吗?如果不是,那么是否有解决方法?
当前回答
下面是一个使用委托模式的具体示例。
设置您的协议:
@objc protocol MyProtocol:class
{
func requiredMethod()
optional func optionalMethod()
}
class MyClass: NSObject
{
weak var delegate:MyProtocol?
func callDelegate()
{
delegate?.requiredMethod()
delegate?.optionalMethod?()
}
}
将委托设置为类并实现协议。请注意,不需要实现可选方法。
class AnotherClass: NSObject, MyProtocol
{
init()
{
super.init()
let myInstance = MyClass()
myInstance.delegate = self
}
func requiredMethod()
{
}
}
重要的一点是,可选方法是可选的,在调用时需要“?”。提到第二个问号。
delegate?.optionalMethod?()
其他回答
这里有一个非常简单的例子,只适用于swift类,而不适用于结构或枚举。 注意,协议方法是可选的,有两个级别的可选链接。 同样,采用协议的类在声明中需要@objc属性。
@objc protocol CollectionOfDataDelegate{
optional func indexDidChange(index: Int)
}
@objc class RootView: CollectionOfDataDelegate{
var data = CollectionOfData()
init(){
data.delegate = self
data.indexIsNow()
}
func indexDidChange(index: Int) {
println("The index is currently: \(index)")
}
}
class CollectionOfData{
var index : Int?
weak var delegate : CollectionOfDataDelegate?
func indexIsNow(){
index = 23
delegate?.indexDidChange?(index!)
}
}
与最初的问题有点偏离主题,但它建立在安托万的想法上,我想它可能会帮助到一些人。
您还可以为具有协议扩展的结构设置可选的计算属性。
您可以将协议上的属性设置为可选的
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 3.0中
@objc protocol CounterDataSource {
@objc optional func increment(forCount count: Int) -> Int
@objc optional var fixedIncrement: Int { get }
}
这会节省你的时间。
在协议中定义函数并为该协议创建扩展,然后为您想要作为可选使用的函数创建空实现。
下面是一个使用委托模式的具体示例。
设置您的协议:
@objc protocol MyProtocol:class
{
func requiredMethod()
optional func optionalMethod()
}
class MyClass: NSObject
{
weak var delegate:MyProtocol?
func callDelegate()
{
delegate?.requiredMethod()
delegate?.optionalMethod?()
}
}
将委托设置为类并实现协议。请注意,不需要实现可选方法。
class AnotherClass: NSObject, MyProtocol
{
init()
{
super.init()
let myInstance = MyClass()
myInstance.delegate = self
}
func requiredMethod()
{
}
}
重要的一点是,可选方法是可选的,在调用时需要“?”。提到第二个问号。
delegate?.optionalMethod?()
推荐文章
- 为什么Swift的编译时间这么慢?
- iPhone上UIView和UILabels的渐变
- 如何测试等价的Swift枚举与相关的值
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- 在Swift中转换Float为Int
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 我如何在Swift中声明一个弱引用数组?
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?