2017-03-16 48 views
2

我有一堆是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嗎?或者,還有更好的方法?

回答

4

正如@vadian說,你可以使用index的版本,需要關閉。在這種情況下,您正在查找特定實例,因此請使用index(where: { $0 === blueView })

===操作:

Returns a Boolean value indicating whether two references point to the same object instance.

另外,你需要讓你的協議ViewWithColor一個class協議,因爲===只與類實例的作品。

protocol ViewWithColor: class {} 

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(where: { $0 === blueView }) 
print(index1 ?? -1) 
2 
let index2 = viewsWithColorArray.index(where: { $0 === blueView }) 
print(index2 ?? -1) 
0 
+0

太棒了,這有效! –

3

您可以使用封閉語法並檢查類型:

let index1 = allViews.index(where: {$0 is BlueView}) 
let index2 = viewsWithColorArray.index(where: {$0 is BlueView}) 
+0

好主意,但不會在我的情況下工作。對於index2,我不是在尋找所有BlueView類型的視圖,而是針對一個特定的實例。在viewsWithColorArray中可能有多個BlueView實例 –

+0

無論語法的索引(of)或索引(where)在成功的情況下,您總是會得到匹配條件的第一個**匹配項的索引 – vadian

+0

'index(其中:{$ 0 === blueView})''查找特定實例? – vacawama