Reputation: 12216
My end goal is to pass the desired array to a function. The problem is the array name depends on the situation. It may be 1 of 30 names.
I have about 30 arrays all named "default_SomeName". Now the previous VC passes the SomeName value. Based on that value, my goal is to pass one of the 30 arrays to a function. Yet, dynamic references are apparently not easy.
I've tried:
var someName: String! //Passed from presenting VC
let desiredArray = "default_" + someName
myFunction(desiredArray)
But I get:
Cannot convert value of type 'String' to expected argument type [String]
Anyone know how to do this?
Upvotes: 0
Views: 55
Reputation: 12216
Well, since there didn't seem to be an easy way, I decided to go with a sure-fire, clear way!
This switch is as basic as it gets. It takes someName, matches it to a case, and they all run the same function but an array specific to that someName value.
func passArrayToFunc () {
switch someName {
case "somename1":
funcThatNeedsArray(someArray1)
case "someName2":
funcThatNeedsArray(someArray2)
case "someName3":
funcThatNeedsArray(someArray3)
case "someName4":
funcThatNeedsArray(someArray4)
case "someName5":
funcThatNeedsArray(someArray5)
case "someName6":
funcThatNeedsArray(someArray6)
case "someName7":
funcThatNeedsArray(someArray7)
case "someName8":
funcThatNeedsArray(someArray8)
default:
print("No matches")
}
Upvotes: 0
Reputation: 115104
You can use a dictionary to associate each dictionary with it's name. Dictionaries are explained in the Apple Swift book, but generally you would do something like this:
var dictionary=[String:[Int]]()
dictionary["default_1234"]=[1,2,3,4]
dictionary["default_5678"]=[5,6,7,8]
let suffix="1234"
print(dictionary["default_\(suffix)"])
In this case I have used an array of Int, but you can have any array type
Upvotes: 2