Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an optional string extension?

You can create a String extension like so:

extension String {    func someFunc() -> Bool { return true } } 

but what if you want it to apply to optional string?

var optionalString: String? = "" optionalString!.someFunc() /* String? does not have a member someFunc */ 

Attempting to add extension String? { produces the error:

Constrained extension must be declared on the unspecialized generic type 'Optional' with constraints specified by a 'where' clause

like image 529
vol7ron Avatar asked Apr 05 '15 22:04

vol7ron


People also ask

How do you declare an optional string?

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".

What is optional extension?

Optional Extension Period means the period of time after the end of the Policy Period for reporting Claims as provided in Clause XII.

Which is optional in variable declaration?

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.

What is optional Xcode?

Optionals say either "there is a value, and it equals x" or "there isn't a value at all". An Optional is a type on its own, actually one of Swift 4's new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift 4.


2 Answers

In Swift 3.1 you can add an extension to optional values as well:

extension Optional where Wrapped == String {   var isBlank: Bool {     return self?.isBlank ?? true   } } 
like image 139
Vladyslav Zavalykhatko Avatar answered Oct 10 '22 23:10

Vladyslav Zavalykhatko


You can do it like this:

protocol OptionalType { typealias A; var opt: A? { get } } extension Optional: OptionalType { var opt: A? { return self } }  protocol StringType { var get: String { get } } extension String: StringType { var get: String { return self } }  extension Optional where Wrapped: StringType {   func getOrElse(s: String) -> String {     return self.opt?.get ?? s   } } 

And:

let optStr: String? = nil optStr.getOrElse("hello world") 

The reason that you cannot constrain Optional or String for that matter, is because they are struct. By making pseudo-protocol for each, now we can constrain as we like.

I feel like swift has given up a lot of things just to make it easier for beginners to learn or maybe the language hasn't matured enough yet.

like image 22
Daniel Shin Avatar answered Oct 11 '22 00:10

Daniel Shin