So I have a plist with a number of items that I would like to access in my project. The plist is an array of items, which are in turn dictionaries with of type string:string (Item1 -> "name" : "somename", "description" : "somedescription")
I would like to access only the name value of my items, and display in an array. I have managed to retreive all the key-value pairs in my plist with the following code:
let path = Bundle.main.path(forResource: "PlistName", ofType: "plist")
let dict = NSArray.init(contentsOf: URL.init(fileURLWithPath: path!)) as! [[String:String]]
by using print(dict) I am able to get everything printed to the console, however like I said I only want the names of the items in an array.
What confuses me the most is the fact that the dict is equal to an NSArray of type [[String:String]]. I do not understand how an array can be of type String:String. This looks like a dictionary to me. I tried changing NSArray to NSDictionary, but that gives me an error saying
"Cast from 'NSDictionary?' to unrelated type '[[String : String]]' always fails"
I'm also not able to tap into either the key or value of dict.
let oneDict = dict[0]
returns one dictionary, and if you really want an array of one dictionary do this:
let array = [oneDict]
You can extract values for a specific key by using the map or compactMap functions, in this case I use compactMap in case one of the dictionaries doesn't contain a name
let arrayOfDictionaries = [["name": "a", "some": "x"],
["name": "b", "some": "y"],
["some": "z"],
["name": "c"]]
let names = arrayOfDictionaries.compactMap {$0["name"]}
Related
I have an array of strings in Swift. I also have an url and I want to check if this url contains one of the elements contained into this array of strings I have.
So if url.pathComponents.contains("how can I do that?")
I thought at for loop but I was looking at a one line solution if any.
Thanks a lots.
let things = ["aaa", "bbb", "ccc"]
url.pathComponents.contains(where: things.contains)
For example:
let url = URL(string: "https://www.example.com/foo/bar/baz")!
let things = ["aaa", "bbb", "ccc"]
let doesnt = url.pathComponents.contains(where: things.contains) // false
let things2 = ["aaa", "bar", "ccc"]
let does = url.pathComponents.contains(where: things2.contains) // true
To break that down a bit: if you have an array, things, then things.contains is a function that given a thing will return true if it is in things. And such a function is useful as the predicate function for contains(where:), which is a function on collections that will return true if any of the things in the collection satisfy the given predicate function.
Or you could write the predicate as a closure expression like { thing in things.contains(thing) }.
I'm new to coding and this is my first post!
I have created a dictionary in Swift where each individual value is an array.
Ex
1: [0.0443, 0.220832, 0.526799, 0.72147, 0.646954,0.511456,1.00405]
What I need to do is to access the value and store into a different array for data manipulation.
I am having trouble doing this because swift is viewing the array as a single object.
ex. dict[1]!.count will print 1 not 7 (ie. the 7 values)
Is there a way to do this - meaning to get swift to store the value as an array of Doubles?
Thanks.
It would be nice if you shared some code with us. but to access a dictionary of arrays you can do something like this :
let array1 = ["a", "b" , "c"]
let array2 : [Float] = [1.2,2.8,3.4]
let dictionary : Dictionary<String, Any> = ["array1" : array1, "array2" :array2]
var arrayFromDictionary = dictionary["array1"] as! [String]
var array2FromDictionary = dictionary["array2"] as! [Float]
print(arrayFromDictionary[1])
print(array2FromDictionary[2])
the first print call will print out "b" since it is the second member of the array1.
the second print call will print out 3.4 since it is the third member of array2.
does this answer your question ?
I have an array which stores a dictionary. The dictionary has a String for a key, and a Tuple for the value. It looks like this:
var mydict: [String: (key1: String, key2: String)]
I want to initialize this array with a key, and an empty array for a value.
So like this:
var mydict: [String: (key1: String, key2: String)] = ["dict_key1" : []]
each time I try I get errors. any solutions?
You can't initialize a tuple value with an array, because they're two different types. A tuple is a distinct type that has to contain the number of elements you specified for it to contain. So if you declare your dictionary as storing 2-element tuples, you have to store something in it with two elements. So you could initialize your dictionary with something like:
var mydict: [String: (key1: String, key2: String)] = ["dict_key1" : (key1: "", key2: "")]
However, if you want to store an array in the dictionary, I'd suggest you just type the dictionary as such:
var mydict: [String : [String]]
I have a Dictionary which contains an array of fruits and a Double. What I would like to be able to do is access the fruits inside the array.
How can I access items inside the fruits array?
var fruits = ["Apple", "Oranges"]
var fruitDictionary:[String: Any] = ["fruits":fruits, "car":2.5]
print("Dictionary: \(fruitDictionary["fruits"]!)") // output: Dictionary: ["Apple", "Oranges"]
I tried...
print("Dictionary: \(fruitDictionary["fruits"[0]]!)")
and...
print("Dictionary: \(fruitDictionary["fruits[0]"]!)")
But no luck
Thanks
First you need to access the fruits entry of the dictionary and cast it as an array of strings.
From there you can access the elements of the array.
if let array = fruitDictionary["fruits"] as? [String] {
print(array[0])
}
The reason why your attempts did not work is because the values in your dictionary are of type Any, which might not be able to be accessed through a subscript.
G'day,
I'm trying to use a for loop to access the values for the same key within an array of dictionaries in Swift.
For example,
let dictionaryOne = [
"name": "Peter",
"age": "42",
"location": "Milwaukee"]
let dictionaryTwo = [
"name": "Paul",
"age": "89",
"location": "Denver"]
let arrayOfDictionaries = [dictionaryOne, dictionaryTwo]
I'm attempting to create a function using a for loop that will output an array containing the values for location i.e. ["Milwaukee", "Denver"]
I have looked at other responses but I can only find how to access the value for "location" straight from the dictionary itself, which would be cumbersome if there were many different dictionaries rather than just two.
Many thanks for any help you can provide!
You can take advantage of the map method, whose purpose is to loop through the array and transform each element into another type:
arrayOfDictionaries.map { (dict: [String : String]) -> String? in
return dict["location"]
}
The closure passed to the map receives an array element, and returns the transformed value - in your case, it retrieves and returns the value for the location key.
You can also use the compact form:
arrayOfDictionaries.map { $0["location"] }
Note that this method returns an array of optional strings, because the dictionary subscript operator always returns an optional. If you need an array of non optionals, then this is the unsafe version:
let x = arrayOfDictionaries.map { $0["location"]! }
Of course if the value for "location" key doesn't exist for an array element, a runtime exception will be raised.
More info about map at the Swift Standard Template Library
The way I see it, you would populate a new array of Strings from the cities listed before.
var locations = [String]()
for dictionary in arrayOfDictionaries{
locations.append(dictionary["location"]!)
}
println(locations)
There are a few ways you could do this. One is to use key-value coding (KVC):
let locations = (arrayOfDictionaries as NSArray).valueForKey("location") as [String]