정의
func greet(person: String) -> String P{
let greeting = "hello, " + person
return greeting
}
호출
print(greet(person: "Anna"))
func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
func greet(person: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return greetAgain(person: person)
} else {
return greet(person: person)
}
}
fucn greet(person: String) {
print("Hello, \(person)!")
}
greet(person: "Dave")
*주의 - 사실 ()를 사용한 빈 튜플인 Void라는 특별한 형을 반환한다.
func hi(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
~
return (currentMin, currentMax)
(min: Int, max: Int)?
실제 반환 값에 접근하기 위해서는 if let 과 같은 옵셔널 체인을 이용해 unwrapping 해줘야 한다.
if let bounds = minMax ~
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill! Glad you could visit from Cupertino."
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
// 함수 안에서 firstParameterName, secondParameterName
// 인자로 입력받은 첫번째, 두번째 값을 참조합니다.
}
someFunction(1, secondParameterName: 2)
(: Int = 12)과 같이 함수의 파라미터값에 기본값을 설정할 수 있다. 기본값이 설정되어 있는 파라미터는 함수 호출시 생략 가능하다.
인자 값으로 특정 타입의 집합 값을 사용할 수 있다.
(_ numbers: Dobule...)
인자 값을 직접 변경하는 파라미터로 inout 이라는 키워드를 사용한다.
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"
함수의 타입은 파라미터 타입과 반환 타입으로 구성되어 있다.
var mathFunction: (Int, Int) -> Int = addTwoInts
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Prints "Result: 8"
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}