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

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.

主站蜘蛛池模板: 沽源县| 肃北| 石屏县| 青海省| 乐平市| 腾冲县| 濮阳市| 陆良县| 剑川县| 乌什县| 巴彦县| 德阳市| 中卫市| 鄂托克前旗| 三原县| 南开区| 塘沽区| 海原县| 咸阳市| 奇台县| 尚志市| 通化市| 阜新| 原平市| 大厂| 合江县| 肥东县| 昆山市| 内丘县| 荆门市| 兖州市| 新密市| 涟水县| 墨竹工卡县| 绥宁县| 仪征市| 腾冲县| 南开区| 依安县| 巫溪县| 湖州市|