Create mutable Dictionary with dynamic value/keys in SWIFT - ios

I need to create a Dictionary with dynamic keys.
At the end I need a Dictionary
I tried to use:
var animDictionary:[String:AnyObject]
for position in 1...10
{
let strImageName : String = "anim-\(position)"
let image = UIImage(named:strImageName)
animDictionary.setValue(image, forKey: strImageName) //NOT WORK
//BECAUSE IT'S NOT A NSMUTABLEDICTIONARY
}
So I tried:
var animMutableDictionary=NSMutableDictionary<String,AnyObject>()
for position in 1...10
{
let strImageName : String = "anim-\(position)"
let image = UIImage(named:strImageName)
animMutableDictionary.setValue(image, forKey: strImageName)
}
But I don't find the how to convert my NSMutableDictionary to a Dictionary. I'm not sure it's possible.
In the Apple doc, I found :
I don't know if it's possible to use it in my case.

Xcode 11 • Swift 5.1
You need to initialize your dictionary before adding values to it:
var animDictionary: [String: Any] = [:]
(1...10).forEach { animDictionary["anim-\($0)"] = UIImage(named: "anim-\($0)")! }
Another option is to use reduce(into:) which would result in [String: UIImage]:
let animDictionary = (1...10).reduce(into: [:]) {
$0["anim-\($1)"] = UIImage(named: "anim-\($1)")!
}

Related

Is there a way to map an array of strings to an array of images?

I'm not sure if this is even possible but lets say we have an array of strings and need to match them up with a corresponding array of images. Like :
["Patriots", "Broncos", "Cowboys"] = [pat.png, bronc.png, cow.png]
I've tried with the map function but it doesn't seem to work:
let footballArray = ["Patriots", "Broncos", "Cowboys"].map({return [pat.png, bronc.png, cow.png] })
Any help solving this issue is appreciated!
You can create dictionary like this from both sequence.
let a = ["Patriots", "Broncos", "Cowboys"]
let b = ["pat.png", "bronc.png", "cow.png"]
var footballDict: [String : String] = [:]
zip(a, b).forEach { footballDict[$0] = $1 }
You can try
let footballArray = [String : String] = ["Patriots" : "pat.png", "Broncos" : "bronc.png", "Cowboys" : "cow.png"]
Or view here
this is how you can add the extension to your strings using .map
let footballArray = ["Patriots", "Broncos", "Cowboys"].map({ (value: String) -> String in
return value + ".png"
If you're talking about how to combine two arrays into one, you can use zip:
struct Team {
let teamName: String
let imageName: String
}
let teamNames = ["Patriots", "Broncos", "Cowboys"]
let imageNames = ["pat.png", "bronc.png", "cow.png"]
let teams = zip(teamNames, imageNames).map { (teamName, imageName) in
Team(teamName: teamName, imageName: imageName)
}
That yields an array of Team objects, built using elements from those two arrays.

How to for loop in userDefaults swift

I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function
let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: heading!)
To get all keys and corresponding values in UserDefaults, you can use:
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
print("\(key) = \(value) \n")
}
In swift 3, you can store and retrieve using:
UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
I think is not a correct way to do.
I suggest you to put your values into a dictionary and set the dictionary into the UserDefaults.
let DictKey = "MyKeyForDictionary"
var userDefaults = UserDefaults.standard
// create your dictionary
let dict: [String : Any] = [
"value1": "Test",
"value2": 2
]
// set the dictionary
userDefaults.set(dict, forKey: DictKey)
// get the dictionary
let dictionary = userDefaults.object(forKey: DictKey) as? [String: Any]
// get value from
let value = dictionary?["value2"]
// iterate on all keys
guard let dictionary = dictionary else {
return
}
for (key, val) in dictionary.enumerated() {
}
If you have multiple Strings, simply save value as array
UserDefaults.standard.set(YourStringArray, forKey: "stringArr")
let arr = UserDefaults.standard.stringArray(forKey: "stringArr")
for s in arr! {
//do stuff
}
Here you are setting the key as heading and the value as description.
You can retrieve the value from userDefaults using UserDefaults.standard.object(forKey:), UserDefaults.standard.string(forKey: ),UserDefaults.standard.value(forKey: ) etc functions.
So its better to save heading and description for 2 different keys may be like
let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: "description")
save.set(heading, forKey: "heading")
And you could retrieve like
let description = UserDefaults.standard.string(forKey:"description")
let heading = UserDefaults.standard.string(forKey:"heading")

What is the data source for filteredUsers should be in my TableViewController?

