How do I concatenate strings in Swift?

前端 未结 20 1791
梦毁少年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 04:06

    From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.” :

    To combine (concatenate) two strings, the simplest approach is to use the + operator:

    let s = "hello"
    let s2 = " world"
    let greeting = s + s2
    

    This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation). The + operator comes with a += assignment shortcut; naturally, the variable on the left side must have been declared with var:

    var s = "hello"
    let s2 = " world"
    s += s2
    

    As an alternative to +=, you can call the append(_:) instance method:

    var s = "hello"
    let s2 = " world"
    s.append(s2)
    

    Another way of concatenating strings is with the joined(separator:) method. You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:

    let s = "hello"
    let s2 = "world"
    let space = " "
    let greeting = [s,s2].joined(separator:space)
    

提交回复
热议问题