Swift: changing value inside class structured array - swift

class Store: NSObject {
var storeNumber : NSString!
var storetitle : NSString!
init(number:NSString, stTitle title : NSString) {
self.storeNumber = number
self.storetitle = title
}
}
var arrStore : NSMutableArray! = NSMutableArray()
var store = Store(number: "1", stTitle: "Adidas")
self.arrStore.addObject(store)
var store = Store(number: "2", stTitle: "Nike")
self.arrStore.addObject(store)
I want to change the value of the title "Nike"? How could I do that?
The below code changes the title of all objects in arrStore array:
self.arrStore.setValue("rebook", forKey: "storetitle")
I want something like:
self.arrStore.setValue("rebook", forKey: "storetitle")[1]
But unfortunately it is wrong!
Thank you in advance.

Just use:
let store = arrStore.objectAtIndex(1) as Store
store.storetitle = "New title"
or the more concise syntax:
let store = arrStore[1] as Store
store.storetitle = "New title"

I would suggest you to use Swift array rather than NSMutableArray.
var array = [Store]()
var store = Store(number: "1", stTitle: "Adidas")
self.arrStore.append(store)
var store = Store(number: "2", stTitle: "Nike")
self.arrStore.append(store)
array[0].storetitle = "New Title"

Related

Swift: Convert Array of Dictionaries to Array of String based on a key

Following is my Array of Dictionaries and I want to get an Array of only strings based on particular key (contentURL key in my case).
How can I achieve it? I have came across Reduce & Filter but no one fits into my requirement.
(
{
contentURL = "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4";
},
{
contentURL = "https://d1shcqlf263trc.cloudfront.net/151021804847312.mp4";
},
{
contentURL = "https://d1shcqlf263trc.cloudfront.net/151021536556612.mp4";
},
{
contentURL = "https://d1shcqlf263trc.cloudfront.net/151021528690312.mp4";
}
)
Expected Output
[
"https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4",
"https://d1shcqlf263trc.cloudfront.net/151021804847312.mp4",
"https://d1shcqlf263trc.cloudfront.net/151021536556612.mp4",
"https://d1shcqlf263trc.cloudfront.net/151021528690312.mp4"
]
Just use compactMap
let array = arrayOfDicts.compactMap {$0["contentURL"] }
var myDict: [[String : String]] = [["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"],["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"],["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"]]
let arr = myDict.map { $0["contentURL"] }
var stringArray:[String] = []
for (key, value) in yourArrayOfDictionary {
stringArray.append(value)
}
var arrayDict = [["contentURL":"fd"],["contentURL":"fda"],["contentURL":"fdb"],["contentURL":"fdc"]]
let arraywithOptionstring = arrayDict.map{$0["contentURL"]}
if let arr = arraywithOptionstring as? [String]{
print(arr)
}
Expected Output : ["fd", "fda", "fdb", "fdc"]
If you want to use reduce:
let arr = [
["contentURL" : "https://d1shcqlf263trc.cloudfront.net/"],
["contentURL" : "https://d1shcqlf263trc.cloudfront.net/.mp4"],
["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"]
]
let only = arr.reduce([String]()) { (partialRes, dictionary) -> [String] in
return partialRes + [dictionary["contentURL"]!]
}
More compact version:
let compact = arr.reduce([String]()) { $0 + [$1["contentURL"]!] }
Probably you weren't able to use reduce since you need to remember that subscripting a dictionary returns an Optional that is a different type than String
Also you can use just .map in this case.
let array = arrayOfDicts.map {$0["contentURL"]! }

Retrieve dictionary from dictionary swift

I am converting objective c code in swift.
I am getting data from server which has a dictionaries in a dictionaries.
i am getting key value string but cannot get dictionary.
example data:
data = {
caption = hello;
image = {
a = "https://www.google.com/1024x1024";
b = "https://www.google.com/640x640";
c = "https://www.google.com/480x480";
d = "https://www.google.com/";
};
};
i can get caption
let dataDict = (mainDict[data] as? Dictionary<String,AnyObject>)!
Obj.caption=String(dataDict["caption"]!) //getting hello
Obj.imageDictionary = (dataDict["image"] as? Dictionary<String,String>)! //getting 0 key value pairs
initialised imageDictionary as
var imageDictionary = Dictionary<String, String>()
please suggest how to get the image dictionary, I want this dictionary to store in imageDictionary object.
Any suggestions would be highly appreciated!
Thanks in advance!
Try this:
let data : [String : Any] = ["caption" : "hello",
"image" :["a" : "https://www.google.com/1024x1024",
"b" : "https://www.google.com/640x640",
"c" : "https://www.google.com/480x480",
"d" : "https://www.google.com/",
]
]
let caption = data["caption"] as! String
let imageDictionary = data["image"] as! [String : String]
In imageDictionary, I am getting:
["b": "https://www.google.com/640x640", "a": "https://www.google.com/1024x1024", "d": "https://www.google.com/", "c": "https://www.google.com/480x480"]
Screenshot:

