- 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.
推薦閱讀
- Testing with JUnit
- Web Development with Django Cookbook
- Internet of Things with the Arduino Yún
- C語(yǔ)言程序設(shè)計(jì)立體化案例教程
- Building a Recommendation Engine with Scala
- 深入RabbitMQ
- Access 2010數(shù)據(jù)庫(kù)應(yīng)用技術(shù)(第2版)
- Extending Puppet(Second Edition)
- 寫(xiě)給程序員的Python教程
- HTML+CSS+JavaScript網(wǎng)頁(yè)制作:從入門(mén)到精通(第4版)
- Web程序設(shè)計(jì):ASP.NET(第2版)
- Java EE 7 with GlassFish 4 Application Server
- Android技術(shù)內(nèi)幕(系統(tǒng)卷)
- Mastering OpenStack
- Elasticsearch搜索引擎構(gòu)建入門(mén)與實(shí)戰(zhàn)