这是一个泛型函数的代码示例,用于交换两个值:

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var x = 1
var y = 2
swapTwoValues(&x, &y)
print('x is now (x), and y is now (y)')

var stringValue1 = 'hello'
var stringValue2 = 'world'
swapTwoValues(&stringValue1, &stringValue2)
print('stringValue1 is now (stringValue1), and stringValue2 is now (stringValue2)')

这个函数可以接受任何类型的参数,并将它们交换。在这个例子中,我们使用了泛型类型 T,它可以是任何类型。在函数体内,我们创建了一个临时变量 temporaryA 来保存 a 的值,然后将 a 赋值为 b,最后将 b 赋值为 temporaryA。这个函数使用了 inout 关键字来表示参数是可修改的。

Swift 泛型函数代码示例 - 交换两个值

原文地址: https://www.cveoy.top/t/topic/njDn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录