Swift基础 泛型

泛型

在程序设计中,要实现任意数据类型执行统一的一段操作,可以运用模版,对于整型、字符型、浮点型或者其他类型,均可以实现,这就叫泛型,可以重复利用。
编写泛型函数的步骤是:将涉及不同代码的部分用T表示。

    struct Student {
    
    
        var name = "name"
        var height = 160.00
    }
    
    override func viewDidLoad() {
    
    
        super.viewDidLoad()
        
        var xiaoMing = Student()
        var xiaoHong = Student()
        
        xiaoMing.name = "xiaoHong"
        xiaoHong.name = "xiaoMing"
        xiaoMing.height = 172.5
        xiaoHong.height = 168.5
        print("交换之前:\n xiaoMing:\(xiaoMing)\n xiaoHong:\(xiaoHong)")
        //名字搞错了,交换一下
        exchange(objectA: &xiaoHong.name, objectB: &xiaoMing.name)
        //身高也搞错了,交换一下
        exchange(objectA: &xiaoHong.height, objectB: &xiaoMing.height)
        print("交换之后:\n xiaoMing:\(xiaoMing)\n xiaoHong:\(xiaoHong)")
    }
    
    func exchange<T>(objectA:inout T,objectB:inout T) {
    
    
        let temp = objectA
        objectA = objectB
        objectB = temp
    }

inout关键字表示可以修改外部的变量值。
运行结果:

交换之前:
 xiaoMing:Student(name: "xiaoHong", height: 172.5)
 xiaoHong:Student(name: "xiaoMing", height: 168.5)
交换之后:
 xiaoMing:Student(name: "xiaoMing", height: 168.5)
 xiaoHong:Student(name: "xiaoHong", height: 172.5)

猜你喜欢

转载自blog.csdn.net/kkkenty/article/details/124607261