0
votes

I pass a long number as string from FirstVC.swift to SecondVC.swift like:

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)

and receive in 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
    }

}

but I get error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

If socid has an optional value, why I can not unwrap the string? AND when socid equals some other short number everything works.

4
can you pass data by delegate - Quiet Islet
@QuietIslet anyway, I get this error although socid has a value - Scripy
does indicate which line you got error - Quiet Islet
@QuietIslet let i1 = Int(socid!)! + 7778955 here - Scripy
check my answer - Quiet Islet

4 Answers

0
votes

For me your code works but still I think it would be a good practice to avoid the forced unwrapping. Maybe do something like this instead:

if let socid = socid, let socidInt = Int(socid) {
  let i1 = socidInt + 7778955
  print(i1)
} else {
  print("Failed to unwrap socid to an integer")
}
0
votes

It's crashing because converting your string to an int is failing:

let i1 = Int(socid!)! + 7778955

If Int(bigthing) fails then it will be nil.

0
votes
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.
}
0
votes

Try this...

override func viewDidLoad() {
    super.viewDidLoad()

    if let socid = socid, var i1 = Int(socid)
    {
        i1 += 7778955
        print("Te number is \(number)")
    }
}