How do I concatenate strings in Swift?

前端 未结 20 1729
梦毁少年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:02

    You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

    "".join(["string1", "string2", "string3"]) // "string1string2string"
    " ".join(["hello", "world"]) // "hello world"
    

    DISCLAIMER: I wrote this extension

    0 讨论(0)
  • 2020-11-28 04:04

    One can also use stringByAppendingFormat in Swift.

    var finalString : NSString = NSString(string: "Hello")
    finalString = finalString.stringByAppendingFormat("%@", " World")
    print(finalString) //Output:- Hello World
    finalString = finalString.stringByAppendingFormat("%@", " Of People")
    print(finalString) //Output:- Hello World Of People
    
    0 讨论(0)
  • 2020-11-28 04:05

    You can add a string in these ways:

    • str += ""
    • str = str + ""
    • str = str + str2
    • str = "" + ""
    • str = "\(variable)"
    • str = str + "\(variable)"

    I think I named them all.

    0 讨论(0)
  • 2020-11-28 04:06

    \ this is being used to append one string to another string.

    var first = "Hi" 
    var combineStr = "\(first) Start develop app for swift"
    

    You can try this also:- + keyword.

     var first = "Hi" 
     var combineStr = "+(first) Start develop app for swift"
    

    Try this code.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 04:06

    Swift 5

    You can achieve it using appending API. This returns a new string made by appending a given string to the receiver.

    API Details : here

    Use:

    var text = "Hello"
    text = text.appending(" Namaste")
    

    Result:

    Hello
    Hello Namaste
    
    0 讨论(0)
提交回复
热议问题