Dynamic Struct creation in Swift - based on user input

I am trying to create dynamic struct in swift based on user input.
struct Diagnosis {
var diagName = String() // Name of the diagnosis
var diagSymptoms = [String]() // Symptoms of the diagnosis in a ranked array to identify prevelancy
var diagSpecialization = [String]() // the specializations which would mostly encounter this diagnosis
var diagRank = Int() // the overall rank of the diagnosis
var diagSynonoms = [String]() // the other name thru which the same diagnosis is called / referred.
// func init(diagName: String(),diagSymptoms: [String](),diagSpecialization: [String](),diagSynonoms: [String]())
init( let pasdiagName: String,let pasdiagSymptoms:Array<String>) {
self.diagName = pasdiagName
self.diagSymptoms = pasdiagSymptoms
}
}
var maleria = Diagnosis(pasdiagName: "Maleria",pasdiagSymptoms: ["fever","chill","body pain"])
The above creates the structure maleria - But in future I want to have the input from user and create a structure for that inputted string
var abc = "typhoid"
let valueof(abc) = Diagnosis()
The value of function is something I just put here arbitrarily to make my explanation clear.
I know I could do this in python and I am new to swift. Thanks in advance for the help.
As #Wain suggested, you should use a Dictionary.
This is how you create a mutable dictionary where the key is a String and the value can be any type.
var dict = [String:Any]()
This is how you put key/value pairs into the dictionary
dict["year"] = 2016
dict["word"] = "hello"
dict["words"] = ["hello", "world"]
And this is how you extract a value and use it
if let word = dict["word"] as? String {
print(word) // prints "hello"
}

How to initialize a Dictionary with structure components in Swift

I have the following structure:
struct song {
var songnum: Int = 0
var name = "not defined"
var lyrics_wo_chords = NSMutableAttributedString()
var lyrics_w_chords = NSMutableAttributedString()
var favorite = false
}
And I'm trying to make a dictionary var songs = [String: [song]]()
where the the String is the name of the Songbook and the [song]
is an array of structures called song that hold the individual structure members
I've tried this songs["SongBook name"] = song.self as? [song] to add a new Key to the Dictionary. But otherwise, i have no idea how i would initialize it.
Also, when i append the array of the Key:
songs["SongBook name"]?.append(song(
songnum: 1,
name: "Name",
lyrics_o_chords: NSMutableAttributedString(string:"No Chords"),
lyrics_w_chords: NSMutableAttributedString(string: "With Chords"),
favorite:
false))`
the dictionary returned is nil
Any help would be much appreciated, thank you
Your value in your dictionary is an array of song (that is [song]), so you need to put [ ] around your value to make it into an array of song:
songs["SongBook name"] = [song(
songnum: 1,
name: "Name",
lyrics_wo_chords: NSMutableAttributedString(string:"No Chords"),
lyrics_w_chords: NSMutableAttributedString(string: "With Chords"),
favorite: false)
]
Structure and class names should be capitalized, so use Song instead of song when defining your structure.

Change value of dictionary within array in Swift 2

I'm trying to change a value of a dictionary that is within an array. I made a small prototype in PlayGround:
var arr = [NSDictionary]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])
//test remove
arr.removeAtIndex(2)
arr.count
//test edit
let nameChange = arr[1]
nameChange.setValue("black", forKey: "name")
arr[1]
But an error occurred, and I can not solve:
Some can help me?
Because you created your dictionary as NSDictionary - the values can't change once they are set. But you still want to change them using setValue() and thats why you have the error. The fix is easy, change it to NSMutableDictionary. BUT. You shouldn't use Objective-C API, when you have Swift API. Thats why you should use Swift's Dictionary. How? e.g.
var arr = [[String:String]]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])
//test remove
arr.removeAtIndex(2)
arr.count
//test edit
var nameChange = arr[1]
nameChange["name"] = "black"
Finally Got Some Code,
let DuplicateArray: NSArray = array
let DuplicateMutableArray: NSMutableArray = []
DuplicateMutableArray.addObjectsFromArray(DuplicateArray as [AnyObject])
var dic = (DuplicateMutableArray[0] as! [NSObject : AnyObject])
dic["is_married"] = "false"
DuplicateMutableArray[self.SelectedIndexPath] = dic
array = []
array = (DuplicateMutableArray.copy() as? NSArray)!
//Output Will Be Like
array = [
{
"name": "Kavin",
"Age": 25,
"is_married": "false"
},
{
"name": "Kumar",
"Age": 25,
"is_married": "false"
}
]