2015-09-06 132 views
3

我正在學習iOS開發,並且在嘗試操作元組數組時遇到了一個問題。不能用類型爲(String,Int)的索引來下標類型爲[(String,Int)]的值Swift 2

我得到以下錯誤消息:

無法下標類型的 '[(字符串,整數)]' 與類型的索引 '(字符串,整數)'

的值碼生成的情況如下:

justStrings.append(filteredRestraunts[i2].0) 

作爲一個整體的功能是這樣的:

func filterBySliderValue() -> [String] { 
    var filteredRestraunts: [(String, Int)] 
    for var i = 0; i < restraunts.count; i++ { 
     if restraunts[i].1 > Int(starSlider.value) { 
      filteredRestraunts.append(restraunts[i]) 
     } 
     else {filteredRestraunts.append(("", 1))} 
    } 
    var justStrings: [String] 
    var i2 = 0 
    for i2 in filteredRestraunts { 
     justStrings.append(filteredRestraunts[i2].0) 
    } 
    return justStrings 
} 

這是陣列restraunts:

var restraunts: [(String, Int)] = [("Dallas BBQ", 3), ("Chicken Express", 4), ("Starbucks", 5)] 

預先感謝。

回答

3

for i2 in filteredRestraunts { 
    justStrings.append(filteredRestraunts[i2].0) 
} 

i2不是索引,但陣列元件,即 超過迭代它是一個(String, Int)元組。你大概意思是

for i2 in filteredRestraunts { 
    justStrings.append(i2.0) 
} 

補充說明:

  • 變量

    var i2 = 0 
    

    完全不使用,i2在for循環是一個新的變量,其範圍是 限於循環。

  • 變量filteredRestrauntsjustStrings 未初始化,所以這應該會導致其他編譯器錯誤。

  • 兩個循環可以通過使用 filtermap一個功能更強大的方法來取代:

    let filteredRestraunts = restraunts.filter { $0.1 > Int(starSlider.value) } 
    let justStrings = filteredRestraunts.map { $0.0 } 
    

    當然也可以合併到

    let justStrings = restraunts.filter { $0.1 > Int(starSlider.value) }.map { $0.0 } 
    
+0

感謝您的幫助。我修復了範圍警告,並初始化(並立即清空)數組,現在應用程序可以正常工作。我之前已經看到過使用地圖和過濾器函數,但仍然不知道它們是如何工作的(甚至不知道如何使用它們)。再次感謝幫助,我整個星期都遇到了這個錯誤。 –

相關問題