小编典典

Swift:可选值中的可选文本

swift

如何Optional("")在显示时删除可选值上的文本而不必强制输入!

更新资料

// 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

阅读 203

收藏
2020-07-07

共1个答案

小编典典

您可以使用??(null合并运算符)解开它,并提供默认值(如果为nil)

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