Swift:可选值中的可选文本

时间:2014-09-11 04:59:35

标签: swift optional

如何在不强制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

3 个答案:

答案 0 :(得分:3)

您可以使用??(空合并运算符)来展开它,如果它是nil则提供默认值

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

答案 1 :(得分:2)

您可以使用此广告连播http://cocoapods.org/pods/NoOptionalInterpolation

或者,将此代码添加到项目中以删除字符串插值中的Optional(...)和nil文本:

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() ?? "")
    }
}

请注意,简单地覆盖description的{​​{1}}函数不适用于字符串插值,尽管它适用于Optional

答案 2 :(得分:0)

如果您想要没有可选值,则必须打开Optional。您可以使用"可选绑定"打开一个可选:

if let url = self.session?.apiURL{
     //you can use url without optional
     print(url)
}

您可以在online swift playground中查看我的示例,以便更好地理解。