官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 深水埗区| 三门县| 海淀区| 台前县| 宁德市| 小金县| 天柱县| 南靖县| 定陶县| 合山市| 常宁市| 崇阳县| 克什克腾旗| 思南县| 宜兰市| 沙洋县| 百色市| 台东市| 洛扎县| 云浮市| 陕西省| 荃湾区| 太谷县| 龙岩市| 北海市| 略阳县| 阿尔山市| 昌邑市| 婺源县| 宁陕县| 南投县| 西乡县| 定西市| 巴里| 福贡县| 巴青县| 石棉县| 榆林市| 舞阳县| 蓬莱市| 孟津县|