Swift:可选值中的可选文本

前端之家收集整理的这篇文章主要介绍了Swift:可选值中的可选文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在不强制显示的情况下显示可选值上的可选(“”)文本.

更新

// 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)
let sessionApiURL = self.session?.apiURL ?? ""
var url = "\(sessionApiURL)/api/products.json"
原文链接:https://www.f2er.com/swift/320130.html

猜你在找的Swift相关文章