如何在不强制显示的情况下显示可选值上的可选(“”)文本.
更新
// 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 } } }
当会话具有值时,url具有值:
Optional("my_api_url_here")/api/products.json
您可以使用 ?? (null coalescing operator)打开它并提供默认值(如果它是nil)
原文链接:https://www.f2er.com/swift/320130.htmllet sessionApiURL = self.session?.apiURL ?? "" var url = "\(sessionApiURL)/api/products.json"