모바일앱/Swift
함수 응용하기
GeekCode
2021. 10. 5. 07:16
반응형
:: 함수 응용해보기 ::
함수는 기본적으로 아래의 형태로 구성되어있다.
함수명(매개변수1: 데이터타입, 매개변수2: 데이터타입) -> 반환값의 데이터타입{
실행할 함수내용
ruturn 반환할 값
}
func totalPrice(price: Int, count:Int) -> Int{ //반환값의 데이터타입
let totalPrice = price * count
return totalPrice//건내줄때 사용
}
let calculatedPrice = totalPrice(price: 10000, count: 77)
calculatedPrice
import UIKit
//함수와 매서드의 차이
//함수는 독립적 print()
//매서드는 엮여서 사용, 오브젝트에 속해서 기능을 수행할 때 price.text
print("\n=====> param 1개\n")
// 숫자를 받아서 10을 곱해서 출력한다
func printMutipleOfTen(value: Int) {
print("\(value) * 10 = \(value * 10)")
}
printMutipleOfTen(value: 10)
printMutipleOfTen(value: 3)
print("\n=====> param 2개\n")
//물건값과 갯수를 받아서 전체 금액을 출력
func printTotalPrice(price: Int, count: Int) {
print("Total Price : \(price * count)")
}
printTotalPrice(price: 1500, count: 5)
print( "\n=====> param에 이름 없이 value만 가능\n")
//external name을 표현하는 방법
func printTotalPrice(_ price: Int, _ count: Int) {
print("Total Price : \(price * count)")
}
printTotalPrice(1500,5)
print("\n=====> param에 한글을 쓰고 value입력 가능\n")
// swift는 유니코드가 지원되기 때문에 한글도 가능
func printTotalPrice(가격 price: Int, 갯수 count: Int) {
print("Total Price : \(price * count)")
}
printTotalPrice(가격:1500, 갯수:5)
/*
=====> param 1개
10 * 10 = 100
3 * 10 = 30
=====> param 2개
Total Price : 7500
=====> param에 이름 없이 value만 가능
Total Price : 7500
=====> param에 한글을 쓰고 value입력 가능
Total Price : 7500
*/
//let 출력된가격 = 전체가격출력(가격: 1500, 갯수: 5)
//한글로도 코딩이 가능하다
func printTotalPrice(price: Int, count: Int){
print("Total Price: \(price * count)")
}
printTotalPrice(price: 1500, count: 5)
printTotalPrice(price: 1500, count: 10)
printTotalPrice(price: 1500, count: 7)
printTotalPrice(price: 1500, count: 1)
//함수안에 default를 설정 가능
func printTotalPriceWithDefaultValue(price: Int = 1500, count: Int){
print("Total Price: \(price * count)")
}
//똑같이 계산 -> 함수가 깔끔해 보인다
printTotalPriceWithDefaultValue(count: 5)
printTotalPriceWithDefaultValue(count: 10)
printTotalPriceWithDefaultValue(count: 7)
printTotalPriceWithDefaultValue(count: 5)
//default가 있더라도 부가적으로 지정할 수 있다.
printTotalPriceWithDefaultValue(price: 2000, count: 1)
func totalPrice(price: Int, count:Int) -> Int{ //반환값의 데이터타입
let totalPrice = price * count
return totalPrice//건내줄때 사용
}
let calculatedPrice = totalPrice(price: 10000, count: 77)
calculatedPrice
반응형