Home > Enterprise >  How can i disable adding new item to an array in Swift?
How can i disable adding new item to an array in Swift?

Time:08-02

I have an array like this inside a struct:

struct TestType {
    
    private(set) var array: [String] = ["0", "1", "2"]
    
    mutating func updateItem0(_ value: String) {
        self.array[0] = value
    }
    
    mutating func updateItem1(_ value: String) {
        self.array[1] = value
    }
    
    mutating func updateItem2(_ value: String) {
        self.array[2] = value
    }
}

I want be able to disable appending method to this array when I use an instance of struct, and keeping the count of it as it is. I cannot use private(set) because it would not allow me to update items of it.

My idea is using private(set) inside struct and making a mutating function for updating items in case, I wanted to know if there is better way for it?

CodePudding user response:

Lots of options but a simple enhancement would be passing the index:

mutating func update(_ value: String, at index: Int) {
    array[index] = value
}

And another is to check if the operation is possible:

enum Error: Swift.Error {
    case indexOutOfBound
}

mutating func update(_ value: String, at index: Int) throws {
    guard array.indices.contains(index) else { throw Error.indexOutOfBound }
    array[index] = value
}

CodePudding user response:

Here is a nice way to handle it. Add subscript to your struct which then allows you to access and change the values like you would an array. Adopting CustomStringConvertible and implementing description allows you to print the internal array while keeping it entirely private:

struct TestType: CustomStringConvertible {
    
    private var array: [String] = ["0", "1", "2"]

    var description: String { String(describing: array) }
 
    subscript(_ index: Int) -> String {
        get {
            return array[index]
        }
        set {
            array[index] = newValue
        }
    }
}

var foo = TestType()

foo[0] = "hello"
foo[2] = "goodbye"
foo[3] = "oops" // Fatal error: Index out of range

print(foo[0]) // hello
print(foo[1]) // 1
print(foo[2]) // goodbye
print(foo)    // ["hello", "1", "goodbye"]
  • Related