How do you make a variable from a string?

后端 未结 2 768
天命终不由人
天命终不由人 2021-01-27 05:49

I want to be able to convert a String into a variable name and then use it to call a variable in another Swift file.

//ViewController.swift
var hireTypes = [\"sc         


        
相关标签:
2条回答
  • 2021-01-27 06:30

    Short answer: You can't do that. Variable names are created and evaluated at compile time.

    There are a few workarounds. One of them is passing the index and using a switch expression.

    //ViewController.swift
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
      var data = FullData.data(indexPath.row)
      print("The data from selected row is \(data)")
    }
    
    //FullData.swift
    
    static func data(index : Int) -> [String:String] {
      switch index {
      case 0: return FullData.schoolData
      case 1: return FullData.councilData
      case 2: return FullData.nationalData
      default: return [String:String]()
      }
    }
    
    static var schoolData = [...]
    static var councilData = [...]
    static var nationalData = [...]
    

    or still easier

    //ViewController.swift
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
      var data = FullData.data[indexPath.row]
      print("The data from selected row is \(data)")
    }
    
    //FullData.swift
    
    static var data : [[String:String]] {
       return [FullData.schoolData, FullData.councilData, FullData.nationalData]
    }
    
    static var schoolData = [...]
    static var councilData = [...]
    static var nationalData = [...]
    
    0 讨论(0)
  • A better option is to use the string as a key into a dictionary to get the values.

    E.g.

    static var dataDictionary = [
    "school" : [
        "name": "School",
        "warningMessageOne": "Please check system value",
        "warningMessageThree": "May or June",
        "warningMessageTwo": "Check hire fits in with morning and afternoon school runs"
     ],
    "council" : [
        "name": "Council",
        "warningMessageOne": "Please check system value",
        "warningMessageThree": "Aug or June",
        "warningMessageTwo": "Check hire fits in with morning and afternoon school runs"
     ],
     .....
    ]
    

    Then access the data as

    var data = FullData.dataDictionary[variableName]
    
    0 讨论(0)
提交回复
热议问题