How do I concatenate strings in Swift?

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

    To print the combined string using

    Println("\(string1)\(string2)")
    

    or String3 stores the output of combination of 2 strings

    let strin3 = "\(string1)\(string2)"
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 03:47

    You can concatenate strings a number of ways:

    let a = "Hello"
    let b = "World"
    
    let first = a + ", " + b
    let second = "\(a), \(b)"
    

    You could also do:

    var c = "Hello"
    c += ", World"
    

    I'm sure there are more ways too.

    Bit of description

    let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

    var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

    Note

    In reality let and var are very different from NSString and NSMutableString but it helps the analogy.

    0 讨论(0)
  • 2020-11-28 03:47

    I just switched from Objective-C to Swift (4), and I find that I often use:

    let allWords = String(format:"%@ %@ %@",message.body!, message.subject!, message.senderName!)
    
    0 讨论(0)
  • 2020-11-28 03:47

    Several words about performance

    UI Testing Bundle on iPhone 7(real device) with iOS 14

    var result = ""
    for i in 0...count {
        <concat_operation>
    }
    
    

    Count = 5_000

    //Append
    result.append(String(i))                         //0.007s 39.322kB
    
    //Plus Equal
    result += String(i)                              //0.006s 19.661kB
    
    //Plus
    result = result + String(i)                      //0.130s 36.045kB
    
    //Interpolation
    result = "\(result)\(i)"                         //0.164s 16.384kB
    
    //NSString
    result = NSString(format: "%@%i", result, i)     //0.354s 108.142kB
    
    //NSMutableString
    result.append(String(i))                         //0.008s 19.661kB
    

    Disable next tests:

    • Plus up to 100_000 ~10s
    • interpolation up to 100_000 ~10s
    • NSString up to 10_000 -> memory issues

    Count = 1_000_000

    //Append
    result.append(String(i))                         //0.566s 5894.979kB
    
    //Plus Equal
    result += String(i)                              //0.570s 5894.979kB
    
    //NSMutableString
    result.append(String(i))                         //0.751s 5891.694kB
    

    *Note about Convert Int to String

    Source code

    import XCTest
    
    class StringTests: XCTestCase {
    
        let count = 1_000_000
        
        let metrics: [XCTMetric] = [
            XCTClockMetric(),
            XCTMemoryMetric()
        ]
        
        let measureOptions = XCTMeasureOptions.default
    
        
        override func setUp() {
            measureOptions.iterationCount = 5
        }
        
        func testAppend() {
            var result = ""
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result.append(String(i))
                }
            }
    
        }
        
        func testPlusEqual() {
            var result = ""
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result += String(i)
                }
            }
        }
        
        func testPlus() {
            var result = ""
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result = result + String(i)
                }
            }
        }
        
        func testInterpolation() {
            var result = ""
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result = "\(result)\(i)"
                }
            }
        }
        
        //Up to 10_000
        func testNSString() {
            var result: NSString =  ""
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result = NSString(format: "%@%i", result, i)
                }
            }
        }
        
        func testNSMutableString() {
            let result = NSMutableString()
            measure(metrics: metrics, options: measureOptions) {
                for i in 0...count {
                    result.append(String(i))
                }
            }
        }
    
    }
    
    
    0 讨论(0)
  • 2020-11-28 03:49

    In Swift 5 apple has introduces Raw Strings using # symbols.

    Example:

    print(#"My name is "XXX" and I'm "28"."#)
    let name = "XXX"
    print(#"My name is \#(name)."#)
    

    symbol # is necessary after \. A regular \(name) will be interpreted as characters in the string.

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