How do you make a variable from a string?

后端 未结 2 767
天命终不由人
天命终不由人 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 = [...]
    

提交回复
热议问题