keyword : func
func printName() {
print("My name is Meredith")
}
printName()
func numgob(i: Int) {
print(i*10)
}
numgob(i: 7)
func totalPrice(price: Int, count: Int) {
print("Total Price : $\(price*count)")
}
totalPrice(price: 3, count: 15)
func printTotalPrice(_ price: Int, _ count: Int) {
print("Total Price : $\(price*count)")
}
printTotalPrice(price: Int, count: Int) // price:Int 자리에 3, count:Int 자리에 15 입력
printTotalPrice(3, 15)
func printTotalPriceKorean(ㄱㅏㄱㅕㄱ price: Int, ㄱㅐㅅ수 count: Int) {
print("Total Price : $\(price*count)")
}
printTotalPriceKorean(ㄱㅏㄱㅕㄱ: Int, ㄱㅐㅅ수: Int)
printTotalPriceKorean(ㄱㅏㄱㅕㄱ: 3, ㄱㅐㅅ수: 15)
//내가 설정한 한글로도 입력 전에 보이게 할 수 있다.
keyword : -> dataType
func totalPrice(price: Int, count:Int) -> Int {
let total = price * count
return total
}
print(totalPrice(price: 3, count: 15))
function 이름은 같지만 parameters가 서로 type이 다른 것
// overroad
func printTotalPrice(price: Double, count: Double) {
print(" Total price : \(price * count)")
}
func printTotalPrice(price: Int, count: Int) {
print(" Total price : \(price * count)")
}
parameter는 기본적으로 상수(constant)가 전달된다.
상수이기에 값을 수정할 수 없다.
따라서 함수 내에서 수정이 필요할 때 inout parameter를 사용한다
1. 함수가 호출되면, 매개변수로 넘겨진 변수가 복사됩니다.
2. 함수 몸체에서, 복사했던 값을 변화시킵니다.
3. 함수가 반환될 때, 이 변화된 값을 원본 변수에 재할당합니다.
var value = 3
func incrementAndPrint(_ num: inout Int) {
num += 1
print(num)
}
incrementAndPrint(&value)
즉, inout은 값을 변화시키겠다는 선언과도 같은 표현이다.
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func subtract(_ a: Int, _ b: Int) -> Int {
return a - b
}
var function = add
function(4, 2)
function = subtract
print(function(4, 2))
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print(function(a, b))
}
printResult(add, 33, 33)