编辑代码

// 定义一个泛型结构体
struct Stack<T> {
    var items = [T]()
    var hello: T

    init(items: [T], hello: T) {
        self.items = items
        self.hello = hello
    }

    mutating func push(item:T) {
        items.append(item)
    }
    
    mutating func pop() -> T {
        return items.removeLast()
    }
}

// 扩展泛型结构体
extension Stack {
    var topItem:T? {
        return items.isEmpty ? nil : items[items.count - 1]
    }

    // 类型明确的变量不能使用泛型
    var countT: Int? {
        return items.isEmpty ? nil : items.count - 1
    }
}

// 定义一个泛型函数,把2个参数的值进行交换
func swapTwoValues<T>(valueOne:T , valueTwo:T) -> [T] {
    let temporaryA = valueOne
    var valueOne = valueTwo
    var valueTwo = temporaryA
    return [valueOne, valueTwo]
}

// 测试函数
print(swapTwoValues(valueOne: 1, valueTwo: 2))
print(swapTwoValues(valueOne: "一", valueTwo: "二"))
print(swapTwoValues(valueOne: [1,2], valueTwo: [2,1]))

// 测试结构体
var hello1 = Stack(items:[1,2],hello: 1)
hello1.push(item: 3)
print(hello1)
print(hello1.topItem,hello1.countT)

var hello2 = Stack(items:["one","two"],hello: "one")
hello2.push(item: "three")
print(hello2)