How do I concatenate strings in Swift?

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

    Concatenation refers to the combining of Strings in Swift. Strings may contain texts, integers, or even emojis! There are many ways to String Concatenation. Let me enumerate some:

    Same String

    Using +=

    This is useful if we want to add to an already existing String. For this to work, our String should be mutable or can be modified, thus declaring it as a Variable. For instance:

    var myClassmates = "John, Jane"
    myClassmates += ", Mark" // add a new Classmate
    // Result: "John, Jane, Mark"
    

    Different Strings

    If we want to combine different Strings together, for instance:

    let oldClassmates = "John, Jane" 
    let newClassmate = "Mark"
    

    We can use any of the following:

    1) Using +

    let myClassmates = oldClassmates + ", " + newClassmate
    // Result: "John, Jane, Mark"
    

    Notice that the each String may be a Variable or a Constant. Declare it as a Constant if you're only gonna change the value once.

    2) String Interpolation

    let myClassmates = "\(oldClassmates), \(newClassmate)"
    // Result: "John, Jane, Mark"
    

    3) Appending

    let myClassmates = oldClassmates.appending(newClassmate)
    // Result: "John, Jane, Mark"
    

    Refer to Strings & Characters from the Swift Book for more.

    Update: Tested on Swift 5.1

提交回复
热议问题