我有一堆是UIViews的類。有些符合特定的協議。我有這些特定的人的數組,但我不能叫:)指數(這個陣列上(該代碼可以被粘貼到一個遊樂場):如何使用[SomeProtocol]的索引(of :)?
import UIKit
protocol ViewWithColor {}
class BlackView: UIView {}
class WhiteView: UIView {}
class BlueView: UIView, ViewWithColor {}
class GreenView: UIView, ViewWithColor {}
class YellowView: UIView, ViewWithColor {}
let blackView = BlackView()
let whiteView = WhiteView()
let blueView = BlueView()
let greenView = GreenView()
let yellowView = YellowView()
let allViews = [blackView, whiteView, blueView, greenView, yellowView]
let viewsWithColorArray: [ViewWithColor] = [blueView, greenView, yellowView]
let index1 = allViews.index(of: blueView)
let index2 = viewsWithColorArray.index(of: blueView)
的錯誤是:
cannot invoke 'index' with an argument list of type '(of: BlueView)'
該函數無法調用,因爲協議ViewWithColor不符合Equatable
。我真的需要實現equatable嗎?或者,還有更好的方法?
太棒了,這有效! –