- Reactive Programming with Swift 4
- Navdeep Singh
- 242字
- 2021-06-24 18:57:59
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.
推薦閱讀
- PWA入門與實踐
- Node.js 10實戰
- Java程序設計實戰教程
- Vue.js前端開發基礎與項目實戰
- Magento 2 Theme Design(Second Edition)
- Python從入門到精通(精粹版)
- Visual C++應用開發
- Modern JavaScript Applications
- AppInventor實踐教程:Android智能應用開發前傳
- Python語言實用教程
- Python從入門到精通
- Learning Material Design
- Kotlin Programming By Example
- Visual FoxPro程序設計
- Unity AI Game Programming(Second Edition)