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!)
Related
I'm going to display some data from NSArray in the tableViewCell.
Here is my NSArray format
(
{
score = "480.0";
uid = 2;
},
{
score = "550.0";
uid = 1;
}
)
So, how to display for example score?
Here is m code, but it doesn't display it
var gamesRound: NSArray = []
let game = gamesRound[indexPath.row]
//let user = users[Int(game.userId - 1)]
cell.textLabel?.text = game as? String
//cell.detailTextLabel?.text = "\(String(Int(game.score))) PTS"
//print(user.fullname!)
return cell
Change your gamesRound variable to Array of Dictionary like this:
Put some value like this, in viewDidLoad (maybe):
var gamesRound = [[String: Any]]()
To render value on cells of a UITableView
gamesRound = [["score": "480.0", "uid" = 2], ["score": "550.0", "uid": 1]]
Some what like this:
let game = gamesRound[indexPath.row] as! [String: Any]
cell.textLabel?.text = "\(game["score"] as? Int ?? 0)"
cell.detailTextLabel?.text = "\(game["uid"] as? Int ?? 0)"
seems to me that you have an NSDictionary in each position of you NSArray.
So, use this code to get the position that you want:
let game = gamesRound[indexPath.row]
Now the game is an NSDictionary and you only need to extract the information using the key that you want:
let uid = game["uid"]
let score = game["score"]
I hope my example helps you.
Here you have the Array of dictionary so when you write let dict = gamesRound[indexPath.row] you will get the dictionary object and you can get the value by using the key because dictionary has the key value pair while the array has the indexing.
Also, you can Declare array like this
var gamesRound: Array<Dictionary<String,Any>> = []
So you can verify by printing the values step by step:
print(gamesRound)
let dict = gamesRound[indexPath.row] as! Dictionary<String,Any>
print(dict)
let score = dict["score"]
print(dict["score"])
cell.textLabel?.text = "\(score!)"
Try this code,
let gameRound : NSDictionary = yourArray[indexPath.row] as! NSDictionary
let strUid = gameRound["uid"]
cell.textLabel.text = strUid as? String
let uid = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference().child("users").child((uid)!)
ref.observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String: AnyObject] {
let htest = dictionary["h"] as! String //error is mainly here signal SIGABRT
var inthtest = Int(htest)
if (inthtest==0){
self.checkPointsk()
print("scanning1")
I've tried changing the as String Value To int Value but it still doesn't work
The error is self explanatory. You're trying to cast a number as a string. Replace the below two lines
let htest = dictionary["h"] as! String
var inthtest = Int(htest)
with
var inthtest = dictionary["h"] as! Int
The best way to avoid crashes like this is to use conditional binding.
if var inthtest = dictionary["h"] as? Int{
//Do your stuff
}
else if var inthtest = dictionary["h"] as? String{
if let integerValue = Int(inthtest){
//Do your stuff
}
}
I'm having a lot of frustration with Swift when it comes to working with Dictionaries and NSDictionaries.
I am pulling data from a server. One of the values is a Bool.
I started with a Swift Dictionary and moved to NSDictionary out of frustration. However, I still cannot get the values from the dictionary.
All of the following fail with contradictory errors:
let unread:Bool = data!["unread"] as! Bool
let unread:Bool = data?["unread"] as! Bool
let unread:Bool = data?.objectForKey("unread") as! Bool
let unread:NSNumber = data?["unread"] as! NSNumber
error: Could not cast value of type 'NSTaggedPointerString' (0x110c1eae8) to 'NSNumber' (0x10e0ab2a0).
Okay, looks like that data is coming in as a String... let's try:
let unreadStr:String = data!["unread"] as! String
let unreadStr:NSString = data!["unread"] as! NSString
error: Could not cast value of type '__NSCFBoolean' (0x1097413b8) to 'NSString' (0x106bcdb48).
So I'm confused. When I try to convert it to a Bool it says I cannot convert a String to a Number. When I try to convert it to a String, it says I cannot convert a number to a string.
Here is what the data looks like:
Optional({
senderId = 10154040;
sent = 1460844986973;
text = "Test Message 1";
unread = false;
})
You should try something along these lines:
let data: [String : Any] = ["first" : "test", "second" : 2, "third" : true]
let first = data["first"] as! String
let second = data["second"] as! Int
let third = data["third"] as! Bool
print(first)
print(second)
print(third)
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
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)