함수 정의 키워드는 func이다.
함수의 이름, 매개변수(parameter), 반환 타입(Return Type)등으로 함수를 정의한다.
함수 이름을 지정해준 후 매개변수는 소괄호(())로 감싸준다. '->'를 사용하여 어떤 타입이 반환(return)될 것인지 명시해준다.
기본 형태의 함수 정의와 사용
func hello(name: String) -> String {
return "Hello \(name)!"
}
let helloJenny: String = hello(name: "Jenny")
// 함수 = hello(name:), 매개변수 = name, 전달인자 = Jenny
print(helloJenny)
func introduce(name: String) -> String {
// [return "제 이름은 " + name + "입니다"]와 같은 작동을 합니다.
"제 이름은 " + name + "입니다"
}
let introduceJenny: String = introduce(name: "Jenny")
print(introduceJenny)
func helloWorld() -> String {
return "Hello, world!"
}
print(helloWorld()) // Hello, world!
func sayHello(myName: String, yourName: String) -> String {
return "Hello \(yourName)! I'm \(myName)"
}
print(sayHello(myName: "Jin", yourName: "Jenny"))
// "Hello Jenny! I'm Jin"
func 함수 이름(`전달인자 레이블` `매개변수1이름:` `매개변수1타입,` `전달인자 레이블` `매개변수2이름:`
`매개변수2타입`) -> `반환 타입` {
`실행 구문`
return `반환 값`
}
// from과 to라는 전달인자가 있으며
// myName과 name이라는 매개변수 이름이 있는 sayHello 함수
func sayHello(from myName:String, to name:String) -> String {
return "Hello \(name)! I'm \(myName)"
}
print(sayHello(from: "Jin", to: "Jenny"))
// Hello Jenny! I'm Jin
func sayHello(_ name: String, _ times: Int) -> String {
var result: String = ""
for _ in 0..<times {
result += "Hello \(name)!" + " "
}
return result
}
print(sayHello("Chope", 2))
//Hello Chope! Hello Chope!
func sayHello(to name: String, _ times: Int) -> String {
var result: String = " "
for _ in 0..<times {
result += "Hello \(name)!" + " "
}
return result
}
func sayHello(to name: String, repeatCount times: Int) -> String {
var result: String = " "
for _ in 0..<times {
result += "Hello \(name)!" + " "
}
return result
}
print(sayHello(to: "Chope", 2))
print(sayHello(to: "Chope", repeatCount: 2))
// 위의 ('전달인자 레이블이 없는 함수 정의와 사용'과 비슷한 함수)
func sayHello(_ name: String, times: Int = 3) -> String {
var result: String = ""
for _ in 0..<times {
result += "Hello \(name)!" + " "
}
return result
}
print(sayHello("Hana"))
// Hello Hana! Hello Hana! Hello Hana!
// times 매개변수의 전달 값을 넘겨주지 않아 기본값 3을 반영해서 3번 출력
print(sayHello("Joe", times: 2))
// Hello Joe! Hello Joe!
// times 매개변수의 전달 값을 2로 넘겨주었기 때문에 전달 값을 반영해서 2번 출력
func sayHelloToFriends(me: String, friends names: String...) -> String {
var result: String = ""
for friend in names {
result += "Hello \(friend)!" + " "
}
result += "I'm " + me + "!"
return result
}
print(sayHelloToFriends(me: "Jin", friends: "Johansson", "Jay", "Wizplan"))
// Hello Johansson! Hello Jay! Hello Wizplan! I'm Jin!
print(sayHelloToFriends(me: "Jin"))
// I'm Jin!
var numbers: [Int] = [1, 2, 3]
func nonReferenceParameter(_ arr: [Int]) {
var copiedArr: [Int] = arr
copiedArr[1] = 1
}
func referenceParameter(_ arr: inout [Int]) {
arr[1] = 1
}
nonReferenceParameter(numbers)
print(numbers[1]) // 2
referenceParameter(&numbers) // 참조를 표현하기 위해 & 붙여줌
print(numbers[1]) // 1
func sayHelloWorld() {
print("Hello, world!")
}
sayHelloWorld() // Hello, world!
func sayHello(from myName: String, to name: String) {
print("Hello \(name)! I'm \(myName)")
}
sayHello(from: "Jin", to: "Mijeong") // Hello Mijeong! I am Jin
func sayGoodbye() -> Void { // Void를 명시해주어도 상관없음
print("Good bye")
}
sayGoodbye() // Good bye
(매개변수 타입의 나열) -> 반환 타입
// 동일한 표현
sayHello(name: String, times: Int) -> String
sayHello(name:times:)
typealias CalculateTwoInts = (Int, Int) -> Int
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
var mathFunction: CalculateTwoInts = addTwoInts
// var mathFunction: (Int, Int) -> Int = addTwoInts
print(mathFunction(2,5)) // 2 + 5 = 7
mathFunction = multiplyTwoInts
print(mathFunction(2,5)) // 2 * 5 = 10
func printMathResult(_ mathFunction: CalculateTwoInts, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Result: 8
// -3 | -2 | -1 | 0 | 1 | 2 | 3 | .... 이런 게임판이 있다는 가정
// 원점으로 이동하기 위한 함수
typealias MoveFunc = (Int) -> Int
func goRight(_ currentPosition: Int) -> Int {
return currentPosition + 1
}
func goLeft(_ currentPosition: Int) -> Int {
return currentPosition - 1
}
func functionForMove(_ shouldGoLeft: Bool) -> MoveFunc {
return shouldGoLeft ? goLeft : goRight
}
var position: Int = 3 // 현 위치
let moveToZero: MoveFunc = functionForMove(position > 0)
print ("원점으로 갑시다.")
// 원점에 도착하면(현 위치가 0이면) 반복문 종료
while position != 0 {
print("\(position)...")
position = moveToZero(position)
}
print("원점 도착!")
//3... 2... 1... //원점 도착!
typealias MoveFunc = (Int) -> Int
func functionForMove(_ shouldGoLeft: Bool) -> MoveFunc {
func goRight(_ currentPosition: Int) -> Int {
return currentPosition + 1
}
func goLeft(_ currentPosition: Int) -> Int {
return currentPosition - 1
}
return shouldGoLeft ? goLeft : goRight
}
var position: Int = -4 // 현 위치
// 현 위치가 0보다 작으므로 전달되는 인자 값은 false가 됨
// 그러므로 goRight(_:) 함수가 할당됨
let moveToZero: MoveFunc = functionForMove(position > 0)
// 원점에 도착하면(현 위치가 0이면) 반복문이 종료됨
while position != 0 {
print(":\(position)...")
position = moveToZero(position)
}
print("원점 도착!")
// -4... -3... -2... -1... 원점 도착!
func crashAndBurn() -> Never {
fatalError("Something very, very bad happened")
}
crashAndBurn() // 프로세스 종료 후 오류 보고
func someFunction(isAllIsWell: Bool) {
guard isAllIsWell else {
print("마을에 도둑이 들었습니다!")
crashAndBurn()
}
print("All is well")
}
someFunction(isAllIsWell: true)
someFunction(isAllIsWell: false)
func say(_ something: String) -> String {
print(something)
return something
}
@discardableResult func discardableResultSay(_ something: String) -> String {
print(something)
return(something)
}
say("hello")
// 반환 값을 사용하지 않았으므로 컴파일러가 경고를 표시할 수 있으나
// @discardableResult 메서드를 사용해 경고 알림을 막음