I am working on iOS project using Swift and I am trying to add a search bar to my TableViewController
This is my code:
the properties part:
var UserNamesArray: NSMutableArray = []
and
var filteredUsers = [UserNamesArray]()
When I add the previous line it give me an error: instance member 'UserNamesArray' cannot used on type 'MyTableVC' .
So this is the problem, what can I put instead of [UserNamesArray]?
viewDidLoad function:
ref.queryOrderedByChild("Job").queryEqualToValue("Programers")
.observeEventType(.Value, withBlock: { snapshot in
if let dict = snapshot.value as? NSMutableDictionary{
print("dict====== \(dict)")
for (key,value) in dict {
let mainDict = NSMutableDictionary()
mainDict.setObject(key, forKey: "userid")
if let dictnew = value as? NSMutableDictionary{
if let metname = dictnew["UserName"] as? String
{
mainDict.setObject(metname, forKey: "UserName")
}
if let metname = dictnew["Details"] as? String
{
mainDict.setObject(metname, forKey: "Details")
}
if let metname = dictnew["Email"] as? String
{
mainDict.setObject(metname, forKey: "Email")
}
}
print("mainDict========= \(mainDict)")
self.UserNamesArray.addObject(mainDict)
}
print("UserNamesArray ==== \(self.UserNamesArray)")
}
self.tableView.reloadData()
})
}
To make it clear, I took a screen shot of values of the variables:
1) dict 2) mainDict 3) UserNamesArray
Please, click here
That what my table view controller look like:
Here
I attempted to make it clear as I can I hope that someone can help.
Thanks in advance!
var filteredUsers = [UserNamesArray]() doesn't work because UserNamesArray is not a valid type, it's just an object.
For example in the syntax var foo = [Bar](), Bar is the type of the objects in the array foo.
So if filteredUsers is meant to hold an array of String objects then what you want is:
var filteredUsers = [String]()

Appending Dictionary to Swift Array

I have this Swift code in which I'm trying to append a Dictionary to Array.
var savedFiles: [Dictionary<String, AnyObject>] = []
var newEntry = Dictionary<String,AnyObject>()
if let audio = receivedAudio?.filePathURL {
newEntry["url"] = audio
}
newEntry["name"] = caption
savedFiles.append(newEntry! as Dictionary<String,AnyObject>)
This gives me an error on last line (in append) Cannot invoke 'append' with an argument list of type '(Dictionary<String, AnyObject>)'
Any idea? I also tried remove force unwrapping as well.
Please try this:
var savedFiles: [[String: AnyObject]] = []
var newEntry: [String: AnyObject] = [:]
if let audio = receivedAudio?.filePathURL {
newEntry["url"] = audio
}
newEntry["name"] = caption
savedFiles.append(newEntry)
Hi just tried on playground its working, only you should know this: audio could be nil any time, in that case this key value pair won't be added in newEntryDictionary.
var savedFilesDictionary = [[String: AnyObject]]()
var newEntryDictionary = [String: AnyObject]()
var receivedAudio = NSURL(string: "/something/some")
if let audio = receivedAudio?.filePathURL {
newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = "some caption"
savedFilesDictionary.append(newEntryDictionary)
As of Swift 4, the correct way to work with dictionaries:
Declare empty dictionary (associative array):
var namesOfIntegers = [Int: String]()
Append to dictionary:
namesOfIntegers[16] = "sixteen"
Check if dictionary contains key:
let key = 16
if namesOfIntegers.keys.contains(key) {
// Does contain array key (will print 16)
print(namesOfIntegers[key])
}
See more, straight from Apple: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
Absolutely no problem:
var savedFiles: [Dictionary<String, AnyObject>] = []
var newEntry = Dictionary<String, AnyObject>()
newEntry["key"] = "value"
savedFiles.append(newEntry)
Although this is the "Swifty"-Style:
var savedFiles = [[String: AnyObject]]()
var newEntry = [String: AnyObject]()
newEntry["key"] = "value"
savedFiles.append(newEntry)
I am using Xcode 7.2.1.
var savedFilesDictionary = [String: AnyObject]()
var newEntryDictionary = [String: AnyObject]()
if let audio = receivedAudio?.filePathURL {
newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = caption
savedFilesDictionary.append(newEntryDictionary)
Try this.

error using valueForKey in swift

Why do I get an error when I used valueForKey... I am using same trick like in objectiveC ...
In ObjectiveC, the code is
self.strSubscribe =[responseObject[#"subscribe"] valueForKey:#"subscribe_ids"];
In Swift , the code is
self.strSubscribe = responseObject["subscribe"].valueForKey["subscribe_ids"] as! String
I declare the variables like
var arraySubCategory : NSMutableArray! = NSMutableArray()
var strSubscribe:String!
And I tried to access the value from below response
{
subscribe =
{
"subscribe_ids" = "1,14";
}
}
Edit
It works using Amit and Eric's solution but now for following data
{
data = (
{
"subscribe_ids" = "1,14";
}
);
}
let dictionary = responseObject["data"][0] as! Dictionary<String,AnyObject>
self.strSubscribe = dictionary["subscribe_ids"] as! String
OR//
if let dic = responseObject["data"][0] as? [String:String], let ids = dic["subscribe_ids"] {
self.strSubscribe = ids
}
but it gives me error:
could not find member 'subscript'
Swift doesn't know the type of responseObject["subscribe"], you have to help the compiler a bit; for example:
if let dic = responseObject["subscribe"] as? [String:String], let ids = dic["subscribe_ids"] {
self.strSubscribe = ids // "1,14"
}
UPDATE:
It's still the same problem: the compiler doesn't know the type of responseObject["data"], so when you try to access the subscript there's an error (because you know it's a dictionary inside the array, but the compiler doesn't).
One solution is to give the type to the compiler by declaring an array of dictionaries in the if let condition:
if let arr = responseObject["data"] as? [[String:String]], let ids = arr[0]["subscribe_ids"] {
self.strSubscribe = ids
}
Notice that it's [[String:String]] (array of dictionaries), not [String:String] (dictionary).
Write like this.
let dictionary = responseObject["subscribe"] as! Dictionary<String, AnyObject>
self.strSubscribe = dictionary["subscribe_ids"] as! String
Since responseObject["subscribe"] will give a AnyObject? output and AnyObject does not have any member called valueForKey.

Resources