함수는 어떤 기능을 수행하는 코드 블럭
func functionName(exteranlName param: ParamType) -> ReturnType {
//....
return returnValue
}
func printName() {
print("My name is Jon")
}
printName() // My name is Jon
func printMultipleOfTen(value: Int) {
print("\(value) * 10 = \(value * 10)")
}
printMultipleOfTen(value: 3)
func printTotalPrice(price: Int, count: Int) {
print("Total Price: \(price * count)")
}
printTotalPrice(price: 3500, count: 3)
func printTotalPrice(가격 price: Int, 갯수 count: Int) {
print("Total Price: \(price * count)")
}
printTotalPrice(가격: 3500, 갯수: 3)
func printTotalPriceWuthDefaultValue(price: Int = 1500, count: Int) {
print("Total Price: \(price * count)")
}
printTotalPriceWuthDefaultValue(count: 3)
printTotalPriceWuthDefaultValue(count: 10)
printTotalPriceWuthDefaultValue(count: 32)
printTotalPriceWuthDefaultValue(price: 3500, count: 1)
func totalPrice(price: Int, count: Int) -> Int {
let totalPrice = price * count
return totalPrice
}
let calculatedPrice = totalPrice(price: 10000, count: 7)
calculatedPrice
도전과제
1. 성, 이름을 받아서 fullname을 출력하는 함수 만들기
2. 1번에서 만든 함수를 파라미터 이름을 제거하고 fullname을 출력하는 함수 만들기
3. 성, 이름을 받아서 fullname return 하는 함수 만들기
func printFullName (fristName: String, lastName: String) {
print("제 이름은 \(fristName)\(lastName)입니다")
}
printFullName(fristName: "park", lastName: "tae")
func printFullName (_ fristName: String, _ lastName: String) {
print("제 이름은 \(fristName)\(lastName)입니다")
}
printFullName("park", "tae")
func fullName (fristName: String, lastName: String) -> String {
return "\(fristName) \(lastName)"
}
let name = fullName(fristName: "park", lastName: "tae")
name
overloading
func printTotalPrice(price: Int, count: Int) {
print("Total Price: \(price * count)")
}
func printTotalPrice(price: Double, count: Double) {
print("Total Price: \(price * count)")
}
func printTotalPrice(가격: Int, 개수: Int) {
print("Total Price: \(가격 * 개수)")
}
In-out parameter
Swift에서 함수의 파라미터는 상수(Constant)이므로 함수 내부에서 파라미터의 값을 변경할 수 없다 만약 함수의 파라미터 값을 변경하고, 변경된 값이 함수 호출이 종료된 후에도 지속되길 원하ㄷ면 inout
파라미터를 사용하면 된다.
var value = 3
func incrementAndPrint(_ value: inout Int) {
value += 1
print(value)
}
incrementAndPrint(&value)
function as a parameter
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
function(4, 2)
func printResult(_ function:(Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b)
print(result)
}
printResult(add, 10, 5)
printResult(subtract, 10, 5)
변수에 값이 들어갈 수도 있고, 아닐 수도 있다 (nil)
var carName: String?
var bikeName: String!
var favoriteMovieStar: String?
favoriteMovieStar = "송강호"
Optional 고급 기능 4가지
var carName: String? = "아우디"
print(carName!)
carName = nil
if let unwrappedCarName = carName {
print(unwrappedCarName)
} else {
print("Car Name이 없다")
}
func printParsedInt(from: String) {
if let parsedInt = Int(from) {
print(parsedInt)
} else {
print("Int로 컨버팅 안됩니다")
}
}
printParsedInt(from: "100") // 100
printParsedInt(from: "Hello") // Int로 컨버팅 안됩니다
func printParsedInt(from: String) {
guard let parsedInt = Int(from) else {
print("Int로 컨버팅 안됩니다 ")
return
}
print(parsedInt)
}
//printParsedInt(from: "100")
printParsedInt(from: "Hello")
carName = "모델 3"
let myCarName: String = carName ?? "모델 S"
도전과제
1. 최애 음식이름을 담는 변수를 작성하시고 (String?)
2. 옵셔널 바인딩을 이용해서 값을 확인해보기
3. 닉네임을 받아서 출력하는 함수 만들기, 조건 입력 파라미터는 String?
let favoriteFood: String? = "소고기"
if let foodName = favoriteFood {
print(foodName)
} else {
print("좋아하는 음식 없음")
}
func printNickNmae(name: String?) {
guard let printNickNmae = name else {
print("닉네임을 만들어보자")
return
}
print(printNickNmae)
}
printNickNmae(name: "Dino")
참고 : FastCampus iOS 앱 개발 올인원 패키지