无法使用类型为(String,Int)的索引对类型为[(String,Int)]的值进行下标操作 Swift 2

4
我正在学习iOS开发,最近在尝试操作一个元组数组时遇到了问题。
我收到了以下错误消息:
“Cannot subscript a value of type '[(String, Int)]' with an index of type '(String, Int)'”
生成此错误的代码如下:
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
}

这是餐厅数组:
var restraunts: [(String, Int)] = [("Dallas BBQ", 3), ("Chicken Express", 4), ("Starbucks", 5)]

谢谢你提前帮忙。

1个回答

4

In

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

i2 不是索引,而是遍历数组 elements 的元素,即它是一个 (String, Int) 元组。你可能想要的是:

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

额外说明:

  • The variable

    var i2 = 0
    

    is not used at all, i2 in the for-loop is a new variable whose scope is restricted to the loop.

  • The variables filteredRestraunts and justStrings are not initialized, so this should cause additional compiler errors.

  • Both loops can be replaced by a more functional approach using filter and map:

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

    Which of course could be combined to

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

感谢您的帮助。我修复了作用域警告,并初始化(并立即清空)了数组,现在应用程序可以正常工作了。我以前见过使用map和filter函数,但仍然不知道它们是如何工作的(甚至不知道如何使用它们)。再次感谢您的帮助,这个错误困扰了我整整一周。 - Brandon Bradley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接