Create a variable in swift with dynamic name

前端 未结 4 953
闹比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:58

    What you are trying to do is not possible in swift. Variable name is just for human being (Especially in a compiled language), which means they are stripped in compilation phase.

    BUT if you really really want to do this, code generation tool is the way to go. Find a proper code generation tool, run it in build phase.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-03 22:03

    let name = "person_\(index)"

    then add name to a mutable array declared before the loop.

    Something like that?

    0 讨论(0)
  • 2020-12-03 22:11

    One solution is to store all your variables in an array. The indexes for the variables you store in that array will correspond to the index values you're trying to include in the variable name.

    Create an instance variable at the top of your view controller:

    var people = [WhateverTypePersonIs]()

    Then create a loop that will store however many people you want in that instance variable:

    for var i = 0; i < someVariable; i++ {
        let person = // someValue of type WhateverTypePersonIs
        people.append(person)
    }
    

    If you ever need to get what would have been "person_2" with the way you were trying to solve your problem, for example, you could access that person using people[2].

    0 讨论(0)
提交回复
热议问题