- 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.
推薦閱讀
- TypeScript Blueprints
- Go語言高效編程:原理、可觀測性與優化
- Java:Data Science Made Easy
- Visual C++串口通信技術詳解(第2版)
- Python機器學習:手把手教你掌握150個精彩案例(微課視頻版)
- Python面向對象編程:構建游戲和GUI
- 前端HTML+CSS修煉之道(視頻同步+直播)
- Mastering JavaScript Design Patterns(Second Edition)
- Python極簡講義:一本書入門數據分析與機器學習
- LabVIEW虛擬儀器程序設計從入門到精通(第二版)
- Fast Data Processing with Spark(Second Edition)
- Tableau Desktop可視化高級應用
- Hack與HHVM權威指南
- Python編程快速上手2
- Spring Boot 3:入門與應用實戰