class Animal {
func run() {
print("Animal run")
}
}
class Dog :Animal {
override func run() {
print("Dog run")
}
}
class Cat :Animal {
override func run() {
print("Cat run")
}
}
func AnimalRunPint<T:Animal>(animal:T) {
animal.run()
}
AnimalRunPint(animal:Dog())
AnimalRunPint(animal:Cat())
func findIndex<T: Equatable>(array: inout [T], valueToFind: inout T) -> Int? {
var index = 0
for value in array {
if value == valueToFind {
return index
} else {
index += 1
}
}
return nil
}
var array = [3.14159, 0.1, 0.25]
var valueToFind = 9.3
let doubleIndex = findIndex(array: &array, valueToFind: &valueToFind)
if let index = doubleIndex {
print("在浮点型数组中寻找到9.3,寻找索引为\(index)")
} else {
print("在浮点型数组中寻找不到9.3")
}
var array2 = ["Mike", "Malcolm", "Andrea"]
var valueToFind2 = "Andrea"
let stringIndex = findIndex(array: &array2, valueToFind: &valueToFind2)
if let index = stringIndex {
print("在字符串数组中寻找到Andrea,寻找索引为\(index)")
} else {
print("在字符串数组中寻找不到Andrea")
}
protocol Stackable{
associatedtype ItemType
mutating func push(item:ItemType)
mutating func pop() -> ItemType
}
struct Stack<T>:Stackable {
var store = [T]()
mutating func push(item:T){
store.append(item)
}
mutating func pop() -> T {
return store.removeLast()
}
}
var stackOne = Stack<String>()
stackOne.push(item: "hello")
stackOne.push(item: "swift")
stackOne.push(item: "world")
let t = stackOne.pop()
print("t = \(t)")
func pushItemOneToTwo<C1: Stackable, C2: Stackable>
(stackOne: inout C1, stackTwo: inout C2)
where C1.ItemType == C2.ItemType {
var item = stackOne.pop()
stackTwo.push(item: item)
}