【问题标题】:swift typealias with protocol issue带有协议问题的快速类型别名
【发布时间】:2017-04-20 06:31:44
【问题描述】:

我想要一种符合我的自定义协议的 UIView。我尝试这样做,但 Xcode 说这不是正确的声明:

typealias ViewThatConformsToProtocol = UIView: MyCustomProtocol

这也不起作用:

typealias ViewThatConformsToProtocol = UIView, MyCustomProtocol

但我不想为此使用子类。有什么办法吗?

附言 通过子类化,我会这样:

class ViewThatConformsToProtocol: UIView, MyCustomProtocol {

}

但我不想使用子类化,因为它违反了我的设计模式(例如,当我只需要知道我的视图支持此协议的行为时,我不希望此视图子类化 ViewThatConformsToProtocol 。并且有时 View1 可以确认 Protocol1 和 Protocol2,但 View2 可以符合 Protocol1 和 Protocol3 - 这只是示例)。在 Objective-C 中你可以很容易地声明 UIView *viewForProtocol = (UIView<MyCustomProtocol> *)view1 ,但在 SWIFT 中这似乎是不可能的,所以我正在寻找绕过

【问题讨论】:

  • 我并没有真正得到你想要达到的目标。如果你“为此使用子类”,你能告诉我们你会怎么做吗?
  • @Sweeper ,我已经添加了代码和cmets。
  • @MaxPevsner ,这篇文章没有帮助
  • 所以你想要一个类型别名UIViewUIview 的子类并且它符合MyCustomProtocol?
  • @Sweeper ,只有符合 MyCustomProtocol 的 UIView ,不是 UIView 的子类

标签: ios iphone swift swift-protocols type-alias


【解决方案1】:
typealias DesiredAlias<T> = T where T:MyCustomProtocol

//you can assign type like below
var variableThatConformsToProtocol: DesiredAlias<MyCustomProtocol>

也许那段代码符合您的要求?实际上它接受任何符合MyCustomProtocol的类型,所以它类似于Objective-C中的id&lt;MyCustomProtocol&gt; variableThatConformsToProtocol

【讨论】:

    【解决方案2】:

    实际上@MaxPevsner 的建议是正确的,但并不准确。 你不需要使用typealias,因为所有的魔法都可以做泛型。

    protocol MyCustomProtocol {
        // ...
    }
    
    class MyCustomView: UIView, MyCustomProtocol {
    
    }
    
    class MyClass<T> where T: MyCustomProtocol {
    
        func someFunction<T>(_ value: T) {
            self.property = value
        }
    }
    
    // ...
    let view = MyCustomView()
    let trick = MyClass<MyCustomView>()
    trick.someFunction(view)
    

    它符合您的要求吗?

    【讨论】:

    • 其实没有,因为这里我们不太需要 AnotherCustomProtocol ,因为我需要在 Objective-C UIView *viewForProtocol = (UIView *)view1 中做很多方法(I' m 将 Objective-C 代码转换为 SWIFT)
    【解决方案3】:

    类型别名是特定类型的别名。你要求的是符合一组条件的东西

    鉴于您发布的代码 sn-p

    UIView *viewForProtocol = (UIView<MyCustomProtocol> *)view1 
    

    等效的 swift 代码是

    let viewForProtocol = view1 as? MyCustomProtocol as ? UIView
    

    【讨论】:

    • 猜你有一个 UIView 或 MyCustomProtocol 的句柄。你不能两者兼得
    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多