-2

I got access error('fatal error: unexpectedly found nil while unwrapping an Optional value') when print variable p02. According to the error message, I still cannot understand the reason.

var p02:Person! = nil
var p03:Person? = nil

if (p02==nil)
{
    print("p02 is nil")
}
if (p03==nil)
{
    print("p03 is nil")
}
print(p03)
print(p02)

Anyone know why, Thanks

gigir
  • 132
  • 1
  • 10
  • 1
    Because p02 is an *implicitly __unwrapped__ Optional* and p03 is just a normal Optional. – Eric Aya Jul 18 '16 at 13:16
  • Why declaration of p02 (var p02:Person! = nil ) is legal ? – gigir Jul 18 '16 at 13:29
  • Read the [Optionals](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309) chapter in the Swift guide, specifically the "Implicitly Unwrapped Optionals" part. – Eric Aya Jul 18 '16 at 13:30

1 Answers1

1

cause it always tries to print p02 and p03 even if they are nil

try this

var p02:Person! = nil
var p03:Person? = nil

if (p02==nil)
{
    print("p02 is nil")
}else{
    print(p02)
}
if (p03==nil)
{
    print("p03 is nil")
}else{
    print(p03)
}
Daniel Poulsen
  • 1,446
  • 13
  • 21