func minMax(array:[Int])->(min:Int,max:Int){
var currentMin = array[0]
var currentMax = array[1]
for value in array[1..<array.count]{
if value < currentMin{
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return (currentMin,currentMax)
}
func swapTwoInts(_ a:inout Int, _ b: inout Int){
let temporaryA = a
a=b
b=temporaryA
}
스위프트에서는 파라메터가 상수로 들어와 함수내부에서 파라메터 수정이 불가능하다.
해서 inout 키워드로 파라메터 변수를 선언하게 되면 파라메터의 주소값이 넘어오게 된다.
함수 호출시 변/상수의 주소값을 전달하기 위해 &키워드로 함수를 호출해야한다.
var someInt = 3
var anotherInt = 106
//&키워드로 호출해야함
swapTwoInt(&someInt,&anotherInt)
//두변수 값이 바뀜을 확인
스위프트는 함수형 언어로 함수가 1급 객체이다.
//1번
func addTwoInts(_ a:Int, _b: Int)->Int{
return a+b
}
//2
func printHelloWorld(){
print("Hello world~!")
}
//활용
let mathFunction:(Int,Int)->Int = addTwoInts
예시 1번의 Function type은 (Int,Int) → Int이다.
예시 2번의 Function type은 () → Void
Function type을 사용하여 변수에 함수를 저장 할 수 있다.
Function Types as Paramater Types
func printMathResult(_ mathFunction: (Int,Int)->Int, _ a:Int,_ b:Int){
print("Result:\\(mathFunction(a,b))")
}
printMathResult(addTwoInts,3,5)
//print "Result:8":