網路上有許多很詳細的教學,這邊只整理具體用法,建議詳讀官方文件
我在寫App Project
internal
: 只開放這個Project內的所有.swift,允許Access, Subclass, Override
fileprivate
: 只開放同一個.swift,允許Access, Subclass, Override
private
: 只開放在宣告範圍內,允許Access, Subclass
fileprivate
vs private
struct Card {
var number: String?
}
struct Bag {
private var privateCard: Card?
fileprivate var fileCard: Card?
}
class BagWorker {
func updateCard(in bag: inout Bag, number: String) {
// 'privateCard' is inaccessible due to 'private' protection level
bag.privateCard?.number = number
bag.fileCard?.number = number
}
}
extension Bag {
// we can use extension to solve it
func updatePrivateCard(in bag: inout Bag, number: String) {
// but we only can use 'privateCard' through 'extension' in the SAME file
bag.privateCard?.number = number
}
}
我在寫Module / Framework Project
open
: 開放給其他Application Project,允許 Subclass, Override
public
: 開放給其他Application Project,只允許它們 Access(對內部沒有限制)
其他的跟App Project規則一樣
要怎麼練習?
可以透過Xcode的Playground,把 Sources
資料夾當作一個Module、.playground視為App Project。當要Access Sources裡的.swift時,會發現要加上 open
或 public
才行。