ios - Turn a string into a variable -


hello have in loop elements variable being changed , in case "elements" string there corresponding variable out side of in loop has same name string called elements. mean out side there var time = [some,text,words] , theres in loop calls string named "time" , know how convert string in in loop variable how taking off "'s (not simple know) without saying "time"(the variable) instead converting "elements"(which string 'time') string variable. hope clear enough if i'm not making sense i'll try again.

you cannot refer local variables dynamically names in swift. break lot of compiler optimizations type safety if could.

you can refer object properties names if class conforms key-value coding. example:

class x : nsobject {     let time = ["some", "text", "words"]      func readwordsfromprop(name: string) -> string {         guard let list = self.valueforkey(name) as? [string] else {             return ""         }         var result = ""         word in list {             result += word         }         return result     } }  let x = x() print(x.readwordsfromprop("time")) 

in general, there better ways things in swift using closures don't rely on fragile name-matching. kvc can powerful tool


Comments