Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing a default value for an Optional in Swift?

Tags:

swift

optional

The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it's nil:

if let value = optionalValue {     // do something with 'value' } else {     // do the same thing with your default value } 

which involves needlessly duplicating code, or

var unwrappedValue if let value = optionalValue {     unwrappedValue = value } else {     unwrappedValue = defaultValue } 

which requires unwrappedValue not be a constant.

Scala's Option monad (which is basically the same idea as Swift's Optional) has the method getOrElse for this purpose:

val myValue = optionalValue.getOrElse(defaultValue) 

Am I missing something? Does Swift have a compact way of doing that already? Or, failing that, is it possible to define getOrElse in an extension for Optional?

like image 882
Wes Campaigne Avatar asked Jun 07 '14 17:06

Wes Campaigne


People also ask

How do I set optional value in Swift?

To use an optional, you "unwrap" it An optional String cannot be used in place of an actual String . To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping".

How do I declare optional type in Swift?

Optional Types Syntax and Usage in Swift Here's the syntax for an optional type: <data-item> <var-name>:<data-type>? The declaration is similar to declaring regular variables, except that you add a question mark (?) beside the data type which makes it an Optional type.

Is it possible to give a default value to a function parameter Swift?

You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter's type. If a default value is defined, you can omit that parameter when calling the function. // the value of parameterWithDefault is 12 inside the function body.


2 Answers

Update

Apple has now added a coalescing operator:

var unwrappedValue = optionalValue ?? defaultValue 

The ternary operator is your friend in this case

var unwrappedValue = optionalValue ? optionalValue! : defaultValue 

You could also provide your own extension for the Optional enum:

extension Optional {     func or(defaultValue: T) -> T {         switch(self) {             case .None:                 return defaultValue             case .Some(let value):                 return value         }     } } 

Then you can just do:

optionalValue.or(defaultValue) 

However, I recommend sticking to the ternary operator as other developers will understand that much more quickly without having to investigate the or method

Note: I started a module to add common helpers like this or on Optional to swift.

like image 132
drewag Avatar answered Jan 01 '23 10:01

drewag


As of Aug 2014 Swift has coalescing operator (??) that allows that. For example, for an optional String myOptional you could write:

result = myOptional ?? "n/a" 
like image 44
MirekE Avatar answered Jan 01 '23 10:01

MirekE