IOS Swift 2 - How to construct multidimensional array - ios

How can I achieve the following output:
rsPool[0][p1] = "123"
rsPool[0][p2] = "234"
rsPool[1][p1] = "abc"
rsPool[1][p2] = "bcd"
I deserialized from JSON output, which has the following data
first dimention > type (1 to 7)
second dimention > p1...P10
value > xxxx
I have tried to create:
var rspool : [Int: String] : []
but I don't know how to add/append to the array.

You define multidimensional array by use square brackets multiple times:
var rspool: [[String]] = [["123", "234"], ["abc", "bcd"]]
print(rspool[0][0])
print(rspool[0][1])
print(rspool[1][0])
print(rspool[1][1])
//123
//234
//abc
//bcd
This is array of arrays of String.
Dynamic array
Usually you use dynamically changed array sizes, by using Array methods like append, insert and removeAtIndex. Lets compose given array from empty array:
var rspool = [[String]]()
rspool.append([String]()) //adding first line; now we can access it by rspool[0]
rspool[0].append("abc")
rspool[0].append("bcd")
//we started from second line for to show example with insert:
rspool.insert([String](), atIndex: 0) //inserting new line as first line
rspool[0].append("123")
rspool[0].append("234")
print(rspool)
//[["123", "234"], ["abc", "bcd"]]
You need always be careful with accessing to this array by indexes, since you can receive "index out of range" exception. You read and overwrite existed values in array directly by indexes:
let veryFirst = raspol[0][0]
raspol[0][0] = "456"
Static array
If you wish manipulate your array only by indexes, aka matrix style, you need to set constant dimensions and initialize all array first. Optional type as element type and repeated values are useful then:
let m = 3
let n = 5
var rspool = [[String?]](count: m, repeatedValue: [String?](count: n, repeatedValue: nil))
Now you can read an write elements by indexes:
rspool[0][0] = "123"
rspool[0][1] = "234"
rspool[1][0] = "abc"
rspool[1][1] = "bcd"
print(rspool)
//[[Optional("123"), Optional("234"), nil, nil, nil], [Optional("abc"), Optional("bcd"), nil, nil, nil], [nil, nil, nil, nil, nil]]
Matrix- style array numerating example:
rspool[2][4] = "END"
for i in 0..<m {
for j in 0..<n {
print("\(rspool[i][j] ?? ".")\t", terminator: "")
}
print()
}
//123 234 . . .
//abc bcd . . .
//. . . . END

Your data seems to be this:
var rsPool = [
[
"p1": "123",
"p2": "234"
],
[
"p1": "abc",
"p2": "bcd"
]
]
which is of type [Dictionary<String, String>]
So the declaration should be:
var rsPool: [[String:String]]
Here's Playground reference:

Related

How to add a text prefix to an array on Swift?

Right now I have a array that when printed just displays what number I submitted. I would like the word "car" to be in front of every array number. For example: I enter 1 and 2 in the array. When the array is called it would look like [car 1, car 2] not [1,2].
I have added my array variable and what I am calling to print the array:
var arrayOfInt = [Int]()
label.text = String(describing: arrayOfInt)
Try this:
let arrayOfInt: [Int] = [1, 2]
let cars = arrayOfInt.map { "car \($0)" }
as a result, the cars array will be:
["car 1", "car 2"]
finally, convert to string as before:
label.text = String(describing: cars)
The Array.map function returns an array containing the results of mapping the given closure over the array's elements. In other words, it tranforms one array into another one by applying the specified function on each element.

How to append associative array elements in Swift

