0

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

  • Have a look at http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language. – Martin R Apr 09 '17 at 16:34

1 Answers1

1

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)
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Thks I was just coding that already, fearing that I couldn't do it another way. Just not well convinced why the hell i can't access and change at a specific index just as another languages... – Layon Tavares Apr 09 '17 at 17:40
  • @LayonTavares Because unlike *most* languages, Swift's `String` is rigorously about properly and safely supporting Unicode. Read this for more information: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID293 – Alexander Apr 09 '17 at 17:42
  • @LayonTavares Here's an example of the types of bugs that can arise from the improper unicode support used by default in Java: https://repl.it/HCUn/1 – Alexander Apr 09 '17 at 17:47
  • @LayonTavares And here is that same example in Swift, which handles it correctly: https://repl.it/HCVH/1 – Alexander Apr 09 '17 at 17:52