'How can I access private property outside that class in Swift? [duplicate]

Here I have a class and make its properties private to prevent from modifications by accident.

class Article {
    private var lineIndex: [Int] = []
    private var text: [String] = []

    ....
}

I know I can write a function like func text(_ index: Int) -> String to get its value at index. But when I call it, article1.text(2) would be weird. Because it's less clear to indicate 2 is an index than what an array does like article1.text[2]. So can I use getter or something else instead, while keeping the clear syntax like text[2]. It couldn't be better if you can offer some examples.



Solution 1:[1]

You can use one of these ways:

  • with private(set), which allows editable inside the class:
class Article {
    private(set) var text: [String] = []
    ...
}
  • with get only computed property (this is the same like your get function)
class Article {
    var _text: [String] {
        return text
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 son