Access modifiers

The fileprivate access control modifier was used in Swift 3 to make important data visible outside the class in which it was declared but within the same file. This is how it all works in the case of extensions:

class Person {
fileprivate let name: String
fileprivate let age: Int
fileprivate let address: String
init(name: String, age: Int, address: String) {
self.name = name
self.age = age
self.address = address
}
}

extension Person {
func info() -> String {
return "(self.name) (self.age) (self.address)"
}
}

let bestFriend = Person(name: "Robert", age: 31)
bestFriend.info()

In the preceding code, we created an extension for the Person class and accessed its private properties in the info() method using String interpolation. Swift encourages the use of extensions to break code into logical groups. In Swift 4, you can now use the private access level instead of fileprivate in order to access class properties declared earlier, that is, in the extension:

class Person {
private let name: String
private let age: Int
private let address: String
init(name: String, age: Int, address: String) {
self.name = name
self.age = age
self.address = address
}
}
extension Person {
func info() -> String {
return "(self.name) (self.age) (self.address)"
}
}
let bestFriend = Person(name: "Robert", age: 31)
bestFriend.info()

These were all the changes introduced in Swift 4. Now we will take a look at the new introductions to the language.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset