Swift 通用類型和通用函數 | Generic type and function

來源:互聯網
上載者:User

標籤:

如果你想交換兩個變數的值:

1. 整型

func swapTwoInts(inout a: Int, inout b: Int) {let temporaryA = aa = bb = temporaryA}

2. 字串

func swapTwoStrings(inout a: String, inout b: String) {    let temporaryA = a    a = b    b = temporaryA}

3. 浮點型

... 應該不用我寫了吧.

也許你自己寫完都覺得累,那怎麼弄呢? 別忘了Swift很高大上的。

通用類型 也就是一個通用類型可以適用於不同的傳統類型,無需再去指定具體類型了。

func swapTwoValues<T>(inout a: T, inout b: T) {    let temporaryA = a    a = b    b = temporaryA}
var a = 10var b = 20swapTwo(&a, &b)

var a = 10

var b = 20

swapTwo(&a, &b)

println("\(a)"+"------"+"\(b)")

結果:

"20------10"

 

Swift 通用類型和通用函數 | Generic type and function

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.