We want to
change string “8” to number 8. We do like this
let a="8"
let number = NSNumberFormatter().numberFromString(a)
var num = number!.integerValue
let b=9+num
Change “8”
to “8m”, error mark at line let b=9+num because can’t change “8m” to number.
We use Try
catch like this.
do {
let number = try NSNumberFormatter().numberFromString(a)
var num = number!.integerValue
let b=9+num
}
catch let error as NSError{
print("Error cast string to number")
}
It still
show error, because Swift doesn’t support try catch like this.
To catch
exception in this case, we do this way.
if let number = NSNumberFormatter().numberFromString(a){
var num = number.integerValue
let b=9+num
}
else{
print("Error cast string to number ")
}
Run to see
result, programme still run, not crash.
Remove
character m in variable a, it run normally, result show 17.
Try catch useless
here but sometime you must use it when make app, for example, to check when
read txt file.
This lesson
let you know about it, that ‘s all.
No comments:
Post a Comment