将array.count转换为String

时间:2016-03-08 13:19:09

标签: arrays swift

我需要将array.count转换为计数的String值,即 array.count = 5应返回[" 0"," 1"," 2"," 3"," 4&# 34]

我已经尝试了

var strRow = array.map { String($0) }
return strRow

但它没有按照预期的方式运作。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

尝试

return Array(0...array.count)

如果你想要字符串数组,那么只需映射它 Array(0...array.count).map{String($0)}

答案 1 :(得分:1)

试试这个(提示在代码注释中):

var array = [1, 2, 3, 4, 5] // array.count = 5
var stringArray = [String]()

// 0 ... array.count to go from 0 to 5 included
for index in 0 ... array.count {
    // append index with cast it to string
    stringArray.append(String(index))
}

print(stringArray)
// result -> ["0","1","2","3","4","5"]

答案 2 :(得分:1)

在你的问题中,你举一个例子,计数5的数组应该转换为["0","1","2","3","4","5"],这是一个6计数的数组,你确定这是你需要的吗?我假设您希望将5计数数组转换为["0","1","2","3","4"],如果我错了,请在评论中纠正我。

以下是我建议的解决方案:

let array = [5,5,5,5,5] // count 5

let stringIndices = array.indices.map(String.init)
// ["0", "1", "2", "3", "4"]