Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 686
Allan Macatingrao Avatar asked Apr 25 '26 18:04

Allan Macatingrao


1 Answers

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.

like image 191
Thanh Pham Avatar answered Apr 27 '26 08:04

Thanh Pham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!