我将一个长数字作为字符串从FirstVC.swift
传递给SecondVC.swift
,如:
let userId = user.userID // GOT FROM GOOGLE SIGN IN
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC
let navigationController = self.tabBarController?.navigationController
vc.socid = userId!
let transition = CATransition()
transition.duration = 0.3
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionMoveIn
transition.subtype = kCATransitionFromTop
self.navigationController?.view.layer.add(transition, forKey: nil)
self.navigationController?.pushViewController(vc, animated: false)
并在SecondVC.swift
收到:
var socid:String!
override func viewDidLoad() {
super.viewDidLoad()
print(socid) // RETURNS Optional("11365489964475")
if(socid==nil){
print("socid is empty")
}else{
let i1 = Int(socid!)! + 7778955 //I GET ERROR HERE
}
}
但我收到错误:主题1:致命错误:在解包可选值时意外发现nil
如果socid
有可选值,为什么我无法打开字符串? AND 当socid
等于其他一些短号时,一切正常。
答案 0 :(得分:0)
因为将字符串转换为int失败而崩溃:
let i1 = Int(socid!)! + 7778955
如果Int(bigthing)
失败,则为零。
答案 1 :(得分:0)
let socid = ""
override func viewDidLoad() {
super.viewDidLoad()
let mySocid = Int(socid)
guard let mySocid2 = mySocid else {
return
}
let newValue = mySocid2 + 50
print("newValue\(newValue)")
// Do any additional setup after loading the view, typically from a nib.
}
答案 2 :(得分:0)
对我来说,你的代码有效,但我认为避免强制解包是一个好习惯。也许做这样的事情:
if let socid = socid, let socidInt = Int(socid) {
let i1 = socidInt + 7778955
print(i1)
} else {
print("Failed to unwrap socid to an integer")
}
答案 3 :(得分:0)
试试这个......
override func viewDidLoad() {
super.viewDidLoad()
if let socid = socid, var i1 = Int(socid)
{
i1 += 7778955
print("Te number is \(number)")
}
}