- 给一个数组,要求写一个函数,交换数组中的两个元素
func swap<T>(to array: inout [T], swap sIndex: Int, for dIndex: Int) -> Bool {
guard !array.isEmpty else {
debugPrint(" source array is empty ! ")
return false
}
guard array.count - 1 >= sIndex && sIndex >= 0 ,array.count - 1 >= dIndex && dIndex >= 0 else {
debugPrint("index out of bounds!")
return false
}
(array[sIndex], array[dIndex]) = (array[dIndex], array[sIndex])
return true
}
使用
var array = ["1","2","3"]
debugPrint(swap(to: &array, swap: 2, for: 1))
注意:
swift 泛型,Tuple,以及对异常处理的思考。
- 实现一个函数,输入是任一整数,输出要返回输入的整数 + 2
enum OperationMode {
case add
case reduce
case multiply
case divide
}
func operation(_ a: Int, _ b: Int, _ mode: OperationMode) -> Int {
switch mode {
case .add:
return a + b
case .reduce:
return a - b
case .multiply:
return a * b
case .divide:
return a / b
}
}
func addTwo(_ a: Int) -> Int {
return operation(a, 2, .add)
}
debugPrint(addTwo(2))
网友评论