在Swift中使用for-in创建字符串数组 [英] Create array of strings using for-in in Swift
问题描述
我正在学习Swift并找到了一个精彩的教程,其中解释了如何创建纸牌游戏。重点是我们使用14张牌卡片,图像文件名为 card0,card1 ...... 等。
I'm learning Swift and found one wonderful tutorial where explained how to create card game. Point is that we use 14 cards with card images and image files are named card0, card1... etc.
所以,我们必须使用这些文件名创建字符串数组。老师用硬编码来做就好了
So, we have to create array of strings with these filename. Teacher does it with hardcoding like
var cardNamesArray:[String] = ["card1","card2","card3","card4","card5","card6","card7","card8","card9","card10","card11","card12","card13"]
我想用for-in做。但当我尝试这样做时:
I want to do it with the for-in. But when I try to do like this:
for i in 0...13 {
var cardNamesArray:String = [String(format: "card%i", i)]
}
I在XCode上获取错误,因为....预期声明。
I get error in XCode on line with for.... "Expected declaration".
请你指出我错在哪里,或者有其他方法可以做到。
Could you please point me where I'm wrong or if there is another way to do it.
推荐答案
使用map()可以写成:
Using map() this could be written:
var cardNamesArray = (0...13).map{"card\($0)"}
这篇关于在Swift中使用for-in创建字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!