0

Below is the code for optional string for variable name yourname and yourname2.

Practically what is difference between them and how forced unwrapping in case of yourname2

var yourname:String?
yourname = "Paula"
if yourname != nil {
    println("Your name is \(yourname)")
}

var yourname2:String!
yourname2 = "John"
if yourname2 != nil {
    println("Your name is \(yourname2!)")
}
NNikN
  • 3,720
  • 6
  • 44
  • 86

3 Answers3

2

What you call 'forced unwrapping' is known as an 'implicitly unwrapped optional'. An implicitly unwrapped optional is normally used in objects that can't or won't assign a value to a property during initialization, but can be expected to always return a non-nil value when used. Using an implicitly unwrapped optional reduces code safety since its value can't be checked before runtime, but allows you to skip unwrapping a property every time it's used. For instance:

 var a: Int!
 var b: Int?

 var c = a + b //won't compile
 var d = a + b! //will compile, but will throw an error during runtime
 var e = a + a //will compile, but will throw an error during runtime

 a = 1
 b = 2

 var f = a + b //still won't compile
 var g = a + b! //will compile, won't throw an error
 var h = a + a //will compile, won't throw an error

Generally speaking you should always use optionals if you don't assign a value to a variable at initialization. It will reduce program crashes due to programmer mistakes and make your code safer.

kellanburket
  • 12,250
  • 3
  • 46
  • 73
2

The String? is normal optional. It can contain either String or nil.

The String! is an implicitly unwrapped optional where you indicate that it will always have a value - after it is initialized.

yourname in your case is an optional, yourname2! isn't. Your first print statement will output something like "Your name is Optional("Paula")"

Your second print statement will output something like "Your name is John". It will print the same if you remove the exclamation mark from the statement.

By the way, Swift documentation is available as "The Swift Programming Language" for free on iBooks and the very latest is also online here.

MirekE
  • 11,515
  • 5
  • 35
  • 28
0

Forced unwrapping an optional, give the message to the compiler that you are sure that the optional will not be nil. But If it will be nil, then it throws the error: fatal error: unexpectedly found nil while unwrapping an Optional value.

The better approach to unwrap an optional is by optional binding. if-let statement is used for optional binding : First the optional is assign to a arbitrary constant of non-optional type. The assignment is only valid and works if optional has a value. If the optional is nil, then this can be proceed with an else clause.

H S W
  • 6,310
  • 4
  • 25
  • 36