How do I create and append to an associative array in Swift? I would think it should be something like the following (note that some values are strings and others are numbers):
var myArray = []
var make = "chevy"
var year = 2008
var color = "red"
myArray.append("trackMake":make,"trackYear":year,"trackColor":color)
The goal is to be able to have an array full of results where I can make a call such as:
println(myArray[0]["trackMake"]) //and get chevy
println(myArray[0]["trackColor"]) //and get red
Simply like this:
myArray.append(["trackMake":make,"trackYear":year,"trackColor":color])
Add the brackets. This will make it a hash and append that to the array.
In such cases make (extensive) use of let:
let dict = ["trackMake":make,"trackYear":year,"trackColor":color]
myArray.append(dict)
The above assumes that your myArray has been declared as
var myArray = [[String:AnyObject]]()
so the compiler knows that it will take dictionary elements.
I accept above answer.It is good.Even you have given correct answer,I like to give simplest way.The following steps are useful,if you guys follow that.Also if someone new in swift and if they go through this,they can easily understand the steps.
STEP 1 : Declare and initialize the variables
var array = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()
var make = "chevy"
var year = 2008
var color = "red"
STEP 2 : Set the Dictionary(adding keys and Values)
dict["trackMake"] = make
dict["trackYear"] = year
dict["trackColor"] = color
println("the dict is-\(dict)")
STEP 3 : Append the Dictionary to Array
array.append(dict)
println("the array is-\(array)")
STEP 4 : Get Array values to variable(create the variable for getting value)
let getMakeValue = array[0]["trackMake"]
let getYearValue = array[0]["trackYear"]
let getColorValue = array[0]["trackColor"]
println("the getMakeValue is - \(getMakeValue)")
println("the getYearValue is - \(getYearValue)")
println("the getColorVlaue is - \(getColorValue)")
STEP 5: If you want to get values to string, do the following steps
var stringMakeValue:String = getMakeValue as String
var stringYearValue:String = ("\(getYearValue as Int)")
var stringColorValue:String = getColorValue as String
println("the stringMakeValue is - \(stringMakeValue)")
println("the stringYearValue is - \(stringYearValue)")
println("the stringColorValue is - \(stringColorValue)")
STEP 6 : Finally the total output values are
the dict is-[trackMake: chevy, trackColor: red, trackYear: 2008]
the array is-[{
trackColor = red;
trackMake = chevy;
trackYear = 2008;
}]
the getMakeValue is - Optional(chevy)
the getYearValue is - Optional(2008)
the getColorVlaue is - Optional(red)
the stringMakeValue is - chevy
the stringYearValue is - 2008
the stringColorValue is - red
Thank You
This sounds like you are wanting an array of objects that represent vehicles. You can either have an array of dictionaries or an array of vehicle objects.
Likely you will want to go with an object as Swift arrays and dictionaries must be typed. So your dictionary with string keys to values of differing types would end up having the type [String : Any] and you would be stuck casting back and forth. This would make your array of type [[String : Any ]].
Using an object you would just have an array of that type. Say your vehicle object's type is named Vehicle, that would make your array of type [Vehicle] and each array access would return an instance of that type.
If I want to try it with my own statement. Which also I want to extend my array with the data in my dictionary and print just the key from dictionary:
var myArray = ["Abdurrahman","Yomna"]
var myDic: [String: Any] = [
"ahmed": 23,
"amal": 33,
"fahdad": 88]
for index in 1...3 {
let dict: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = myDic[myArray] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(myArray)
// replace back into `data`
myDic[myArray] = existingItems
}

Swift shows nil value for Dictionary type

I have a dictionary of type < String, String>. It can access by index values like dictionary[0]. But i want to access each values in this in a simple way by using the key.
var rows: [Dictionary<String, String>] = []
rows = [..] // assigned some value
var value = rows[0]["id"]
println(rows[0]) // ["id": "2", "name": "Bob", "age": "19"]
println(value) // I get nil value
How can i access by this key format. Any suggestions. Thanks in advance.
I tried to read values from a CSV file. And assigned to rows. It works fine when i print rows[0] it shows the correct value. But on the next line if i print rows[0]["id"] it gives me a nil value. And i tried with manual dictionary like
rows = [["name": "alvin"]]
var value = rows[0]["name"]
println(value) // prints alvin
Whats the difference?
This could happen if your key has a space in it. Consider the following:
var rows: [Dictionary<String, String>] = []
rows = [["id ": "2", "name": "Bob", "age": "19"]] // assigned some value
var value = rows[0]["id"]
println(rows[0]) // ["id": "2", "name": "Bob", "age": "19"]
println(value) // I get nil value
To check your keys, print them out like this to see if there is any space in them:
for key in rows[0].keys {
println("XXX\(key)XXX")
}
prints:
XXXid XXX
XXXageXXX
XXXnameXXX
showing that key id is followed by a space, but age and name are not.

Create Dictionary<String, [SomeStruct]> from [SomeStruct] source-array

