Difference between optional and forced unwrapping [duplicate]

别来无恙 提交于 2019-12-01 14:25:27

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!