Swift 中让一个属性是一个类型又采纳一个协议

如题, 比如

@protocol A <NSObject>
@end

@interface B : UIView
@property UIView C<A> *c;
@end

这个代码用swift怎么实现

protocol A {
}

class B: UIView {
    //var c: C, A
    //var c: protocol<C,A>
    // 上面两种都不行
}

在线等...

阅读 3.9k
2 个回答

在 Swift 中,如果是原生类型(如:Int、String)的话,通过 extension 让原生类型遵守新 Protocol。
如果是自定义类型,就直接遵守即可。

具体示例代码如下:

protocol A { }

class B: UIView {
    var c1: C
    // or
    var c2: Int
}

class C: A { }

extension Int: A { }
新手上路,请多包涵
import UIKit

class ViewController: UIViewController {
    
    var po:(UIView&TestPol)!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        po = TestCl()
    }
}
protocol TestPol {
    
}
class TestCl:UIView, TestPol {
    
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进