swift,functonType
functionType as Return Types, functionType을 ReturnType으로 쓸 수 있습니다.
//앞으로 한칸
func stepForward(input: Int) -> Int {
return input + 1
}
// 뒤로한칸
func stepBackward(input: Int) -> Int {
return input - 1
}
//선택
func chooseStepFunction(backword: Bool) -> (Int) -> Int {
return backword ? stepBackward : stepForward
}
//현재 3에 있을경우
var currentValue = 3
// moveTozero는 currentValue를 가지고 선택을 하도록합니다.
var MoveNeartToZero = chooseStepFunction(backword: currentValue > 0)
while currentValue != 0 {
//movetozero가 최초 3 backward값이 true
// chooseStepFunction에서 stepBackwoard가 호출되고 currentValue가 input값으로 들어가 -1감소하게 됩니다.
//.... 반복
// currentValue가 0 이되면 whil문이 더 이상 돌아가지않게됩니다.
currentValue = MoveNeartToZero(currentValue)
}
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backword: Bool) -> (Int) -> Int {
return backword ? stepBackward : stepForward
}
var currentValue = 3
while currentValue != 0 {
currentValue = chooseStepFunction(backword: currentValue > 0)(currentValue)
}
functionType as Paramter Types, functionType을 매개변수 type으로도 쓸 수 있습니다.
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
var mathfunction: (Int, Int) -> Int = addTwoInts
func printMathResult(mathfunction: (Int, Int) -> Int, a: Int, b: Int ) -> Int {
return mathfunction(a,b)
}
print(printMathResult(mathfunction: mathfunction, a: 102, b: 0))
functionType, 함수도 타입으로 사용할 수 있습니다. 일반적으로쓰닌 int와 같이 말이죠.
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
//타입을 정해주고, addTwoInts의 값을 줍니다.
var mathfunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathfunction(10,20))")