iOS/Swift이론

Swift) iOS 프로그래밍 함수, 1급객체, 클로저, 클래스

Sweetft 2021. 10. 5. 15:00

함수

함수의 타입

(자료형, 자료형, ...) -> 리턴형(Int, Int, ...) -> Int       => 리턴형이 Void형이면 ()

함수의 자료형 출력 print(type(of:함수몀))

 

func sum(num1 x: Int, sum2 y: Int) -> Int {
  return(x+y) //함수 정의
}
sum(num1:1, num2:2) //함수 호출

num1과 num2는 argument label이라 불리며 외부 매개변수라고도 한다.

x와 y는 parameter name 혹은 내부 매개변수라 한다.

함수를 정의할 때는 parameter name을, 함수를 호출할 때는 argument label을 사용한다.

argument name(외부 매개변수명)이 따로 없다면, parameter name(내부 매개변수명)이 이를 대체한다.

 

※참고로, 이 함수의 type은 (Int, Int) -> Int, 함수명은 sum(num1:num2:)

    => Swift의 함수명은 함수명(외부매개변수명:외부매개변수명:.....), print(#function)

 

import Foundation
func calcBMI(weight : Double, height : Double) -> String{
 let bmi = weight / (height*height*0.0001)
 let printBmi = String(format: "%.1f", bmi)
 var body = ""
 if bmi >= 40 {
    body = "DANGER"
 }else if bmi >= 30 && bmi < 40 {
    body = "WARNING"
 }else if bmi >= 25 && bmi < 30 {
    body = "CAUTION"
 }else if bmi >= 18.5 && bmi < 25 {
    body = "NORMAL"
 }else {
    body = "LOW"
 }
 return "BMI:\(printBmi), 결과:\(body)"
 }
print(calcBMI(weight:65.0, height:170.0)) //BMI:22, 결과:NORMAL
import Foundation
func calcBMI (weight : Double, height : Double) { //Void형
    let bmi = weight / (height*height*0.0001)
    let printBmi = String(format: "%.1f", bmi)
    switch bmi {
    case 0.0..<18.5:
        print("BMI:\(printBmi),결과:LOW")
    case 18.5..<25.0 :
        print("BMI:\(printBmi),결과:NORMAL")
    case 25.0..<30.0 :
        print("BMI:\(printBmi),결과:CAUTION")
    case 30.0..<40.0 :
        print("BMI:\(printBmi),결과:WARNING")
    default :
        print("BMI:\(printBmi),결과:DANGER")
        }
}
calcBMI(weight:72.3, height: 170.0) // BMI:25.0,결과:CAUTION
import Foundation
func calcBMI(weight : Double, height : Double) -> String {
    let bmi = weight / (height*height*0.0001) // kg/m*m
    let printBmi = String(format: "%.1f", bmi)
    var result = ""
    switch bmi {
    case 0.0..<18.5:
        result=("결과:LOW")
    case 18.5..<25.0 :
        result=("결과:NORMAL")
    case 25.0..<30.0 :
        result=("결과:CAUTION")
    case 30.0..<40.0 :
        result=("결과:WARNING")
    default :
        result=("결과:DANGER")
    }
    return "BMI:\(printBmi), \(result)"
}
print(calcBMI(weight:60.0, height:160.0)) //BMI:23.4, 결과:NORMAL

 

 

first class object(1급 객체) & first class citizen(1급 시민)

 

함수가 1급 객체다(or 1급 시민이다)라는 말의 의미는 무엇일까?

함수가 다음 3가지 조건을 만족하는 경우이다.

1. 변수에 저장할 수 있다.

2. 매개변수로 전달할 수 있다.

3. 리턴값으로 사용할 수 있다.

 

함수를 변수에 저장할 수 있다.

func inchesToCentimeter (inches: Float) -> Float {
   return inches * 2.54
}
let toCentimeter = inchesToCentimeter //함수를 자료형(데이터타입) 처럼 사용하여 변수에 저장한다.
print(toCentimeter(5))  //12.7

 

함수를 매개변수로 사용할 수 있다.

func outputConversion (converterFunc: (Float) -> Float, value: Float) { 
   //(Float)->Float = 매개변수가 Float형이고 return 값도 Float형인 함수를 넣어주겠다.
   let result = converterFunc(value)
   print("Result = \(result)")
}
outputConversion(converterFunc:toCentimeter, value: 5) //12.7

 

함수를 리턴값으로 사용할 수 있다.

func inchesToCentimeter (inches: Float) -> Float {
   return inches * 2.54
}
func inchesToMeter (inches: Float) -> Float {
   return inches * 0.0254
}
let toCentimeter = inchesToCentimeter //함수를 자료형(데이터타입) 처럼 사용하여 변수에 저장한다.
let toMeter = inchesToMeter


func outputConversion (converterFunc: (Float) -> Float, value: Float) { 
   //(Float)->Float = 매개변수가 Float형이고 return 값도 Float형인 함수를 넣어주겠다.
   let result = converterFunc(value)
   print("Result = \(result)")
}

outputConversion(converterFunc:toCentimeter, value: 10) //25.4
outputConversion(converterFunc:toMeter, value: 10) //0.254


func decideFunction (centimeter: Bool) -> (Float) -> Float
{ //매개변수형 리턴형이 함수형
if centimeter {
return toCentimeter //함수를 리턴
} else {
return toMeter //함수를 리턴
}
}

let a = decideFunction(centimeter:true)
print(type(of:a)) //(Float) -> Float
print(a(10)) //25.4
let b = decideFunction(centimeter:false)
print(b(10)) //0.254

 

 

클로저(closure)

 

익명 함수(이름이 없는 함수), 독립적인 코드 블록

왜 사용? 한 번만 호출한다거나, 굳이 함수 이름 넣어가며 만들 지 않아도 될 것 같을 때.

let toCm = {(inches: Float) -> Float in
   return inches * 2.54
}
print(toCm(5))  //12.7

=> 위 inchesToCentimeter 함수를 클로저 함수로 변환

 

 

 

클래스를 통해 객체를 만들고 이렇게 만들어진 것을 인스턴스라고 한다.

Property (member variable - 멤버변수)

Method (member function - 멤버함수)

 

클래스의 기본 구조

class 새로운 클래스 이름 : 부모 클래스 이름 {

     // 프로퍼티(변수(var)와 상수(let))

     // 인스턴스 메서드(객체가 호출하는 메서드)

     // 타입 메서드(클래스가 호출하는 메서드)

}

class Dog{
    var age : Int = 5
    var weight : Double  = 3.5
    func display(){
        print("나이=\(age), 몸무게=\(weight)")
    }
} 
var nala = Dog() // var nala : Dog = Dog()에서 : Dog 생략
nala.display()
print(nala.weight)

 

참고 : iOS프로그래밍기초(21년-2학기) 한성현 교수님 강의 및 강의 자료 변형, 요약