How can I access an struct attribute from an array? - ios

What I want to do is to, after storing several objects of type CodigosAutorizacion inside an array:
for value in 0..<(array.count) {
let codeArray = CodigosAutorizacion(
code: validateData!["codigo"] as? String,
codeCancel: validateData!["cancela_codigo"] as? String,
codeSite: validateData!["cod_sitio"] as? String,
codeSiteCancel: validateData!["cancela_cod_sitio"] as? String,
instance: validateData!["instancia"] as? String
)
codes.append(codeArray)
}
Access the object attributes from the array like this:
codeCell.codigoSitio.text = codes[indexPath.row].instance
This piece throws me the next errors
-No exact matches in call to subscript
-Reference to member 'instancia' cannot be resolved without a contextual type
this is because ´codes´ is an array and not a CodigosAutorizacion type
Storing these objects in an array is important because I will need to generate a table with several of this CodigosAutorizacion objects. Is there any way this can be possible?

var codes = [CodigosAutorizacion]()
for value in 0..<(array.count) {
let codeArray = CodigosAutorizacion(
code: validateData!["codigo"] as? String,
codeCancel: validateData!["cancela_codigo"] as? String,
codeSite: validateData!["cod_sitio"] as? String,
codeSiteCancel: validateData!["cancela_cod_sitio"] as? String,
instance: validateData!["instancia"] as? String
)
codes.append(codeArray)
}
-- Try this --

Fixed! it was a problem with the codes array declaration, it was not supposed to be var codes: Array<Any> but instead var codes: Array<CodigosAutorizacion> in order to access CodigosAutorizacion's properties

Related

iOS Swift 3 - Argument labels '(of:)' do not match any available overloads Error

I'm getting the error message Argument labels '(of:)' do not match any available overloads. Below is the code I'm using.
let prefs = UserDefaults.standard
var id: String!
if var array = prefs.string(forKey: "myArray"){
if let index = array.index(of: id) {
array.remove(at: index)
prefs.setValue(array, forKey: "myArray")
}
}
I've seen a lot of answers on Stack Overflow with very similar code to that. So I'm not quite sure why this wouldn't be working.
Basically I'm just trying to remove the element in the array that = id then set that new array to the user defaults.
Update
Just updated the code above to show how array is getting defined. id is a string that is defined in a separate section.
By accessing prefs.string(forKey: "myArray"), you are getting a String, not an array of strings. You should use this:
if var prefs.array(forKey: "myArray") as? [String] { }
or
if var prefs.value(forKey: "myArray") as? [String] { }
Make sure to not forget putting as! [String], because the first method returns [Any], an which can contain objects of any type, not specifically String. Then your error should be solved, because index(of: ) can only be used on Arrays of specified types.
Hope it helps!
Just make an alt + Click on an "array" variable to make sure it is of type Array ([String]), not a String. To apply .index(of:) method it must be an array.
Like this:
String does not have a method .index(of:). That's what the error is pointing at. And sure make a cast to [String]? if it fits.

Can't cast from Dictionary value to Array

No idea why this won't work. The value of this dictionary is a key, yet whenever I try to cast to an array, I get a multitude of errors. Here's what I've tried, with the error I get following each example (in all examples, parameters is type [String : Any]:
let paramsArray = parameters["inputVO"] as AnyObject
if let array = paramsArray as? Array {
}
Error: Generic parameter 'Element' could not be inferred in cast to 'Array<_>'
if let array = parameters["inputVO"] as? Array {
}
Error: Ambiguous reference to member 'subscript'
I'm not sure what else to do to cast the result to an array? I'm sure I've done this before, I have no idea why this is failing. Any help is greatly appreciated.
Edit: Here's the output when I print out params. As expected, it is populated with an Array of Dictionary's.
Optional([["stmtDate": cmd, "transId": identifier, "isSupplementDataAvailable": true]])
Either it's an array
if let array = parameters["inputVO"] as? [[String:Any]] { ... }
or a dictionary
if let dictionary = parameters["inputVO"] as? [String:Any] { ... }
Both types are generics and need specific type information
[[String:Any]] is the short form of Array<Dictionary<String,Any>>
[String:Any] is the short form of Dictionary<String,Any>

how to get Number value form dictionary

I am accessing data from JSON and storing it in dictionary 1 and passing this dictionary 1 to another view controller's dictionary 2. The view controller has all the details mainly 12 labels. I have managed to access the strings but i am not able to get the number values. Please have a look at the code.
DetailsViewController
var dict2 = [String : AnyObject]()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.lblTopName.text = self.dict2["toponymName"] as? String
self.lblFcodeName.text = self.dict2["fcodeName"] as? String
self.lblName.text = self.dict2["name"] as? String
self.lblCountryCode.text = self.dict2["countrycode"] as? String
self.lblFCL.text = self.dict2["fcl"] as? String
self.lblFclName.text = self.dict2["fclName"] as? String
self.lblWikipedia.text = self.dict2["wikipedia"] as? String
self.lblFcode.text = self.dict2["fcode"] as? String
self.lblLongitude.text = self.dict2["lng"] as? String
Note. The last line of code that is longitude a number value. If I replace String with NSNumber it gives me the following error:
Cannot assign value of type NSNumber to type String
Forced cast should be avoided as much as possible, as it can lead to unexpected crashes. (self.dict2["lng"] as! NSNumber) will crash your application if for some reason the dictionary ends up without the lng key.
Your last line should be:
self.lblLongitude.text = self.dict2["lng"]?.description
This is guaranteed not to crash, as description exists on any object, and in case the dictionary somehow doesn't contain the "lng" key, you'll get a simple nil to assign to text.
plese try this if self.dict2["lng"] never null
self.lblLongitude.text = (self.dict2["lng"] as! NSNumber).stringValue
else if can be null then
self.lblLongitude.text = self.dict2["lng"]?.description
you can get integer value from dictionary like
int value = dict["integerValue"].integerValue // or doubleValue etc
and if you need string it can be like
self.lblLongitude.text = "\(self.dict2["lng"]. doubleValue)"
You can write like this
self.lblLongitude.text = String(format: "%f",self.dict2["lng"]!)

