Hokage Hokage - 6 months ago 22
Swift Question

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

Answer

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"