wobuhuicode
V2EX  ›  Swift

Swift 如果定义一个具备某个 协议(Protocol)的 类(class)?

  •  
  •   wobuhuicode · Apr 20, 2021 · 1746 views
    This topic created in 1901 days ago, the information mentioned may be changed or developed.
    class AView : UIView,ProtocolB{
    }
    class BView : UIView,ProtocolB{
    }
    
    let arr : UIView<ProtocolB> 
    

    我的两个子 view 都具备 ProtocolB,我想用一个 UIView 数组去装这两个子 view 的实例。 可以这样写吗?

    2 replies    2021-04-25 01:15:30 +08:00
    finab
        1
    finab  
       Apr 20, 2021
    或者可以这样?
    protocol ProtocolB: UIView {

    }

    class AView: UIView, ProtocolB {

    }
    class BView: UIView, ProtocolB {

    }

    let arr : [ProtocolB]

    arr.first?.backgroundColor = .white
    YYYeung
        2
    YYYeung  
       Apr 25, 2021
    限制协议实现的类型

    ```swift
    protocol ProtocolB where Self: UIView {}

    class AView: UIView, ProtocolB {}

    class BView: UIView, ProtocolB {}

    let arr: [UIView] = [AView(), BView()]
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2695 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:54 · PVG 09:54 · LAX 18:54 · JFK 21:54
    ♥ Do have faith in what you're doing.