【问题标题】:optional delegates with struct types - swift具有结构类型的可选委托 - swift
【发布时间】:2020-03-16 08:00:19
【问题描述】:

我在将协议设置为可选时遇到错误。

方法不能被标记为@objc,因为参数1的类型 无法在 Objective-C 中表示

我的代码:

@objc protocol PopupDelegate : class {
    @objc optional func popupItemSelected(item : PopupItem, identifier : String)
    @objc optional func popupItemMultipleSelected(item : [PopupItem], identifier : String)
}

struct PopupItem : Hashable {
    var name : String
    var id : Int
    var isSelected : Bool

    init(name: String, id: Int, isSelected : Bool = false) {
        self.name = name
        self.id = id
        self.isSelected = isSelected
    }
}
  • 我在 swift 2 中有一个 post 有同样的问题,但由于 结构中不允许继承,我无法实施此解决方案。。 p>

  • 我尝试将@objc 标志添加到我的结构中,但出现以下错误

只有类(及其扩展)、协议、方法、初始化器、 属性,下标声明可以声明为@objc


有没有办法用结构类型实现可选委托?

【问题讨论】:

    标签: ios swift protocols


    【解决方案1】:

    我认为您发布的错误消息是不言自明的,StructObjective-C 运行时中不可用,因此当您使用 @objc 注释协议时,编译器会警告您 struct 不能作为参数传递给这样的协议。

    如何在纯swift中实现可选行为? 官方在 swift 中没有对应的objective-C optional。但是空的默认扩展将帮助您实现相同的行为。

    protocol PopupDelegate {
        func popupItemSelected(item : PopupItem, identifier : String)
        func popupItemMultipleSelected(item : [PopupItem], identifier : String)
    }
    
    extension PopupDelegate {
        func popupItemSelected(item : PopupItem, identifier : String) { }
        func popupItemMultipleSelected(item : [PopupItem], identifier : String) { }
    }
    

    现在向PopupDelegate 确认的人不需要实现方法,因为已经提供了默认实现,并且因为它的空实现几乎与可选相同。

    这种方法的一个警告是,如果您调用 respondsToSelector,这将返回 true,因为存在默认实现,但如果使用可选实现,您将获得适当的响应。

    【讨论】:

    • 感觉就像它的 hack 到 swift。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多