Append String in Swift

前端 未结 12 1244
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 00:43

I am new to iOS. I am currently studying iOS using Objective-C and Swift.

To append a string in Objective-C I am using following code:

 NSString *str         


        
相关标签:
12条回答
  • 2020-12-03 00:58

    SWIFT 2.x

    let extendedURLString = urlString.stringByAppendingString("&requireslogin=true")
    

    SWIFT 3.0

    From Documentation: "You can append a Character value to a String variable with the String type’s append() method:" so we cannot use append for Strings.

    urlString += "&requireslogin=true"
    

    "+" Operator works in both versions

    let extendedURLString = urlString+"&requireslogin=true"
    
    0 讨论(0)
  • 2020-12-03 01:00

    Strings concatenate in Swift language.

    let string1 = "one"

    let string2 = "two"

    var concate = " (string1) (string2)"

    playgroud output is "one two"

    0 讨论(0)
  • 2020-12-03 01:01

    > Swift2.x:

    String("hello ").stringByAppendingString("world") // hello world
    
    0 讨论(0)
  • 2020-12-03 01:03

    Add this extension somewhere:

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

    Then you can call it like:

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

    A lot of good Swift extensions like this are in my repo here, check them out: https://github.com/goktugyil/EZSwiftExtensions

    0 讨论(0)
  • 2020-12-03 01:04

    According to Swift 4 Documentation, String values can be added together (or concatenated) with the addition operator (+) to create a new String value:

    let string1 = "hello"
    let string2 = " there"
    var welcome = string1 + string2
    // welcome now equals "hello there"
    

    You can also append a String value to an existing String variable with the addition assignment operator (+=):

    var instruction = "look over"
    instruction += string2
    // instruction now equals "look over there"
    

    You can append a Character value to a String variable with the String type’s append() method:

    let exclamationMark: Character = "!"
    welcome.append(exclamationMark)
    // welcome now equals "hello there!"
    
    0 讨论(0)
  • 2020-12-03 01:09

    You can simply append string like:

    var worldArg = "world is good"
    
    worldArg += " to live";
    
    0 讨论(0)
提交回复
热议问题