简体   繁体   中英

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

I'm using the Mapper library with Swift for 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.

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. It's a lot more compact than 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 :

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

map.from(value).nilIfEmpty()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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