How do I concatenate strings in Swift?

前端 未结 20 1731
梦毁少年i
梦毁少年i 2020-11-28 03:04

How to concatenate string in Swift?

In Objective-C we do like

NSString *string = @\"Swift\";
NSString *resultStr = [string stringByAppen         


        
相关标签:
20条回答
  • 2020-11-28 03:50

    You can now use stringByAppendingString in Swift.

    var string = "Swift"
    var resultString = string.stringByAppendingString(" is new Programming Language")
    
    0 讨论(0)
  • 2020-11-28 03:52

    Xcode didn't accept optional strings added with a normal string. I wrote this extensions to solve that problem:

    extension String {
        mutating func addString(str: String) {
            self = self + str
        }
    }
    

    Then you can call it like:

    var str1: String?
    var str1 = "hi"
    var str2 = " my name is"
    str1.addString(str2)
    println(str1) //hi my name is
    

    However you could now also do something like this:

    var str1: String?
    var str1 = "hi"
    var str2 = " my name is"
    str1! += str2
    
    0 讨论(0)
  • 2020-11-28 03:53

    Swift 4.2

    You can also use an extension:

    extension Array where Element == String? {
        func compactConcate(separator: String) -> String {
            return self.compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: separator)
        }
    }
    

    Use:

    label.text = [m.firstName, m.lastName].compactConcate(separator: " ")
    

    Result:

    "The Man"
    "The"
    "Man"
    
    0 讨论(0)
  • 2020-11-28 03:55

    This will work too:

    var string = "swift"
    var resultStr = string + " is a new Programming Language"
    
    0 讨论(0)
  • 2020-11-28 03:55

    Very Simple:

    let StringA = "Hello"
    let StringB = "World"
    let ResultString = "\(StringA)\(StringB)"
    println("Concatenated result = \(ResultString)")
    
    0 讨论(0)
  • 2020-11-28 03:57
    let the_string = "Swift"
    let resultString = "\(the_string) is a new Programming Language"
    
    0 讨论(0)
提交回复
热议问题