你如何从字符串中创建变量?

时间:2016-02-03 12:39:17

标签: swift variables

我希望能够将String转换为变量名,然后使用它来调用另一个Swift文件中的变量。

//ViewController.swift
var hireTypes = ["school", "council", "national"]

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  var variableFromString = "\(hireTypes[indexPath.row])Data"

  var data = FullData.variableFromString
  print("The data from selected row is \(data)")
}


//FullData.swift
static var schoolData = [
"name": "School",
"warningMessageOne": "Please check system value",
"warningMessageThree": "May or June",
"warningMessageTwo": "Check hire fits in with morning and afternoon school runs"
]

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

static var nationalData = [
"name": "National",
"warningMessageOne": "Please check system value",
"warningMessageThree": "Aug or June",
"warningMessageTwo": "Check hire fits in with morning and afternoon school runs"
 ]

我会使用数组来保存这些数据,但Xcode会发出警告,我需要降低数组的复杂性。

2 个答案:

答案 0 :(得分:1)

简短回答:你做不到。在编译时创建和评估变量名称。

有一些解决方法。其中一个是传递索引并使用切换表达式。

//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 = [...]

或者更容易

//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 = [...]

答案 1 :(得分:1)

更好的选择是将字符串用作字典中的键以获取值。

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"
 ],
 .....
]

然后以

的形式访问数据
var data = FullData.dataDictionary[variableName]