I'm new to swift. when I'm learning just basics I got this error at NSLog
Here is my code :
import UIKit class ViewController: UIViewController { var myString: NSString? override func viewDidLoad() { super.viewDidLoad() myString = "himanth" print(myString) NSLog("%@" , myString) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } If I am declaring myString like this
var myString: NSString! It's fine to use NSLog and I can able to see console as well.
But declaring string like this causing problem
var myString: NSString? It reflects at NSLog and showing error.
What is the problem with that?
If you declare var myString: NSString? as an optional then you need to make sure it has a value before you pass it to the NSLog.
So you could do it like this then NSLog("%@" , myString!). If myString is nil and you put ! the program will crash and you will get
fatal error: unexpectedly found nil while unwrapping an Optional value. But if it has a value the program will continue as normal and print out
2016-10-03 10:26:25.077 Swift3.0[65214:1579363] Test I wrote myString = "Test".
Another example as @Grimxn mentioned is the coalescing operator.
NSLog("%@", myString ?? "<nil>")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With