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

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.

主站蜘蛛池模板: 麦盖提县| 财经| 体育| 马公市| 六枝特区| 南汇区| 青海省| 武平县| 鹤庆县| 灵丘县| 滨州市| 师宗县| 阿拉善左旗| 沁水县| 南陵县| 长沙县| 合作市| 盐津县| 普安县| 论坛| 辛集市| 洪湖市| 潞西市| 大名县| 同心县| 岳普湖县| 正宁县| 延长县| 无为县| 高平市| 察雅县| 辰溪县| 隆昌县| 铜陵市| 毕节市| 玉田县| 清远市| 沧源| 延津县| 富蕴县| 肥城市|