Create array of strings using for-in in Swift

前端 未结 3 1795
谎友^
谎友^ 2021-01-14 05:54

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 ca

相关标签:
3条回答
  • 2021-01-14 06:38

    Here is the solution. You first need to initialize an empty string array before the for loop. You then iterate from 1 to 13, not 0 to 13 since it will include 0. You then append the string to the array. Your string formatting was incorrect so notice the way to format it in Swift.

    var cardNamesArray = [String]()
    
    for i in 1...13 {
        cardNamesArray.append("card\(i)")
    }
    
    0 讨论(0)
  • 2021-01-14 06:48

    If I understand the answer correctly, this is the solution:

    var cardNamesArray: [String] = []
    for i in 0...13 {
        cardNamesArray.append("card\(i)")
    }
    

    You need to initialise the array once in your program (before filling it), then fill it in for loop.

    You also can init your array this way:

    var cardNamesArray = [String](count: 14, repeatedValue: "")
    

    This will allocate memory for 14 items of the array, which is better than calling .append() many times.

    var cardNamesArray = [String](count: 14, repeatedValue: "")
    for i in 0...13 {
        cardNamesArray[i] = "card\(i)"
    }
    
    0 讨论(0)
  • 2021-01-14 06:58

    Using map() this could be written:

    var cardNamesArray = (0...13).map{"card\($0)"}
    
    0 讨论(0)
提交回复
热议问题