Swift optionals: language issue, or doing something wrong?

I am doing what I believe to be a very simple task. I'm trying to get a value out of a dictionary if the key exists. I am doing this for a couple keys in the dictionary and then creating an object if they all exist (basically decoding a JSON object). I am new to the language but this seems to me like it should work, yet doesn't:
class func fromDict(d: [String : AnyObject]!) -> Todo? {
let title = d["title"]? as? String
// etc...
}
It gives me the error: Operand of postfix ? should have optional type; type is (String, AnyObject)
HOWEVER, if I do this, it works:
class func fromDict(d: [String : AnyObject]!) -> Todo? {
let maybeTitle = d["title"]?
let title = maybeTitle as? String
// etc...
}
It appears to be basic substitution but I may be missing some nuance of the language. Could anyone shed some light on this?
The recommended pattern is
if let maybeTitle = d["title"] as? String {
// do something with maybeTitle
}
else {
// abort object creation
}
It is possibly really a question of nuance. The form array[subscript]? is ambiguous because it could mean that the whole dictionary (<String:AnyObject>) is optional while you probably mean the result (String). In the above pattern, you leverage the fact that Dictionary is designed to assume that accessing some key results in an optional type.
After experimenting, and noticing that the ? after as is just as ambiguous, more, here is my solution:
var dictionary = ["one":"1", "two":"2"]
// or var dictionary = ["one":1, "two":2]
var message = ""
if let three = dictionary["three"] as Any? {
message = "\(three)"
}
else {
message = "No three available."
}
message // "No three available."
This would work with all non-object Swift objects, including Swift Strings, numbers etc. Thanks to Viktor for reminding me that String is not an object in Swift. +
If you know the type of the values you can substitute Any? with the appropriate optional type, like String?
There are a few of things going on here.
1) The ? in d["title"]? is not correct usage. If you're trying to unwrap d["title"] then use a ! but be careful because this will crash if title is not a valid key in your dictionary. (The ? is used for optional chaining like if you were trying to call a method on an optional variable or access a property. In that case, the access would just do nothing if the optional were nil). It doesn't appear that you're trying to unwrap d["title"] so leave off the ?. A dictionary access always returns an optional value because the key might not exist.
2) If you were to fix that:
let maybeTitle = d["title"] as? String
The error message changes to: error: '(String, AnyObject)' is not convertible to 'String'
The problem here is that a String is not an object. You need to cast to NSString.
let maybeTitle = d["title"] as? NSString
This will result in maybeTitle being an NSString?. If d["title"] doesn't exist or if the type is really NSNumber instead of NSString, then the optional will have a value of nil but the app won't crash.
3) Your statement:
let title = maybeTitle as? String
does not unwrap the optional variable as you would like. The correct form is:
if let title = maybeTitle as? String {
// title is unwrapped and now has type String
}
So putting that all together:
if let title = d["title"] as? NSString {
// If we get here we know "title" is a valid key in the dictionary, and
// we got the type right. title has now been unwrapped and is ready to use
}
title will have the type NSString which is what is stored in the dictionary since it holds objects. You can do most everything with NSString that you can do with String, but if you need title to be a String you can do this:
if var title:String = d["title"] as? NSString {
title += " by Poe"
}
and if your dictionary has NSNumbers as well:
if var age:Int = d["age"] as? NSNumber {
age += 1
}

Swift: iterating through plist

I am trying to use a plist to hold an array of dictionaries. Everything seems to be ok except for when I try to iterate through each element of the array. In this case I an using NSArrays and NSDictionarys.
In the below example, albumInfo is a NSDictionary. The key, "Title" is linked with the a string object. I am using a method called addAlbumInfo which has arguments which are all Strings except for the "price:"
Please help.
var pathToAlbumsPlist:NSString = NSBundle.mainBundle().pathForResource("AlbumArray", ofType: "plist");
var defaultAlbumPlist:NSArray = NSArray(contentsOfFile: pathToAlbumsPlist);
for albumInfo:NSDictionary in defaultAlbumPlist {
self.addAlbumWithTitle(
albumInfo["title"], //Says it is not convertable to a string
artist: albumInfo["artist"],
summary: albumInfo["summary"],
price: albumInfo["price"].floatValue,
locationInStore: albumInfo["locationInStore"]
);
}
Since albumInfo is an NSDictionary it can only contain AnyObjects, which means it can't contain a Swift String that is a struct. If your addAlbumWithTitle expects a String and you try to pass it an AnyObject it will give you this error. You can cast albumInfo["title"] to a Swift String like this:
albumInfo["title"] as String
the solution I found was to make albumInfo assume a type and then type case each of the values
var pathToAlbumsPlist:NSString = NSBundle.mainBundle().pathForResource("AlbumArray", ofType: "plist");
var defaultAlbumPlist:NSArray = NSArray(contentsOfFile: pathToAlbumsPlist);
for albumInfo in defaultAlbumPlist {
self.addAlbumWithTitle(albumInfo["title"] as String,
artist:albumInfo["artist"] as String,
summary:albumInfo["summary"] as String,
price:albumInfo["price"] as Float,
locationInStore:albumInfo["locationInStore"] as String
);
}

Resources