var sourceEntries: [Entry] = [entry1, ..., entry14]
var myDict: Dictionary<String, [Entry]> = [:]
for entry in sourceEntries {
if var array = myDict[entry.attribute1] { theArray.append(entry) }
else { myDict[entry.attribute1] = [entry] }
}
I am intending to create a Dictionary, which matches all the objects of the struct "Eintrag" with the same attribute from the source-Array "alleEinträge" to a String containing the value of the shared attribute. For some reason my final Dictionary just matches Arrays of one element to the Strings, although some Arrays ought to contain up to four elements.
The problem is that the array is passed by value (i.e. "copied"), so the array you are writing to when you say array.append is not the array that is "inside" the dictionary. You have to write back into the dictionary explicitly if you want to change what's in it.
Try it in a simple situation:
var dict = ["entry":[0,1,2]]
// your code
if var array = dict["entry"] { array.append(4) }
// so what happened?
println(dict) // [entry: [0, 1, 2]]
As you can see, the "4" never got into the dictionary.
You have to write back into the dictionary explicitly:
if var array = dict["entry"] { array.append(4); dict["entry"] = array }
FURTHER THOUGHTS: You got me thinking about whether there might be a more elegant way to do what you're trying to do. I'm not sure whether you will think this is "more elegant", but perhaps it has some appeal.
I will start by setting up a struct (like your Entry) with a name attribute:
struct Thing : Printable {
var name : String
var age : Int
var description : String {
return "{\(self.name), \(self.age)}"
}
}
Now I will create an array like your sourceEntries array, where some of the structs share the same name (like your shared attribute attribute1):
let t1 = Thing(name: "Jack", age: 40)
let t2 = Thing(name: "Jill", age: 38)
let t3 = Thing(name: "Jill", age: 37)
let arr = [t1,t2,t3]
And of course I will prepare the empty dictionary, like your myDict, which I call d:
var d = [String : [Thing]]()
Now I will create the dictionary! The idea is to use map and filter together to do all the work of creating key-value pairs, and then we just build the dictionary from those pairs:
let pairs : [(String, [Thing])] = arr.map {
t in (t.name, arr.filter{$0.name == t.name})
}
for pair in pairs { d[pair.0] = pair.1 }

How do I get the key at a specific index from a Dictionary in Swift?

I have a Dictionary in Swift and I would like to get a key at a specific index.
var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>()
I know that I can iterate over the keys and log them
for key in myDict.keys{
NSLog("key = \(key)")
}
However, strangely enough, something like this is not possible
var key : String = myDict.keys[0]
Why ?
That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:
let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]
Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:
let firstKey = Array(myDictionary.keys)[0] // or .first
Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.
Swift 3 : Array() can be useful to do this .
Get Key :
let index = 5 // Int Value
Array(myDict)[index].key
Get Value :
Array(myDict)[index].value
Here is a small extension for accessing keys and values in dictionary by index:
extension Dictionary {
subscript(i: Int) -> (key: Key, value: Value) {
return self[index(startIndex, offsetBy: i)]
}
}
You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)
let dict = ["c": 123, "d": 045, "a": 456]
for (index, entry) in enumerate(dict) {
println(index) // 0 1 2
println(entry) // (d, 45) (c, 123) (a, 456)
}
If you want to sort first..
var sortedKeysArray = sorted(dict) { $0.0 < $1.0 }
println(sortedKeysArray) // [(a, 456), (c, 123), (d, 45)]
var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]
then iterate.
for (index, entry) in enumerate(sortedKeysArray) {
println(index) // 0 1 2
println(entry.0) // a c d
println(entry.1) // 456 123 45
}
If you want to create an ordered dictionary, you should look into Generics.
From https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html:
If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:
let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]
SWIFT 3. Example for the first element
let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]
if let firstLang = wordByLanguage.first?.key {
print(firstLang) // English
}
In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:
extension Dictionary {
subscript(i:Int) -> (key:Key,value:Value) {
get {
return self[index(startIndex, offsetBy: i)];
}
}
}
SWIFT 4
Slightly off-topic: But here is if you have an
Array of Dictionaries i.e: [ [String : String] ]
var array_has_dictionary = [ // Start of array
// Dictionary 1
[
"name" : "xxxx",
"age" : "xxxx",
"last_name":"xxx"
],
// Dictionary 2
[
"name" : "yyy",
"age" : "yyy",
"last_name":"yyy"
],
] // end of array
cell.textLabel?.text = Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
Here is an example, using Swift 1.2
var person = ["name":"Sean", "gender":"male"]
person.keys.array[1] // "gender", get a dictionary key at specific index
person.values.array[1] // "male", get a dictionary value at specific index
I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.
My initial thought was to wrap my dictionary in an Array. [[String: UIImage]] but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0. No more converting it to an Array. Just my 2 cents.

Resources