Allan  Macatingrao
Allan Macatingrao

Reputation: 2101

Swift: Optional Text In Optional Value

How to remove Optional("") text on optional value when displaying without forcing to !.

Update

// I have somthing like this declared outside class
// I put question mark wrapper since I don't know when this session might have a value
var url = "\(self.session?.apiURL)/api/products.json"

// private session
private var _session:Session?

class MyClass
{
   .
   .
   .


   // the value of apiURL depends on session, session has optional value and declared as
   // custom lazy loaded var session
   var session:Session?
   {
      get
      {  
         if _session == nil 
         {
           _session = // fetch from coredata store if there is an active session. Might return nil

           // if no active session
           if _session == nil
           {
              // I just print "No active session"
           }
         }

         // return _session may or may not contain any value
         return _session
      }
   }
}

When the session has a value the url has a value:

Optional("my_api_url_here")/api/products.json

Upvotes: 3

Views: 2314

Answers (3)

slymnozdmrc
slymnozdmrc

Reputation: 400

If you want to without optional value you have to unwrap the Optional. You can use "optional binding" to unwrap an Optional:

if let url = self.session?.apiURL{
     //you can use url without optional
     print(url)
}

You can check my example in online swift playground for better understand.

Upvotes: 0

Thanh Pham
Thanh Pham

Reputation: 2090

You can use this pod http://cocoapods.org/pods/NoOptionalInterpolation.

Alternatively, add this code to your project to remove the Optional(...) and nil text in string interpolation:

public protocol Unwrappable {
    func unwrap() -> Any?
}

extension Optional: Unwrappable {
    public func unwrap() -> Any? {
        switch self {
        case .None:
            return nil
        case .Some(let unwrappable as Unwrappable):
            return unwrappable.unwrap()
        case .Some (let some):
            return some
        }
    }
}

public extension String {
    init(stringInterpolationSegment expr: Unwrappable) {
        self = String(expr.unwrap() ?? "")
    }
}

Please note that simply overriding the description function of Optional won't work for string interpolation, although it works for print.

Upvotes: 4

Bryan Chen
Bryan Chen

Reputation: 46598

you can use ?? (null coalescing operator) to unwrap it and provide a default value if it is nil

let sessionApiURL = self.session?.apiURL ?? ""
var url = "\(sessionApiURL)/api/products.json"

Upvotes: 3

Related Questions