I currently pass a string value from one WKInterfaceController
to another using contextForSegueWithIdentifier
like so:
override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
if segueIdentifier == "segueDetails" {
return self.string1
}
// Return data to be accessed in ResultsController
return nil
}
And then on the destination WKInterfaceController
I do the following:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if let val: String = context as? String {
self.label.setText(val)
} else {
self.label.setText("")
}
// Configure interface objects here.
}
However I want to pass multiple values, using two additional properties with string values called string2
and string3
.
How can I pass additional string values to the WKInterfaceController
?
Swift has three collection types: Array
, Dictionary
, and Set
.
Passing the context as an array of strings:
...
if segueIdentifier == "segueDetails" {
return [string1, string2, string3]
}
func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
if let strings = context as? [String] {
foo.setText(strings[0])
bar.setText(strings[1])
baz.setText(strings[2])
}
}
Passing the context as a dictionary:
...
if segueIdentifier == "segueDetails" {
return ["foo" : string1, "bar" : string2, "baz" : string3]
}
func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
if let strings = context as? [String: String] {
foo.setText(strings["foo"])
bar.setText(strings["bar"])
baz.setText(strings["baz"])
}
}
Personally, I prefer using a dictionary, as the array approach would be a bit more fragile if the caller ever changed the order or the number of strings.
Either way, add necessary checks to make your code robust.