2016-03-26 43 views
0

爲什麼我使用Array.contains(AnyObject)來檢查此數組中是否存在結構對象。它使錯誤:「無法轉換的...拋型 - >布爾」Swift:數組包含(AnyObject)錯誤無法轉換類型...... throw - > Bool

struct DecorationPatternsData { 
    let patternImageName: String 
    init(patternImageName: String) { 
     self.patternImageName = patternImageName 
    } 
} 
var decorationPatterns : [DecorationPatternsData] = [DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif")] 

var pickedDecorationPattern : DecorationPatternsData? = nil 

... 

if (pickedDecorationPattern != nil) { 
    if (decorationPatterns.contains(pickedDecorationPattern)) { 
     // Error: Cannot convert type of ... throw -> Bool 
    } 
} 

回答

0
... 

if let pickedDecorationPattern = pickedDecorationPattern { 
    if decorationPatterns.contains(pickedDecorationPattern) { 
     // Error: Cannot convert type of ... throw -> Bool 
    } 
} 
2

那是因爲你的DecorationPatternsData不符合Equatable這是contains(_:)工作的要求。


解決方案1:

extension DecorationPatternsData: Equatable { } 

func ==(lhs: DecorationPatternsData, rhs: DecorationPatternsData) -> Bool { 
    return lhs.patternImageName == rhs.patternImageName 
} 

現在DecorationPatternsData符合Equatable所以你可以使用:

if let pickedDecorationPattern = pickedDecorationPattern { 
    if decorationPatterns.contains(pickedDecorationPattern) { 
    // Your code 
    } 
} 

解決方案2:

if decorationPatterns.contains({ $0 == pickedDecorationPattern }) { 
    // Your code 
} 

這裏您使用封閉來比較元素,返回一個布爾值contains(_:)

相關問題