在Swift中可以吗?如果不是,那么是否有解决方法?
当前回答
在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/
其他回答
1. 使用默认实现(首选)。
protocol MyProtocol {
func doSomething()
}
extension MyProtocol {
func doSomething() {
/* return a default value or just leave empty */
}
}
struct MyStruct: MyProtocol {
/* no compile error */
}
优势
不涉及Objective-C运行时(好吧,至少没有显式地)。这意味着你可以使结构,枚举和非nsobject类符合它。此外,这意味着您可以利用强大的泛型系统。 当遇到符合这种协议的类型时,您总是可以确保满足所有需求。它总是具体实现或默认实现。这就是“接口”或“契约”在其他语言中的表现。
缺点
For non-Void requirements, you need to have a reasonable default value, which is not always possible. However, when you encounter this problem, it means that either such requirement should really have no default implementation, or that your you made a mistake during API design. You can't distinguish between a default implementation and no implementation at all, at least without addressing that problem with special return values. Consider the following example: protocol SomeParserDelegate { func validate(value: Any) -> Bool } If you provide a default implementation which just returns true — it's fine at the first glance. Now, consider the following pseudo code: final class SomeParser { func parse(data: Data) -> [Any] { if /* delegate.validate(value:) is not implemented */ { /* parse very fast without validating */ } else { /* parse and validate every value */ } } } There's no way to implement such an optimization — you can't know if your delegate implements a method or not. Although there's a number of different ways to overcome this problem (using optional closures, different delegate objects for different operations to name a few), that example presents the problem clearly.
2. 使用@objc可选。
@objc protocol MyProtocol {
@objc optional func doSomething()
}
class MyClass: NSObject, MyProtocol {
/* no compile error */
}
优势
不需要缺省实现。你只需要声明一个可选方法或变量就可以了。
缺点
它要求所有符合要求的类型都与Objective-C兼容,从而严重限制了协议的功能。这意味着,只有继承自NSObject的类才能符合这样的协议。没有结构,没有枚举,没有关联类型。 必须始终通过可选调用或检查符合类型是否实现了可选方法来检查是否实现了可选方法。如果经常调用可选方法,这可能会引入大量样板文件。
您需要在每个方法之前添加可选关键字。 但是,请注意,要使其工作,您的协议必须用@objc属性标记。 这进一步表明该协议将适用于类,但不适用于结构。
这里的其他答案涉及将协议标记为“@objc”,在使用swift特定类型时不起作用。
struct Info {
var height: Int
var weight: Int
}
@objc protocol Health {
func isInfoHealthy(info: Info) -> Bool
}
//Error "Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C"
为了声明能在swift中很好地工作的可选协议,将函数声明为变量而不是func。
protocol Health {
var isInfoHealthy: (Info) -> (Bool)? { get set }
}
然后实现如下协议
class Human: Health {
var isInfoHealthy: (Info) -> (Bool)? = { info in
if info.weight < 200 && info.height > 72 {
return true
}
return false
}
//Or leave out the implementation and declare it as:
//var isInfoHealthy: (Info) -> (Bool)?
}
然后可以使用“?”来检查函数是否已经实现
func returnEntity() -> Health {
return Human()
}
var anEntity: Health = returnEntity()
var isHealthy = anEntity.isInfoHealthy(Info(height: 75, weight: 150))?
//"isHealthy" is true
让我们先来了解一下它们的区别
第一个例子-如果你写UITableViewDataSource,那么你需要强制写两个方法-这是默认协议的快速方式
第二个例子-如果你写UITableViewDelegate,并意识到它不会显示红色错误,请添加所有的委托方法。使用哪种方法取决于你自己。我们可以调用作为可选方法!
让我们通过一个例子来理解
第一种Swift方式默认协议方法
class ContactModel{
var firstname: String?
var lastname: String?
}
protocol ContactDataSource: AnyObject{
func contactConfiguration(contact: ContactModel)
}
class ViewController: ContactDataSource{
func contactConfiguration(contact: ContactModel) {
print(contact)
}
}
第二种方法——可选协议
@objc
class UserModel: NSObject{
var firstname: String = ""
}
@objc protocol UserDataSource{
func contactConfiguration(user: UserModel)
@objc optional func userInfo(user: UserModel)
}
class ViewController: UserDataSource{
func contactConfiguration(user: UserModel) {
print(user)
}
}
注意:如果你能在可选协议中看到,我还没有写userInfo方法,所以这取决于你。这意味着With和不向类添加方法 它工作得很好。-在协议中作为可选方法调用 类声明类和协议 @objc属性,它只与类而不是struct工作!
第三种方法-使用扩展的可选协议
注意:你可以选择Struct或Class
class UserModel{
var firstname: String = ""
}
OR
struct UserModel{
var firstname: String = ""
}
AND
protocol UserDataSource{
func contactConfiguration(user: UserModel)
}
extension UserDataSource{
func userInfo(user: UserModel){}
}
class myview: UserDataSource{
func contactConfiguration(user: UserModel) {
print(user)
}
}
这里有一个非常简单的例子,只适用于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!)
}
}
推荐文章
- 在成功提交我的应用程序后,“太多符号文件”
- 从数组中随机选择一个元素
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- CFNetwork SSLHandshake iOS 9失败
- swift语言中的结构与类
- 我如何在Swift连接字符串?
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- 以编程方式创建segue
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 如何使用Xcode创建。ipa文件?