我是新來的靜態類型的語言,並想知道是否有可能將一個Struct類型轉換爲它的類型來調用正確的重載函數?我遇到的問題是我有一個符合Mutation
協議的結構列表。我想遍歷列表併爲每個Struct調用正確的handle
函數。我會這樣handle
功能移動到結構本身,而是我想實現API我想看看如果這樣的事情是可能的,如下:對於實現相同協議的不同結構重載函數?
//: Playground - noun: a place where people can play
import UIKit
protocol Mutation {
func mutate(state: Int) -> Int
}
struct CountIncrement: Mutation {
func mutate(state: Int) -> Int {
return state + 1
}
}
struct CountDecrement: Mutation {
func mutate(state: Int) -> Int {
return state - 1
}
}
func handle(mutation: CountIncrement, state: Int) -> Int {
print("WILL INCREMENT")
return mutation.mutate(state: state)
}
func handle(mutation: CountDecrement, state: Int) -> Int {
print("WILL DECREMENT")
return mutation.mutate(state: state)
}
var state = 0
var queue = [CountIncrement(), CountDecrement()] as [Mutation]
for mutation in queue {
handle(mutation: mutation, state: state) // error: cannot invoke 'handle' with an argument list of type '(mutation: Mutation, state: Int)'
}