Search code examples
arraysswiftstringcharacter

How to Get and Set a string's character at a specific index in Swift


I would like to use something like arrayString[firstString][index] = "1"

But that results in: Cannot assign through subscript: subscript is get-only

And an explanation why the following code var arrayString: [String] = struct.strings

Does not permit the comparison first[index] == "0" so i need to use var arrayString = struct.strings


Solution

  • Depending on how many times you need to do this, it's probably best to just create a character array from the string, and index into that.

    You can either do it for just the string you care about:

    let strings = ["abcdefg", "123", "qwerty"]
    let characters = Array(strings[1].characters) // => ["1", "2", "3"]
    print(characters[0]) // => "1"
    

    or if you'll be doing lots of accesses to all of the strings, you can preemptively turn all strings into [Character] in advance, like so:

    let strings = ["abcdefg", "123", "qwerty"]
    let stringCharacters = strings.map { Array(string.characters) }
    /* [
           ["a", "b", "c", "d", "e", "f", "g"],
           ["1", "2", "3"],
           ["q", "w", "e", "r", "t", "y"]
       ] */
    print(characters[1][0]) // => "1"
    

    If you want to make a change, then simply convert the character array back into a String, and assign it wherever you want it:

    var strings = ["abcdefg", "123", "qwerty"]
    var characters = Array(strings[1].characters) // => ["1", "2", "3"]
    characters[0] = "0"
    strings[1] = String(characters)
    print(strings) // => ["abcdefg", "023", "qwerty"]
    

    Also, here's a handy extension I use for mutating many characters of a string:

    extension String {
        mutating func modifyCharacters(_ closure: (inout [Character]) -> Void) {
            var characterArray = Array(self.characters)
            closure(&characterArray)
            self = String(characterArray)
        }
    }
    
    
    var string = "abcdef"
    
    string.modifyCharacters {
        $0[0] = "1"
        $0[1] = "2"
        $0[2] = "3"
    }
    
    print(string)