简体   繁体   中英

Swift, Joining (Implicitly Unwrapped) Optional Strings with a joiner

I've tried to join some [String!] . So i'm making like this :

extension String {
    func join(strings: String!... ) -> String {
        return self.join(strings.filter({ $0?.isEmpty == false }).map {$0 as String})
    }
}

var country: String! = nil
var city: String! = ""
var address: String! = "Nowon"
var detailAddress: String! = "Gongneung-dong"

let combinedAddress = " ".join(country, city, address, detailAddress)

But, still it seems to be complicated. How do i optimize this?

If you always know that they can be unwrapped, then you can easily join strings

var a = "this is a "
var b = "this is b "
var c = "this is c"
let myString = a + b + c

I do similar things in my code but first I check if a string is empty

if a.isEmpty == false { }

Is a quick way to do that

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