热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

声明符合Swift2协议的UIView类型的变量-DeclarevariableoftypeUIViewconformingtoaprotocolinSwift2

IneedtodeclareavariableoftypeUIViewwhichalsoconformstoMyProtocol:我需要声明一个UIView类型的变量,它也

I need to declare a variable of type UIView which also conforms to MyProtocol:

我需要声明一个UIView类型的变量,它也符合MyProtocol:

protocol MyProtocol: class {
    func foobar()
}

class MyClass {
    var myView: UIView! // Error: Cannot specialize non-generic type 'UIView'
}

However I get the compiler error: Cannot specialize non-generic type 'UIView'.

但是我得到了编译器错误:不能专门化非泛型类型'UIView'。

I need to access methods on the variable from UIView and MyProtocol.

我需要从UIView和MyProtocol访问变量的方法。

What is the correct variable declaration to support these requirements?

支持这些要求的正确变量声明是什么?

If it makes any difference, only UIView subclasses will implement the protocol. Currently I add protocol conformance via extensions.

如果它有任何区别,只有UIView子类才会实现该协议。目前,我通过扩展添加协议一致性。

I found this answer: https://stackoverflow.com/a/25771265/233602 but it's not clear if that answer is still the best option going in when writing in Swift 2.

我找到了这个答案:https://stackoverflow.com/a/25771265/233602但不清楚在Swift 2中写这个答案是否仍然是最好的选择。

2 个解决方案

#1


9  

Make your class a generic class as follows,

使您的类成为通用类,如下所示,

protocol MyProtocol: class {
    func foobar()
}

class MyClass {
    var myView: T!
}

The error above says that UIView cannot specialise to protocol MyProtocol, so, the solution here would be to make your class a generic class which takes generic parameter which conforms to MyProtocol and is subclass of UIView.

上面的错误说UIView不能专门用于协议MyProtocol,因此,这里的解决方案是使您的类成为泛型类,它接受符合MyProtocol的泛型参数,并且是UIView的子类。

#2


6  

Probably the best way to solve this is to use a protocol where all UIViews conform to:

解决此问题的最佳方法可能是使用所有UIView遵循的协议:

protocol UIViewType {
    var view: UIView { get }
}

extension UIView: UIViewType {
    var view: UIView { return self }
}

// the variable
var myView: protocol

Use the view property to access UIView specific functionality.

使用view属性可以访问UIView特定的功能。


推荐阅读
author-avatar
手机用户2502902093
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有