Swift泛型
/// 泛型函数
var n1 = 10
var n2 = 20
func swapValues<T>(_ a: inout T, _ b: inout T) {
(a, b) = (b, a)
}
swapValues(&n1, &n2)
print(n1)
print(n2)
/// 泛型函数赋值给变量
var fn: (inout Int, inout Int) -> () = swapValues
/// 泛型类型
class Stack<E> {
var elements: [E] = []
init(firstElement: E) {
elements.append(firstElement)
}
func push(_ element: E) {
elements.append(element)
}
func pop() -> E {
return elements.removeLast()
}
func top() -> E? {
return elements.last
}
func size() -> Int {
return elements.count
}
}
var intStack = Stack(firstElement: 10)
//var intStack = Stack<Int>()
//var stringStack = Stack<String>()
//var anyStack = Stack<Any>()
/// 泛型继承
class SubStack<E>: Stack<E> {
}
/// 泛型结构体
struct StackStruct<E> {
var elements: [E] = []
mutating func push(_ element: E) {
elements.append(element)
}
mutating func pop() -> E {
return elements.removeLast()
}
func top() -> E? {
return elements.last
}
func size() -> Int {
return elements.count
}
}
/// 泛型枚举
enum Score<T> {
case point(T)
case grade(String)
}
let score0 = Score<Int>.point(10)
let score1 = Score.point(10.0)
let score2 = Score<Int>.grade("A")
/// 泛型本质, 根据类型元信息操作
/// 关联类型
/// 作用: 给协议中用到的类型定义一个占位名称
/// 协议可以有多个关联类型
protocol Stackable {
associatedtype Element
mutating func push(_ element: Element)
mutating func pop() -> Element
func top() -> Element?
func size() -> Int
}
class StringStack: Stackable {
var elements: [String] = []
func push(_ element: String) {
elements.append(element)
}
func pop() -> String {
return elements.removeLast()
}
func top() -> String? {
return elements.last
}
func size() -> Int {
return elements.count
}
}
/// 类型约束
protocol Runnable { }
class Person { }
func swapValues<T: Person & Runnable>(_ a: inout T, _ b: inout T) {
(a, b) = (b, a)
}
protocol Stackable1 {
associatedtype Element: Equatable
}
class Stack1<E: Equatable>: Stackable1 {
typealias Element = E
}
func equal<S1: Stackable1, S2: Stackable1>(_ s1: S1, _ s2: S2) -> Bool where S1.Element == S2.Element, S1.Element: Hashable {
return false
}
var s1 = Stack1<Int>()
var s2 = Stack1<Int>()
var s3 = Stack1<String>()
equal(s1, s2)
//equal(s1, s3) //error, S1.Element == S2.Element
/// 协议类型注意点
protocol Runnable1 {
associatedtype Speed
var speed: Speed { get }
}
class Person1: Runnable1 {
var speed: Double {
return 0.0
}
}
class Car1: Runnable1 {
var speed: Int {
return 0
}
}
//func get(_ type: Int) -> Runnable1 {
// if type == 0 {
// return Person1()
// } else {
// return Car1()
// }
//}
func get(_ type: Int) -> some Runnable1 {
return Car1()
}
var r1 = get(0) //Runnable1
var r2 = get(1) //Runnable1
/// 不透明类型的限制 (带有关联类型的协议)
/// 1. 只能返回一种明确类型, 这样才能确定关联类型
/// 2. some Runnable1 屏蔽一些内部实现细节, 只让外界知道是Runnable1
--EOF--
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于