2017-04-20 56 views
1

我想要一种符合我自定义协议的UIView类型。我尝试做这样的,但Xcode中说,这是不正确的声明:带协议问题的swift typealias

typealias ViewThatConformsToProtocol = UIView: MyCustomProtocol 

这并不工作过:

typealias ViewThatConformsToProtocol = UIView, MyCustomProtocol 

但我不希望使用的子类那。有没有办法做到这一点?

P.S. 采用子类我会这样说:

class ViewThatConformsToProtocol: UIView, MyCustomProtocol { 

} 

但我不希望使用子类,因为这是对我的设计模式(例如,因为当我只需要知道我查看支持的这个行为调查协议,我不希望这个视图继承ViewThatConformsToProtocol,有时View1可以确认Protocol1和Protocol2,但View2可以遵循Protocol1和Protocol3 - 例如)。在Objective-C中,您可以轻松声明UIView *viewForProtocol = (UIView<MyCustomProtocol> *)view1,但在SWIFT中似乎不可能,所以我正在寻找散步

+0

我真的不明白你想达到什么目的。你能告诉我们,如果你“为此使用了子类”,你会怎么做? – Sweeper

+0

@Sweeper,我添加了代码和评论。 –

+0

@MaxPevsner,这篇文章没有帮助 –

回答

0

实际上@ 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) 

它符合您的要求吗?

+0

实际上没有,因为在这里我们不需要AnotherCustomProtocol非常多,因为我需要像在Objective-C中那样做UIView * viewForProtocol =(UIView *)view1在很多方法中(我将Objective-C代码转换成SWIFT) –

+0

@PaulT。更新的代码片段 – Astoria

0

typealias是特定类型的别名。你问的东西,符合一系列条件

鉴于片断您发布

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

代码等效SWIFT代码将

let viewForProtocol = view1 as? MyCustomProtocol as ? UIView 
+0

不,它不会工作,你将只有UIView –

+0

猜你要么有一个UIView或MyCustomProtocol句柄。你不能拥有两个 – Spads

0
typealias DesiredAlias<T> = T where T:MyCustomProtocol 

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

也许这一块代码符合您的要求?其实它需要符合MyCustomProtocol的任何类型,所以它类似于id<MyCustomProtocol> variableThatConformsToProtocolObjective-C