简体   繁体   English

如何在Swift中为此通用数据类型添加扩展名?

[英]How do I add an extension for this generic data type in Swift?

I'm using the Mapper library with Swift for JSON. 我正在将Swift的Mapper库用于JSON。

To get it into a variable you do something like: 要将其放入变量,您可以执行以下操作:

try firstName = map.from("first_name")

With autocomplete I can see the result of map.from is a value of type T which is a generic I think. 使用自动完成功能,我可以看到map.from的结果是类型T的值,我认为这是一个泛型。

I want to add a nilIfEmpty method like map.from(value).nilIfEmpty() so that if the json is just "" I'll have it be nil. 我想添加一个nilIfEmpty方法,如map.from(value).nilIfEmpty()这样,如果json只是""我将其设为nil。 It's a lot more compact than map.from(value) == "" ? nil : map.from(value) 它比map.from(value) == "" ? nil : map.from(value)更紧凑map.from(value) == "" ? nil : map.from(value) map.from(value) == "" ? nil : map.from(value)

How would I write this though? 我该怎么写呢?

You could just extend String : 您可以只扩展String

extension String {
    func nilIfEmpty() {
        return self.isEmpty ? nil : self
    }
}

map.from(value).nilIfEmpty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM