Just learning Swift, coming from PHP. I'm trying to figure out if you can do deeply nested arrays in Swift. Here's a PHP example of what I'm talking about:
$myArray = array(
"motorcycles" => array ("Honda", "Ducati", "Yamaha"),
"cars" => array(
"sedans" => array("Jetta", "Taurus", "Impala"),
"sport" => array("Porsche", "Ferarri", "Corvette"),
"trucks" => array (
"shortbed" => array("Ford F150", "Dodge Ram 1500"),
"longbed" => array(
"standardCab" => array("Ford F350", "Dodge Ram 2500"),
"crewCab" => array("Ford F350", "Dodge Ram 2500")
)
)
)
);
Swift dictionary is made of two generic types: Key (which has to be Hashable ) and Value. An entry can be made by providing a key and its value. A value can be retrieved by providing a key which has been inserted before. A entry can be deleted by providing a key.
Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.
Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.
Yes, in Swift that would be:
let myArray = [
"motorcycles": ["Honda", "Ducati", "Yamaha"],
"cars": [
"sedans": ["Jetta", "Taurus", "Impala"],
"sport" : ["Porsche", "Ferarri", "Corvette"],
"trucks" : [
"shortbed" : ["Ford F150", "Dodge Ram 1500"],
"longbed" : [
"standardCab":["Ford F350", "Dodge Ram 2500"],
"crewCab":["Ford F350", "Dodge Ram 2500"]
]
]
]
]
Reading values from such a structure can be a bit difficult though, since Swift has difficulty discerning the types. To get the standardCab
vehicles, you can do:
if let trucks = myArray["cars"]?["trucks"] as? [String:AnyObject] {
if let standardCab = trucks["longbed"]?["standardCab"] as? [String] {
println(standardCab)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With