Swift語言中的一些訪問控制設(shè)置詳解
限制訪問代碼塊,模塊和抽象通過訪問控制來完成。類,結(jié)構(gòu)和枚舉可以根據(jù)自己的屬性,方法,初始化函數(shù)和下標(biāo)來通過訪問控制機制進行訪問。常量,變量和函數(shù)的協(xié)議限制,并允許通過訪問控制來訪問全局和局部變量。應(yīng)用于屬性,類型及函數(shù)的訪問控制可以被稱為“實體”。
訪問控制模型是基于模塊和源文件的。
模塊定義為代碼分配一個單獨的單元,并且可以使用import 關(guān)鍵字導(dǎo)入。源文件被定義為一個單一的源代碼文件,模塊可訪問多種類型和函數(shù)。
三種不同的訪問級別是由 Swift 語言提供。它們分別是 Public, Internal 和 Private 訪問。
語法
public class SomePublicClass {}
internal class SomeInternalClass {}
private class SomePrivateClass {}
public var somePublicVariable = 0
internal let someInternalConstant = 0
private func somePrivateFunction() {}
對于函數(shù)類型的訪問控制
某些函數(shù)可能有參數(shù)在函數(shù)聲明中但沒有任何返回值。下面的程序聲明 a 和 b 作為參數(shù)傳遞給sum()函數(shù)。內(nèi)部函數(shù)本身為參數(shù)a和b的值是通過調(diào)用所述通過調(diào)用函數(shù) sum(),其值被打印從而不用返回值。為了使函數(shù)的返回類型為私有,聲明函數(shù)使用 private 修飾整體訪問級別。
private func sum(a: Int, b: Int) {
let a = a + b
let b = a - b
println(a, b)
}
sum(20, 10)
sum(40,10)
sum(24,6)
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
(30, 20) (50, 40) (30, 24)
對于枚舉類型的訪問控制
public enum Student{
case Name(String)
case Mark(Int,Int,Int)
}
var studDetails = Student.Name("Swift")
var studMarks = Student.Mark(98,97,95)
switch studMarks {
case .Name(let studName):
println("Student name is: \(studName).")
case .Mark(let Mark1, let Mark2, let Mark3):
println("Student Marks are: \(Mark1),\(Mark2),\(Mark3).")
default:
println("Nothing")
}
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
Student Marks are: 98,97,95
枚舉在Swift語言中將自動接收枚舉個體并都具有相同的訪問級別。例如,考慮訪問固定于三個科目枚舉名稱,學(xué)生的名字和標(biāo)記被聲明為 student 而存在于枚舉類中的成員都屬于字符串?dāng)?shù)據(jù)類型名稱,標(biāo)記表示為 mark1, mark2 和 mark3 數(shù)據(jù)類型為整數(shù)。要訪問無論是學(xué)生名稱或標(biāo)記分數(shù)。 現(xiàn)在,如果被執(zhí)行 Switch case 塊將打印學(xué)生姓名,否則它將打印由學(xué)生固定的標(biāo)記。如果這兩個條件都失敗默認塊將被執(zhí)行。
子類訪問控制
Swift 允許用戶子類,可以在當(dāng)前訪問上下文存取的任何類。子類不能比其超類有更高的訪問級別。 用戶限制一個公共子類寫入一個內(nèi)部超類。
public class cricket {
private func print() {
println("Welcome to Swift Super Class")
}
}
internal class tennis: cricket {
override internal func print() {
println("Welcome to Swift Sub Class")
}
}
let cricinstance = cricket()
cricinstance.print()
let tennisinstance = tennis()
tennisinstance.print()
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
Welcome to Swift Super Class Welcome to Swift Sub Class
常量,變量,屬性和下標(biāo)訪問控制
Swift 常量,變量或?qū)傩圆荒鼙欢x比其類型更公開。這是無效一個 public 屬性與 private 類型的寫法。同樣,下標(biāo)不能超過其索引或返回類型更公開。
當(dāng)一個常量,變量,屬性或下標(biāo)使用了一個私有類型,則常量,變量,屬性或下標(biāo),也必須標(biāo)記為私有:
getter和setter常量,變量,屬性和標(biāo)自動接收它們屬于相同的訪問級別的常量,變量,屬性或下標(biāo)。
class Samplepgm {
private var counter: Int = 0{
willSet(newTotal){
println("Total Counter is: \(newTotal)")
}
didSet{
if counter > oldValue {
println("Newly Added Counter \(counter - oldValue)")
}
}
}
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
Total Counter is: 100 Newly Added Counter 100 Total Counter is: 800 Newly Added Counter 700
訪問控制的初始化和默認初始化器
自定義初始化函數(shù)可分配的接入級別小于或等于它們初始化的類型。一個必需的初始化必須具有相同的訪問級別,因為它們和類相同。一個初始化的參數(shù)的類型不能比初始化自己的訪問級別更私密(更高)。
聲明每個和初始化每個子類, “required” 關(guān)鍵字需要在init()函數(shù)之前定義。
class classA {
required init() {
var a = 10
println(a)
}
}
class classB: classA {
required init() {
var b = 30
println(b)
}
}
let res = classA()
let print = classB()
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
10 30 10
默認初始化具有相同的訪問級別,因為它初始化,除非該類型被定義為公共類型。 當(dāng)默認初始化定義為公共它被認為是內(nèi)部的。當(dāng)用戶需要一個公共類型在另一個模塊中的一個無參數(shù)初始化進行初始化,明確提供一個公共的無參數(shù)初始化作為類型定義的一部分。
對于協(xié)議的訪問控制
當(dāng)我們定義一個新的協(xié)議,從現(xiàn)有的協(xié)議繼承的功能,既有聲明相同的訪問級別以相互繼承屬性。Swift 訪問控制允許用戶定義 “public” 協(xié)議,它繼承自 “internal” 的協(xié)議。
public protocol tcpprotocol {
init(no1: Int)
}
public class mainClass {
var no1: Int // local storage
init(no1: Int) {
self.no1 = no1 // initialization
}
}
class subClass: mainClass, tcpprotocol {
var no2: Int
init(no1: Int, no2 : Int) {
self.no2 = no2
super.init(no1:no1)
}
// Requires only one parameter for convenient method
required override convenience init(no1: Int) {
self.init(no1:no1, no2:0)
}
}
let res = mainClass(no1: 20)
let print = subClass(no1: 30, no2: 50)
println("res is: \(res.no1)")
println("res is: \(print.no1)")
println("res is: \(print.no2)")
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
res is: 20 res is: 30 res is: 50
擴展訪問控制
當(dāng)用戶使用擴展來添加協(xié)議的一致性,Swift 不允許用戶為擴展提供一個明確的訪問級別修飾符。對于在每個協(xié)議的擴展,要求實現(xiàn)的默認訪問級別設(shè)置自己的協(xié)議訪問級別。
對于泛型訪問控制
泛型允許用戶指定最小訪問級別來訪問類型約束其類型參數(shù)。
public struct TOS<T> {
var items = [T]()
private mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var tos = TOS<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Type Parameters")
println(tos.items)
tos.push("Naming Type Parameters")
println(tos.items)
let deletetos = tos.pop()
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Type Parameters] [Swift, Generics, Type Parameters, Naming Type Parameters]
對于類型別名訪問控制
用戶可以定義類型別名對待不同的訪問控制類型。 相同的訪問級別或不同的訪問級別可以由用戶定義。當(dāng)類型別名為 “private” 及其相關(guān)成員可以聲明為 “private,內(nèi)部 public 類型 ”。當(dāng)類型別名是公共成員不能是別名為 “internal” 或 “private” 的名稱
定義任何類型別名被視為用于不同類型的訪問控制的目的。一個類型別名可以具有小于或等于它的一個訪問級別別名的類型的訪問級別。例如,private類型別名可以別名為 private, internal, 或 public,而 public 類型別名不能別名為 internal 或 private 類型。
public protocol Container {
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct Stack<T>: Container {
// original Stack<T> implementation
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
var tos = Stack<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Where Clause")
println(tos.items)
var eos = ["Swift", "Generics", "Where Clause"]
println(eos)
當(dāng)我們使用 playground 運行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Where Clause] [Swift, Generics, Where Clause]
相關(guān)文章
在一個項目中同時使用Swift和Objective-C代碼混合編程的方法
這篇文章主要介紹了在一個項目中同時使用Swift和Objective-C代碼的方法,在一個工程中同時使用Swift和Objective-C混合語言編程的方法,需要的朋友可以參考下2014-07-07詳解Swift的switch...case語句中break關(guān)鍵字的用法
這篇文章主要介紹了Swift的switch...case語句中break關(guān)鍵字的用法,是Swift入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-04-04本地推送通知UserNotifications在Swift中的實現(xiàn)方式
這篇文章主要介紹了本地推送通知UserNotifications在Swift中的實現(xiàn)方式,想了解消息推送的同學(xué),一定要看一下2021-04-04