iOS cannot convert [String:Any?] to [String] How to convert? - ios

I'm rushing a project and am not able to research to find the answer. I hope I can get some help on this.
var tt: Array<[String:Any]> = []
var forpickarray: [String] = []
Error: cannot convert [String:Any?] to [String]
for index in 1...self.tt.count {
var arr: [String] = self.tt[index-1]
forpickarray.append(self.tt[index-1])
}
I am trying to get the value- Just the listname
[["total": 2, "listName": Testing, "listid": 1], ["total": 1, "listName": Yeeea, "listid": 2]]

Oh, just seen your edit. Helps a lot.
To get the value of the listName from each dictionary you can do like this...
forPickArray = tt.flatMap { $0["listName"] }
Rename your variables to have sensible names. tt is not a sensible name. I have no idea what it is :D

within your for-loop, are you trying to extract keys from the dictionary and convert it to an array? then you need to do the following:
var arr: [String] = Array(tt[index-1].keys)
forpickarray.append(contentsOf: arr)
Because tt is an array of dictionary, each element in tt could have many keys

Please use native Swift syntax rather than ugly Objective-cish code.
A loop is not needed at all:
forpickarray = tt.flatMap{ $0["listName"] as? String }
Even if a loop was required there is a much more efficient way than a (zero!)index-based for loop:
for item in tt {
forpickarray.append(item)
}

Related

Swift 3: how to sort Dictionary's key and value of struct

This is my Struct,by Swift 3. I know the Dictionary is not stored sequence like an Array and that is my problem. I want to get my Dictionary sequence as I set in ViewArray. I can get the ctC Dictionary, but how can i sort the keys or values as i set in ViewArrayplease and appreciate the help.
struct CTArray {
var ctname: String
var ctkey: String
var ctC: [String:String]
}
var ViewArray:[CTArray] = []
ViewArray += [CTArray(ctname: "kerish", ctkey: "KH", ctC: ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"])]
ViewArray += [CTArray(ctname: "tainers", ctkey: "TNN", ctC: ["letGor":"one", "washi":"testing", "monk":"lasth"])]
ViewArray += [CTArray(ctname: "techiu", ctkey: "TCU", ctC: ["22":"tt", "wke":"303", "lenth":"highest"])]
i want to show them in my TableView Cell sorted like these:
the ViewArray[0].ctC.key sorted like [mon, kis, Bat, orlno]
the ViewArray[1].ctC.key sorted like [letGor, washi, monk]
the ViewArray[2].ctC.value sorted like [tt, 303, highest]
It is not clear to me what you are asking, but I'll offer this in case it helps.
I know the Dictionary is not stored sequence like an Array and that is my problem.
If you want to access a dictionary by a certain order of its keys then you can create an array of just the keys in the order you required and use that to access the dictionary. An example is probably easier to follow:
Starting with one of your dictionaries:
let dict = ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"]
print(dict)
this output:
["Bat": "Best", "kis": "aone", "orlno": "bOne", "mon": "Apple"]
which is not what you want. Now introduce a key array and use that to access the dictionary:
let keyOrder = ["mon", "kis", "Bat", "orlno"]
for key in keyOrder
{
print("\(key): \(dict[key]!)")
}
this outputs:
mon: Apple
kis: aone
Bat: Best
orlno: bOne
which is the order you wish.
The same idea can be used anywhere you want to use/show/etc. the keys in a particular order, by using the keyOrder array as part of dictionary access you are making it appear as though the dictionary entries are "stored in sequence" as you put it.
HTH
var object1 = viewArray[0].ctC.flatMap({$0.key})
var object2 = viewArray[1].ctC.flatMap({$0.key})
var object3 = viewArray[2].ctC.flatMap({$0.value})
print(object1)
print(object2)
print(object3)
Outputs:
["Bat", "kis", "orlno", "mon"]
["letGor", "monk", "washi"]
["highest", "tt", "303"]

Add whole emoji list from dictionnary to a string array

I have a function which add classical emoji to a string
var emojiList: [String] = []
func initEmoji() {
for c in 0x1F601...0x1F64F{
self.emojiList.append(String(describing: UnicodeScalar(c)!))
}
}
I would like to use other pod with Emoji, like Emoji-Swift or SwiftEmoji
I don't know how to append my emojiList array with all those new Emoji.
Could someone kindly tell me how to do ?
It might be easy, but I'm stuck ..
Thanks !
The solution (swift 3)!
var emojiDictionary = String.emojiDictionary
for (myKey,myValue) in emojiDictionary {
self.emojiList.append(myValue)

Comparing two arrays in swift and removing elements with specific fields that don't match

I have two arrays:
var packages = [SAPackage]()
var inappProducts = [SKProduct]()
The SAPackage object in the packages array has a String var titled sku. TheSKProduct object in the inappProducts array has a String var titled productIdentifier. What I want to do is remove any object in the packages array that doesn't have a sku String that matches any objects productIdentifier String in the inappProducts array. Is there anyway to go about this? Thought about using sets to find an intersection however I cannot examine individual object fields doing this just whole objects. Any pointers on this would be greatly appreciated!
You can use this code to filter those packages whose "sku" exist in inappProducts, SKProducts,
let filteredPackages = packages.filter { package in
return inappProducts.contains { product in
product.productIdentifier == package.sku
}
}
You can use the filter function of Swift.
Here a simple example:
let dic1 = ["bear","cat","dog","fish"]
let dic2 = ["horse","cat","dog","bird"]
let f = dic1.filter{dic2.contains($0)}
// ["cat", "dog"]

"Extract" array from dictionary in swift

I'm pretty new to Swift and need your help on a (probably) pretty basic problem.
I have a dictionairy:
var dict = ["title" : "Title", "Features" : ["feat1", "feat2", "feat3"], ...]
I can create a string from it like so:
var headline = dict["title"]! as string
but I couldn't manage to create an array. I tried in various combinations:
var features = dict["Features"]
var features = dict["Features"]! as Array
var features: Array = dict["Features"]
So please enlighten me! How do create an array? Is it possible at all?
You should specify the type for the array. Either
let features = dict["Features"] as [String]
or
let features = dict["Features"] as Array<String>
See the discussion of collection types in The Swift Language.
Your problem is that you don't have a type for the array. You describe the type of an array in swift by putting the type name in brackets. In your case, this will be [String]. Thus, your code should be var features = dict["Features"] as [String] for a mutable array, or use let for an immutable array. Hope this helps.

How to create an array in an array, then check if it contains a string. (SWIFT)

What's the correct way of creating an array of strings, and have lots of them in a array?
So far I tried this
var arrayInArray = [[String]]()
Then I appended string arrays into "arrayInArray". And tried checking if it contained a specific string by doing
if arrayInArray[indexPath.row].containsObject(PFUser.currentUser().username)
and the error is [(String)] does not have a member named 'containsObject'.
Whats the correct way of doing this?
Use find:
var arrayInArray = [[String]]()
arrayInArray += [["Hey", "Ho"]]
arrayInArray += [["Yo", "Yeah"]]
let ix = find(arrayInArray[0], "Ho") // Optional(1), the right answer
Or contains:
let ok = contains(arrayInArray[0], "Ho") // true, the right answer

Resources