So I have this routine that sets different text uilabel.text values
self.addressLabel.text = firstObject["ADDRESS"] as? String
self.phoneLabel.text = firstObject["PhoneNums"] as? String
self.latitude.text = firstObject["LAT"] as? String
self.longitude.text = firstObject["LON"] as? String
but when I try to print out
println("\(latitude.text!)")
It outputs:
Label
How can I make it so that the println statement prints the string "38.1848392". Thanks!
You can't cast a Double to String as it will always fail.
self.latitude.text = 38.1848392 as? String // this will always fail
self.latitude.text = String(format:"%f", 38.1848392) // instead, you have to do it this way
You can set the string to a variable, and then print that.
So:
var latitudeString : String = self.latitude.text
println(latitudeString)
Edit:
Seems like casting the latitude as a String is not properly happening. What you could do is the following:
var lat : Float = firstObject["LAT"] as! Float
var latString = String(lat)
self.latitude.text = latString
println(latString)
Related
I converting my String value to Double shows in below code .In final variable i am getting string value i.e ex - 1435.76 But while i am converting into Double value shows nill. Please help me to get rid into this .Thanks in advance
self.cart = result.value(forKey: "cart") as! NSMutableArray
self.totalsDic = result.value(forKey: "totals") as! NSMutableDictionary
print(self.totalsDic)
// print(self.cart)
let total = self.totalsDic.object(forKey: "total") as! NSMutableDictionary
let final = total.object(forKey: "total") as? String
// final = final?.replacingOccurrences(of: "Rs.", with: "")
let myDouble1 = NumberFormatter().number(from: final!)?.doubleValue
print("My double: \(String(describing: myDouble))")
let myDouble2 = Double(final!)
I have the following class
class BannerResponse : NSObject{
let URL = "Url";
let CONTACT_NO = "ContactNo";
let IMAGE = "Image";
let BIG_IMAGE = "BigImage";
let ID = "Id";
let TITLE = "Title";
let NO_VIEW = "NoView";
let START_DATE = "StartDate";
let END_DATE = "EndDate";
var url:String;
var contactNo:String;
var image:String;
var bigImage:String;
var title:String;
var id:Int;
var noView:Int;
var startDate:String;
var endDate:String;
init(data : NSDictionary){
url = data[URL] as! String;
contactNo = data[CONTACT_NO] as! String;
image = data[IMAGE] as! String;
bigImage = data[BIG_IMAGE] as! String;
title = data[TITLE] as! String;
id = data[ID] as! Int;
noView = data[NO_VIEW] as! Int;
startDate = data[START_DATE] as! String;
endDate = data[END_DATE] as! String;
}
}
when I run the code, I got the following error
Could not cast value of type 'NSNull' (0x10a85f378) to 'NSString' (0x109eccb20).
EDIT
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{
onSuccess(BannerResponse(data: json))
}
} catch {
onFail()
}
One of your data[SOME_KEY] is of type NSNull instead of String and because you're forcing the cast to String by using ! the app crashes.
You can do one of two things:
Change your variables on the BannerResponse class to be optional. And use ? instead of ! when setting the values in your init method. Like this:
`
var title: String?
init(data: NSDictionary)
{
self.title = data[TITLE] as? String
}
or
Use ? instead of ! when setting the values in your init method but set a default value whenever dict[SOME_KEY] is nil or is not the expected type. This would look something like this:
`
if let title = data[TITLE] as? String
{
self.title = title
}
else
{
self.title = "default title"
}
// Shorthand would be:
// self.title = data[TITLE] as? String ?? "default title"
And I guess a third thing is ensure that the server never sends down null values. But this is impractical because there's no such thing as never. You should write your client-side code to assume every value in the JSON can be null or an unexpected type.
You are getting null values for some of your keys. They get mapped to NSNull by NSJSONSerialization.
You need to do several things
Change all your variables (url, contactNo, etc) to optionals:
var url:String?
var contactNo:String?
Change all of your assignments to use ? instead of !:
url = noNulls[URL] as? String
contactNo = noNulls[CONTACT_NO] as? String
And finally, make your code handle nil values for all of your variables. (But do not use !. That path leads to crashes.)
I'm trying to pass a text that is correct api put in swift he arrives with the message of "optional". this is my code:
let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = accountValues.objectAtIndex(0) as? String
self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String
When retrieving the value, use ! after the value. The downcast should force unwrap any optionals. Anything set as? can be force unwrapped by using !.
For example,
let intString = 7 as? String
print(intString!)
This should print "7", rather than Optional("7")
please replace these lines :
self.accountTextField.text = accountValues.objectAtIndex(0) as? String
self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String
by :
self.accountTextField.text = (accountValues.objectAtIndex(0) as! String)
self.accountDigitTextField.text = (accountValues.objectAtIndex(1) as! String)
You're using Optional Value "As? String". So, it will return an Optional('value').
Try this:
let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = "\(accountValues.objectAtIndex(0))"
self.accountDigitTextField.text = "\(accountValues.objectAtIndex(1))"
I really thought this was Xcode playing up as I can't for the life of me see what is causing this error in a fairly simple piece of Swift code but after restarting cleaning the project, restarting Xcode, and restarting my MacBook I'm still getting the same error.... But why!!??!!
Here is the code
// Loop through records saving them
for recordItem in records {
if let record: NSDictionary = recordItem as? NSDictionary {
let time: String = record["time"] as! String
let record: String = record["record"] as! String
let recordId: String = record["record_id"] as! String
let saveTime: String = record["save_time"] as! String
let setId: String = record["set_id"] as! String
// Does more stuff
}
}
records is an NSArray and it is made from data downloaded from a remote server.
All is fine until the line beginning let recordId. This and the two lines below it are giving an error - Cannot subscript a value of type 'String' with an index of type 'String'
Why? And why is there no problem with the 2 lines above? And how do I fix it?
Any help is greatly appreciated as I'm at a bit of a dead end.
You are using the variable record to unwrap the optional recordItem but then you are re-assigning record as record["record"] - so from this point on it becomes a String, not a Dictionary - resulting in the error message Cannot subscript a value of type 'String' with an index of type 'String'
You just need to change one of the record variables
for recordItem in records {
if let unwrappedRecord: NSDictionary = recordItem as? NSDictionary {
let time: String = unwrappedRecord["time"] as! String
let record: String = unwrappedRecord["record"] as! String
let recordId: String = unwrappedRecord["record_id"] as! String
let saveTime: String = unwrappedRecord["save_time"] as! String
let setId: String = unwrappedRecord["set_id"] as! String
// Does more stuff
}
}
The problem is here, you are declaring record as a String, previously it was NSDictionary and due to scope the record in record["record_id"] is String not NSDictionary. Quick fix is to change the name as I did
let time: String = record["time"] as! String
let record1: String = record["record"] as! String
let recordId: String = record["record_id"] as! String
let saveTime: String = record["save_time"] as! String
let setId: String = record["set_id"] as! String
Can anyone please explain me the difference
var someString = “Some String”
var someString: String = “Some String”
var someString = “Some String” as String
var someString = “Some String” as! String
var someString = “Some String” as? String
let someString = “Some String”
let someString: String = “Some String”
For this two:
There’s zero runtime efficiency difference between the two. During compilation, Swift is inferring the type and writing it in for you. But once compiled, the two statements are identical.
let someString = “Some String” as String
Means you are casting someString value to string if it is not string.
let someString = “Some String” as! String
Means you are forcibly casting “Some String” as a string but if it is not convertible to string then it will crash the app.
let someString = “Some String” as? String
Means you are optionally casting “Some String” to string means if it is not convertible to string then it will return nil but wont crash at this point.
For last 3 Statement It would compile and work but it is definitely wrong to cast String to String. there is no need to cast a String to String.
And the the last 2 as? and as! would always succeed in your case.
Consider below example:
let stringObject: AnyObject = "Some String"
let someString3 = stringObject as! String
let someString5 = stringObject as? String
This is when you will need to cast. Use as! only if you know it is a string. And use as? if you doesn't know that it will be string or not.
only force downcast with as! if you are sure otherwise use conditional cast like this:
if let someString5 = stringObject as? String {
println(someString5)
}