Search code examples
swiftstringconcatenationvar

Is there a way to concatenate the name of a var in swift?


var object1 = "C_active.scn"
var object86 = "Soap.scn"
var object41 = "image.scn"
var object9 = "NaCl.scn"

Name of different .SCN files

public func addBox(sceneView: ARSCNView) {
let imagePlaneScene = SCNScene(named: "art.scnassets/" + object1)
let imagePlaneNode = imagePlaneScene?.rootNode.childNode(withName: "object1", recursively: true)
imagePlaneNode?.position = positioner

I have a code reader that gives me a number and from that Int I have to place a specific .SCN file. I don't want to add 100 if statements like I do below. Is the some way to concatenate a string with a Int and turn that into a var in swift? (The numbers after each object is the number I receive from my code reader)

if(coding == 1) {
    sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
} else if(coding == 2) {
    sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
} else {
    sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
}

Something like

var("object" + coding) -> coding41 (Var)

Solution

  • Why don't you just use a dictionary to store your file names?

    var object: [Int: String] = [1: "C_active.scn", 9: "NaCl.scn" ...]
    

    When you need a particular filename, just use the number key attached to that string.

    print(object[9]) //Prints "NaCl.scn"