Swift - Generics(泛型)

Swift - Generics(泛型) 首页 / Swift入门教程 / Swift - Generics(泛型)

Swift 4语言提供"Generic"函数来编写灵活且可重用的函数和类型,泛型用于避免重复并提供抽象, Swift 4标准库是使用泛型代码构建的。 Swift 4s的"Arrays"和"Dictionary"类型属于Generic集合。

func exchange(a: inout Int, b: inout Int) {
   let temp=a
   a=b
   b=temp
}

var numb1=100
var numb2=200

print("Before Swapping values are:\(numb1) and\(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping values are:\(numb1) and\(numb2)")

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

Before Swapping values are: 100 and 200
After Swapping values are: 200 and 100

 类型参数

泛型函数可用于访问任何数据类型,如" Int"或" String"。

func exchange<T>(a: inout T, b: inout T) {
   let temp=a
   a=b
   b=temp
}
var numb1=100
var numb2=200

print("Before Swapping Int values are:\(numb1) and\(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping Int values are:\(numb1) and\(numb2)")

var str1="Generics"
var str2="Functions"

print("Before Swapping String values are:\(str1) and\(str2)")
exchange(a: &str1, b: &str2)
print("After Swapping String values are:\(str1) and\(str2)")

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics

函数exchange()用于交换上面程序中描述的值,而<T>用作类型参数。第一次调用函数exchange()返回“ Int”值,第二次调用函数exchange()将返回“ String”值。尖括号内可以包含多个参数类型,以逗号分隔。

类型参数被命名为用户定义,以了解其所持有的类型参数的用途。Swift 4提供<T>作为通用类型参数名称。但是,诸如数组和字典之类的类型参数也可以称为键值,以标识它们属于“字典”类型。

struct TOS<T> {
   var items=[T]()
   mutating func push(item: T) {
      items.append(item)
   }
   mutating func pop() -> T {
      return items.removeLast()
   }
}

var tos=TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)

tos.push(item: "Generics")
print(tos.items)

tos.push(item: "Type Parameters")
print(tos.items)

tos.push(item: "Naming Type Parameters")
print(tos.items)

let deletetos=tos.pop()

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Type Parameters]
[Swift 4, Generics, Type Parameters, Naming Type Parameters]

扩展泛型类型

扩展stack属性以知道项目的顶部包含在'extension'关键字中。

struct TOS<T> {
   var items=[T]()
   mutating func push(item: T) {
      items.append(item)
   }
   mutating func pop() -> T {
      return items.removeLast()
   }
}
var tos=TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)

tos.push(item: "Generics")
print(tos.items)

tos.push(item: "Type Parameters")
print(tos.items)

tos.push(item: "Naming Type Parameters")
print(tos.items)

extension TOS {
   var first: T? {
      return items.isEmpty ? nil : items[items.count - 1]
   }
}
if let first=tos.first {
   print("The top item on the stack is\(first).")
}

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

["Swift 4"]
["Swift 4", "Generics"]
["Swift 4", "Generics", "Type Parameters"]
["Swift 4", "Generics", "Type Parameters", "Naming Type Parameters"]
The top item on the stack is Naming Type Parameters.

类型约束

Swift 4语言允许"类型约束"指定类型参数是从特定类继承还是确保协议符合标准。

func exchange<T>(a: inout T, b: inout T) {
   let temp=a
   a=b
   b=temp
}
var numb1=100
var numb2=200

print("Before Swapping Int values are:\(numb1) and\(numb2)")
exchange(a: &numb1, b: &numb2)
print("After Swapping Int values are:\(numb1) and\(numb2)")

var str1="Generics"
var str2="Functions"

print("Before Swapping String values are:\(str1) and\(str2)")
exchange(a: &str1, b: &str2)
print("After Swapping String values are:\(str1) and\(str2)")

当我们使用游乐场运行上述程序时,我们得到以下输出-

Before Swapping Int values are: 100 and 200
After Swapping Int values are: 200 and 100
Before Swapping String values are: Generics and Functions
After Swapping String values are: Functions and Generics

关联类型

Swift 4允许通过关键字" associatedtype"在协议定义中声明关联类型。

protocol Container {
   associatedtype ItemType
   mutating func append(item: ItemType)
   var count: Int { get }
   subscript(i: Int) -> ItemType { get }
}
struct TOS<T>: Container {
   //原始 Stack<T> 实现
   var items=[T]()
   mutating func push(item: T) {
      items.append(item)
   }
   mutating func pop() -> T {
      return items.removeLast()
   }
   
   //符合容器协议
   mutating func append(item: T) {
      self.push(item: item)
   }
   var count: Int {
      return items.count
   }
   subscript(i: Int) -> T {
      return items[i]
   }
}
var tos=TOS<String>()
tos.push(item: "Swift 4")
print(tos.items)

tos.push(item: "Generics")
print(tos.items)

tos.push(item: "Type Parameters")
print(tos.items)

tos.push(item: "Naming Type Parameters")
print(tos.items)

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Type Parameters]
[Swift 4, Generics, Type Parameters, Naming Type Parameters]

Where 声明

类型约束使用户可以定义对与通用函数或类型关联的类型参数的要求。为了定义关联类型的要求,将" where"子句声明为类型参数列表的一部分。 " where"关键字放置在类型参数列表之后,紧随其后的是关联类型的约束,类型与关联类型之间的相等关系。

protocol Container {
   associatedtype ItemType
   mutating func append(item: ItemType)
   var count: Int { get }
   subscript(i: Int) -> ItemType { get }
}
struct Stack<T>: Container {
   //原始 Stack<T> 实现
   var items=[T]()
   mutating func push(item: T) {
      items.append(item)
   }
   mutating func pop() -> T {
      return items.removeLast()
   }

   //符合容器协议
   mutating func append(item: T) {
      self.push(item: 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 {
   //检查两个容器是否包含相同数量的项目
   if someContainer.count != anotherContainer.count {
      return false
   }
   
   //检查每对项目,看看它们是否相等
   for i in 0..<someContainer.count {
      if someContainer[i] != anotherContainer[i] {
         return false
      }
   }
   //所有项目都匹配,所以返回 true
   return true
}  
var tos=Stack<String>()

tos.push(item: "Swift 4")
print(tos.items)

tos.push(item: "Generics")
print(tos.items)

tos.push(item: "Where Clause")
print(tos.items)

var eos=["Swift 4", "Generics", "Where Clause"]
print(eos)

运行上述程序时,我们得到以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/swift/swift-generics.html

来源:LearnFk无涯教程网

[Swift 4]
[Swift 4, Generics]
[Swift 4, Generics, Where Clause]
[Swift 4, Generics, Where Clause]

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

赵成的运维体系管理课 -〔赵成〕

从0开始学大数据 -〔李智慧〕

面试现场 -〔白海飞〕

视觉笔记入门课 -〔高伟〕

乔新亮的CTO成长复盘 -〔乔新亮〕

容量保障核心技术与实战 -〔吴骏龙〕

数据分析思维课 -〔郭炜〕

Rust 语言从入门到实战 -〔唐刚〕

好记忆不如烂笔头。留下您的足迹吧 :)