當你在Swift編寫一個類時,默認其中任何屬性,方法都能被外部訪問的。有的時候我們不希望屬性或方法被外部訪問,希望私有化。
在swfit用于訪問控制的有三個關鍵字。
- public:公共訪問,允許在任何源文件中使用其定義模塊。如你使用XCTest測試某個類時,就需要在類前添加public。
- internal:swift默認訪問控制,允許在項目內訪問。
- private:私人訪問,只能在當前類中訪問。如果是在class前添加,則只能是當前文件訪問。
舉例說明:
~~~
public class SomePublicClass { // 明確 public class
public var somePublicProperty = 0 // 明確 public class 成員
var someInternalProperty = 0 // 默認 internal class 成員
private func somePrivateMethod() {} // 明確 private class 成員
}
class SomeInternalClass { // 默認 internal class
var someInternalProperty = 0 // 默認 internal class 成員
private func somePrivateMethod() {} // 明確 private class 成員
}
private class SomePrivateClass { // 明確 private class
var somePrivateProperty = 0 // 默認 private class 成員
func somePrivateMethod() {} // 默認 private class 成員
}
~~~
## 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-11-1 | 根據 [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Classes and Structures總結 |
版權所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結構體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運算符(Advanced Operators)