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

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.

主站蜘蛛池模板: 固安县| 文山县| 庄浪县| 于田县| 奉新县| 潍坊市| 南宫市| 红原县| 韶山市| 清流县| 宜兰县| 黄大仙区| 靖州| 鄂伦春自治旗| 通榆县| 青海省| 宁阳县| 徐水县| 鄢陵县| 永州市| 中西区| 瑞安市| 开江县| 竹北市| 博客| 泰顺县| 恩施市| 洱源县| 陈巴尔虎旗| 富平县| 和政县| 卓尼县| 贡嘎县| 宁武县| 五指山市| 武宣县| 青阳县| 潞城市| 左云县| 柯坪县| 新邵县|