BMI를 판정하는 calcBMI()함수 정의
func CheckBMI(weight : Double, height : Double) ->String
{
let bmi = weight / (height*height*0.0001)
let shortendBMI =String(format : "%.5f", bmi)
if bmi >=40
{
print("과체중")
}
else if bmi >=30 && bmi <40
{
print("2단계 비만")
}
else if bmi >=25, bmi <30
{
print("1단계 비만")
}
else if bmi >=18.5, bmi <26
{
print("정상")
}
else { print("저체중") }
return "BMI : \(shortendBMI)"
}
print(CheckBMI(weight : 100.1, height : 178.1))
결과 : 2단계 비만
BMI : 31.55777
2. Switch case 함수 BMI 계산
case print에서 값을 출력 했기 때문에 Return형 X
func CheckBMI(weight : Double, height : Double)
{
let bmi = weight / (height*height*0.0001)
let formatBMI =String(format: "%.4f", bmi)
switch bmi
{
case 0.0..<18.5:
print("BMI 수치는 \(formatBMI)이며 판정 : 저체중")
case 18.5..<25.0 :
print("BMI 수치는 \(formatBMI)이며 판정 : 정상")
case 25.0..<30.0 :
print("BMI 수치는 \(formatBMI)이며 판정 : 1단계 비만")
case 30.0..<40.0 :
print("BMI 수치는 \(formatBMI)이며 )판정 : 2단계 비만")
default :
print("BMI 수치는 \(formatBMI)이며 판정 : 3단계 비만")
}
}
//BMI 수치는 24.9465이며 판정 : 정상
3. Switch case 함수, return BMI 계산
Switch case 후 Reuturn을 해야하니 String형이 필요
func CheckBMI(weight : Double, height : Double) ->String
{
let bmi = weight / (height*height*0.0001)
let formatBMI =String(format: "%.4f", bmi)
var im =""
switch bmi
{
case 0.0..<18.5:
im ="저체중“
case 18.5..<25.0 :
im ="정상“
case 25.0..<30.0 :
im ="1단계 비만“
case 30.0..<40.0 :
im ="2단계 비만“
default :
im ="3단계 비만"
}
return "BMI :\(formatBMI), 판정은 \(im)입니다."
}
print(CheckBMI(weight : 89.3, height : 189.2))
//BMI :24.9465, 판정은 정상입니다.
4. 함수를 변수에 저장하기
func kgtolb (kg : Float) -> Float
{
return kg /2.2
}
let tolb = kgtolb
//함수 kgtolb를 상수 tolb에 값을 넣으면 매개변수명을 넣지 않아도 된다.
//함수 자료형은 Float
print(type(of:tolb)) //(Float) -> Float
print(tolb(10)) //4.5454545
print(kgtolb(kg:10)) //4.5454545
5.함수를 매개변수로 사용
func Change(tolb2 : (Float) -> Float, value : Float)
//함수를 매개변수로 사용
{
let c = tolb2(value) //tolb(10)
print("Change = \(c)") //Change =9.090909
}
//kg을 lb로 변환하는 함수 호출
Change(tolb2 : tolb, value : 20)
6. 리턴값으로 사용
func Function1 (Meter : Bool) -> (Float) -> Float
{ //매개변수형 리턴형이 함수형
if Meter
{
return toMeter //함수를 리턴
}
else
{
return centimeter
}
}
Bool은 참, 거짓을 나뉨으로
Meter가 toMeter, centimeter로 나뉜다.
7. 함수 정리
func MetertoCm (Meter : Int) ->Int
{
return Meter /100
}
let toCm = MetertoCm
print(toCm(100)) //3
//함수 kgtolb를 상수 tolb에 값을 넣으면 매개변수명을 넣지 않아도 된다.
//함수 자료형은 Float
func CmtoMeter (Cm : Int) ->Int
{
return Cm *100
}
let toMeter = CmtoMeter
print(toMeter(3)) //300
//함수 kgtolb를 상수 tolb에 값을 넣으면 매개변수명을 넣지 않아도 된다.
//함수 자료형은 Float
func MeterCm(MeCm: (Int) ->Int, value: Int)
{ //함수를 매개변수로 사용
let result = MeCm(value)
print("결과 = \(result)")
}
MeterCm(MeCm:toCm, value: 1000) //toCm(1000) //결과 = 10
MeterCm(MeCm:toMeter, value: 10) //toMeter(10) //결과 = 1000
func ItsDone(o: Bool) -> (Int) ->Int
{
//매개변수형 리턴형이 함수형
if o
{
return toCm //toCm함수를 리턴
}
else
{
return toMeter ////toMeter함수를 리턴
}
}
let r = ItsDone(o:true) // let r = toUp
print(type(of:r)) //(Int) -> Int
print(r(1000))
//If o일시 10
//else 100000
8. Closure
[변수 or 상수] [함수명] = { (매개변수 : Type) -> 리턴 타잎 in return( )}
함수처럼 여러번 사용하지 않고 적은 횟수로 쓸 시 사용한다
let subtraction = { (a: Int, b: Int) ->Int in return(a-b) }
print(subtraction(19,20))
print(type(of:subtraction))
//1
//(Int, Int) -> Int
let mul = { (value : Int, other : Int) ->Int in return value * other}
let answer = mul(30,20)
print(answer)
//600
l
9. 후행 클로저(trailing closure)
인자로 클로저를 넣기가 길다면 후행 클로저를 사용하여 함수의 뒤에 표현할 수 있다.
let reversedNames = names.sorted() { $0 > $1 }
마지막 인자가 클로저이고, 후행 클로저를 사용하면 괄호“( )”를 생략할 수 있다.
let reversedNames = names.sorted { $0 > $1 }
let reversedNames = names.sorted { (s1: String, s2: String) ->Bool in return s1 > s2 }
10. 클로저, 후행 클로저
let division = { (x : Float, y : Float) -> Float in return x - y }
var answer = division(8.3, 50.2)
print(answer)
let calculate = { (x : Float, y : Float) -> Float in return x / y }
answer = calculate(15.1, 95.4)
print(answer)
func math(a : Float, b : Float, A : (Float, Float) -> Float) -> Float { return A(a, b) }
answer = math(a : 10.9, b : 12.01, A: division)
print(answer)
answer = math(a : 18.1, b : 11.53, A: calculate)
print(answer)
answer = math(a : 12.2, b : 20.1, A : {(x : Float, y : Float) -> Float in return x * y }) //클로저 소스를 매개변수에 직접 작성
print(answer)
answer = math(a : 10.5, b : 20.5) {(x: Float, y: Float) -> Float in return x + y } //trailing closure
print(answer)
11. Class
연관된 것들을 묶어 가독성이 좋다
상속을 하여 코드의 낭비를 줄이고 특정 기능을 추가할 수 있다
새로운 자료형(Class)으로 변수(Object)를 처리할 수 있다
클래스(교실)
객체(인스턴스) – 철수(남자, 떠든다)
(교실 안) - 영희(여자, 공부한다)
클래스 (사람) - 설계도, 청사진
특성 멤버변수 (Member Varialbe, Data) Property
입 손 다리
행위 멤버함수 (Member Function, Operation) Method
먹는다, 잡는다, 걷는다
인스턴스, 객체
실제로 메모리에 할당된 객체
객체의 구성
변수 or 속성(Property)
함수 or 메서드(Method)
12.클래스 생성
클래스명은 자식 클래스이며 부모 클래스는 생략이 가능함
class [클래스명] : 부모 클래스
{
//Property (클래스 내 포함되는 val, let 정의)
//Instance Method (객체가 호출하는 메서드 정의)
//Type, Method (클래스가 호출하는 메서드 정의)
}
Property
클래스, 구조체, 열거형등에 관련된 값을 뜻
저장 프로퍼티(Stored Properties)
지연 저장 프로퍼티(Lazy Stroed Properties)
연산 프로퍼티(Computed Properties)
프로퍼티 감시자(Property Observers)
타입 프로퍼티(Type Properties)
초기 값이 있거나 || init 초기화 || 상수로 선언 or nil
Class Human
{
//Stored Properties
var age : Int //error Why? 초기 값 X, init 초기화 X
var age : Int? //Yes
var age : Int! //Yes
var age : Int = 22 //Yes
}
13. Method
class Human
{
//Stored Properties
var age : Int = 22 //Yes
//Method (인스턴스에서 동작)
func display()
{
print("나이 : \(age)") //나이 : 22
}
}
var Ju : Human = Human() //Ju라는 인스턴스를 만든다
Ju.display() //Method 즉 display 호출, 나이 : 22
print(Ju.age) //22