一. 概念:简单的理解就是一个“泛化”的类型,并不特指某一个具体的类型;
func exchange(num1: inout Int,num2: inout Int)
{
let temp = num1;
num1 = num2
num2 = temp
}
var num1 = 10
var num2 = 20
exchange(num1: &num1, num2: &num2)
num1 //20
num2 //10
func exchange(num1:inout Double,num2:inout Double)
{
let temp = num1;
num1 = num2
num2 = temp
}
var num1 = 1.5
var num2 = 2.7
exchange(num1: &num1, num2: &num2)
num1 //2.7
num2 //1.5
二. 泛型的使用:
- 作为函数的参数或者返回值;
//泛型作为函数参数的使用
func fanExchange<T>(num1:inout T,num2:inout T){
let temp = num1
num1 = num2
num2 = temp
}
//整数
var num5 = 12
var num6 = 13
fanExchange(num1: &num5, num2: &num6)
num5 //13
num6 //12
//小数
var num7 = 1.8
var num8 = 1.9
fanExchange(num1: &num7, num2: &num8)
num7 //1.9
num8 //1.8
//泛型作为函数返回值的使用
func fanSquare<T>(num:T) -> T{
return num
}
let fanS = fanSquare(num: 8) //8
let fanS2 = fanSquare(num: 2.5)*fanSquare(num: 3) //7.5
let fanS3 = fanSquare(num: "abc") + fanSquare(num: "123") //abc123
- 泛型与类型的结合;
//泛型与结构体的结合
struct Point<TT>{
var x:TT
var y:TT
}
let point1 = Point(x: 3, y: 5) //Point<Int>
let point2 = Point(x: 3.1, y: 3.2) //Point<Double>
let point3 = Point(x: "abc", y: "xyz") //Point<String>
//泛型与类的结合
//泛型与类的结合
class Student<TT>{
var a:TT?
var b:TT?
init(a:TT) {
self.a = a
}
}
let student = Student(a: 4.3) //Student<Double>
//泛型与协议的结合
protocol Live{
//实现协议时,会确定TT的类型
associatedtype TT
//当实现这个方法时,就会确定TT是什么类型
func eat() -> TT
func work() -> TT
}
//人
class Person:Live{
func eat() -> Person {
print("人吃饭")
return self
}
func work() -> Person {
print("人工作")
return self
}
}
let person1 = Person()
person1.eat().work()
//Dog类
class Dog:Live{
func eat() -> Dog {
print("小狗吃饭")
return self
}
func work() -> Dog {
print("小狗看门")
return self
}
}
let dog = Dog()
dog.eat().work()
- 泛型与where子句的结合使用。
func testProtocol<T>(a:T) where T:Dog{
//做一系列处理
}
testProtocol(a: dog)
网友评论