Search code examples
swiftstringsubscript

Cannot assign through subscript to Swift String


I have a class that contains a name, an image, a dashed form of the name, and the length of the name. For example, I could have "dog", an image of a dog, "---", and name length 3.

I just want to set name and pic for each object and have dashName and nameLength set automatically.

class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init(){

        var a = 0
        nameLength = name.characters.count

        while a <= nameLength {
            if (name[a] == " ") {dashName[a] = " "}
            else {dashName[a] = "-"}
            a += 1
        }
    }
}

The problem is the error that says: "cannot assign through subscript: subscript is get-only" and another error that says: "subscript is unavailable: cannot subscript String with an Int"


Solution

  • The subscript operator for String is get-only, which means you can only read from a string using it, and have to use something else to write to a mutable String.

    You can solve this issue, and clean up the code by using a map function on name

    Swift 4

    class Answer {
        var name = "name"
        var image: UIImage?
        var dashName = "name"
        var nameLength = 0
    
        init()
        {
            nameLength = name.count
            dashName = name.map { $0 == " " ? " " : "-" }.joined()
        }
    }
    

    Swift 3

    class Answer {
        var name = "name"
        var image: UIImage?
        var dashName = "name"
        var nameLength = 0
    
        init()
        {
            nameLength = name.characters.count
            dashName = name.characters.map { $0 == " " ? String(" ") : String("-") }.joined()
        }
    }