尝试循环遍历Custom类对象的数组

时间:2018-09-11 21:33:24

标签: arrays swift object for-loop

我有一个看起来像这样的数据模块:

class CurrencyModel {
    var currencyName = ""
    var currencyCode = ""
}

我试图遍历所有这些对象并创建一个CurrencyNames数组。

这就是我要这样做的方式:

var currencies = [CurrencyModel]()

override func viewWillAppear(_ animated: Bool) {
    for names in currencies{
        let name = currencies[names].currencyName
        namesArray.append(name)

        print(namesArray)
    }
}

我不断收到此错误:

  

不能用索引为“ CurrencyModel”的下标“ [CurrencyModel]”的值

2 个答案:

答案 0 :(得分:2)

currencies[CurrencyModel]CurrencyModel的数组)。

循环for names in currencies迭代该数组。 names将是数组中每个单独的CurrencyModel对象。

所以这行:

let name = currencies[names].currencyName

应为:

let name = names.currencyName

当然,整个for循环可以替换为一行:

let namesArray = currencies.map { $0.currencyName }

答案 1 :(得分:0)

问题在这里

let name = currencies[names].currencyName

因为currencies是要下标的数组([CurrencyModel]),它需要像currencies[0]这样的整数值,但是您发送names而不是{{1}类型的}

您需要

CurrencyModel

OR

var namesArray = [String]()
override func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  namesArray = currencies.map{$0.currencyName}
}

OR

currencies.forEach { namesArray.append($0.currencyName)}

//

编辑:,然后使用

for names in currencies {  // not perferred 
    namesArray.append(names.currencyName)
}