In C++ you can specify "public: / private:" sections within your class definitions. Is there a way to do this in Swift 3 or do I have to use the keyword "private" on front of every object I wish to be private?
Asked
Active
Viewed 283 times
0
-
You have to do it on every object. I do not think there is other way. – gasho Mar 28 '17 at 16:07
1 Answers
2
If you have
class MyClass {
}
You can declare scoped extensions, e.g.
fileprivate extension MyClass {
var someThing: String { // This computed property is fileprivate
return "ABC"
}
func doSomething() { // This func is fileprivate
}
}
public extension MyClass {
var someOtherThing: String { // This computed property is public
return "123"
}
func doSomethingElse() { // This func is public
}
}
However, you can only declare stored properties in your class definition, so this won't work…
private extension MyClass {
let myName = "Fred"
}
In this case you need to apply the scope keyword to the property itself…
class MyClass {
private let myName = "Fred"
}

Ashley Mills
- 50,474
- 16
- 129
- 160
-
Just one note, private extensions can contain static private properties which can be used in the body of the extension. – JAL Mar 28 '17 at 16:27
-
This `fileprivate` keyword is available in swift 2.3? Or starts from swift 3.0. – Exploring Sep 12 '17 at 08:00
-