Swift allows you to use the shortened str! notation str! to deploy optional. But what if we want to do the opposite?
Let's say I have a variable:
var str = String()
Is there a shorthand notation to convert this to optional (i.e. String? Or String! )?
(For example, I want to do something like var strOptional = ?(str) .)
Alternatively, if there are no abbreviations for these notations, how can you convert it to optional without explicitly specifying its type (for example, I do not want to mention String ).
In other words, I know that I can wrap a variable as optional with any of these methods:
var strOptional = str as String? var strOptional: String? = str var strOptional = String?(str)
... but in each case I have to explicitly write String .
I would rather write something like: var strOptional = str as typeof?(str) if there is no abbreviated syntax. (The advantage is that if the type of the variable changes frequently in the code base, it will be one less place to update.)
As for the real world, where it would be useful, imagine that I want to use AVCaptureDevice, and I use the following code:
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) device.lockForConfiguration(nil)
lockForConfiguration() will fail during operation on a device that does not have a video camera, and the compiler will not warn me about this. The reason is that defaultDeviceWithMediaType may return nil according to the documentation [1] but it is defined as returning AVCaptureDevice! .
To fix an erroneous API like this, it would be nice to do something like:
let device = ?(AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo))
... to get AVCaptureDevice? , and the compiler will catch any errors that I could make.
Currently, I have to resort to a more detailed one:
let device: AVCaptureDevice? = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
Another example:
In this case, I want to specify a default value for my variable, which is a string, but later I can set it to nil .
var myString = "Hi" // ... if (someCondition()) { myString = nil // Syntax error: myString is String }
Currently, I have to resort to var myString: String? = "Hi" var myString: String? = "Hi" , but something like var myString = ?("Hi") will be less verbose.
[1] If you open AVCaptureDevice.h, you will see the following documentation about the return value: "The default device with this media type or nil if there is no device with this media type." sub>