Create a variable in swift with dynamic name

前端 未结 4 971
闹比i
闹比i 2020-12-03 21:34

In swift, in a loop managed by an index value that iterates, I want to create a variable which has the variable name that is a concatenation of \"person_\" and the current l

4条回答
  •  一个人的身影
    2020-12-03 21:59

    In Swift it is not possible to create dynamic variable names. What you are trying to achieve is the typical use case for an Array.

    Create an Array and fill it with your person data. Later, you can access the persons via its index:

    var persons: [String] = []
    
    // fill the array
    for i in 0..<10 {
        persons.append("Person \(i)")
    }
    
    // access person with index 3 (indexes start with 0 so this is the 4th person)
    println(persons[3])  // prints "Person 3"
    

提交回复
热议问题