如何从字符串中创建变量? [英] How do you make a variable from a string?

查看:29
本文介绍了如何从字符串中创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 = ["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 给出了我需要降低数组复杂度的警告.

I would have used a array for holding this data however Xcode gives the warning that I need to reduce the complexity of the array.

推荐答案

更好的选择是使用字符串作为字典的键来获取值.

A better option is to use the string as a key into a dictionary to get the values.

例如

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]

这篇关于如何从字符串中创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