2016-11-19 46 views
-2

在swift 3.0中,我想连接字符串(string1 & string2)并使用结果字符串(string3)作为我想访问的数组的名称。使用变量内容作为数组名称

let fruitsArray = ["apple", "orange", "banana"] 
let appleArray = ["red", "green", "yellow"] 

let string1 = "apple" 
let string2 = "Array" 
let string3 = string1 + string2 

let string4 = string3[1] 

当然有错误消息“下标是不可用......) 什么是做到这一点?非常感谢大家的正确方法。

+0

如果您愿意,可以考虑对我提供的答案给予反馈。 – dfri

回答

0

你想要的是能够使用某种形式内省的,但它是一个不好的做法,非常笨拙,无论如何你应该重塑你的数据,例如,使用字典:

let data = [ 
    "fruitsArray" : ["apple", "orange", "banana"], 
    "appleArray": ["red", "green", "yellow"] 
] 

let string1 = "apple" 
let string2 = "Array" 
let string3 = string1 + string2 

if let array = data[string3] { 
    let string4 = array[1] 
    print(string4) 
} else { 
    print("Key not found") 
} 
+0

是的,我明白这个方法,谢谢。但是有没有办法在没有字典的情况下做到这一点? –

+0

任何其他方法都要求你将'fruitArray'和'appleArray'封装在类或结构中。如果你的包装类继承自'NSObject',你可以使用['value(forKey:)'](https://developer.apple.com/reference/objectivec/nsobject/1412591-value)。如果你想要一个纯粹的Swift解决方案,请看[反射](http://nshipster.com/mirrortype/) –

+0

OK。非常感谢你。 –

0

作为@CodeDifferent writes in his/her answer,你可能要考虑重塑你的数据,因为这类型的运行时性能accessi的ng不是很“Swifty”。

但是,如果您只是为了调试而读取数据时感兴趣,则可以使用Mirror结构对拥有数组属性的数据类型执行运行时自检。

例如为:

struct Foo { 
    let fruitsArray = ["apple", "orange", "banana"] 
    let appleArray = ["red", "green", "yellow"] 
} 

func attemptToReadStringArrayProperty(_ name: String, fromFoo foo: Foo) -> [String]? { 
    return Mirror(reflecting: foo).children 
     .flatMap { ($0 ?? name + ".") == name ? ($1 as? [String]) : nil }.first 
} 

/* example usage/debugging */ 
let string1 = "apple" 
let string2 = "Array" 
let string3 = string1 + string2 
let foo = Foo() 

if let strArr = attemptToReadStringArrayProperty(string3, fromFoo: foo) { 
    strArr.forEach { print($0) } 
} /* red 
    green 
    yellow */ 

当然,你可以申请这种方法对于非调试的目的,但我不会推荐它。