금주 강의는 클래스, 클로저와 같은 좀 더 복잡한 swift 문법에 대해 알아보았다.
강의는 실습코드들을 중간중간 실습해보며, 설명위주의 강의로 배웠다.
다음은 금주 실습한 교수님의 코드들을 조금의 변형과 함께 실행해본 결과이다.
Swift 문자열 서식 (swift string format 자리수)
import Foundation
let weight =60.0
let height =170.0
let bmi = weight / (height *height *0.0001) // kg/m*m
let shortenedBmi =String(format: "%07.3f", bmi) //7범위를 표시한다는 뜻
var body =""
if bmi >=40 {
body ="3단계 비만"
} else if bmi >=30 && bmi <40 {
body ="2단계 비만"
} else if bmi >=25 && bmi <30 {
body ="1단계 비만"
} else if bmi >=18.5 && bmi <25 {
body ="정상"
} else {
body ="저체중"
}
print("BMI:\(shortenedBmi), 판정:\(body)")
//BMI:020.761, 판정:정상
BMI를 판정하는 calcBMI() 함수 정의 & switch~case 판정 결과 리턴하는 함수
import Foundation
func calcBMI(weight : Double, height : Double) -> (){
let bmi = weight / (height *height *0.0001) // kg/m*m
let shortenedBmi =String(format: "%.1f", bmi)
var body =""
switch bmi {
case 0.0..<18.5:
body ="저체중"
case 18.5..<25.0:
body ="정상"
case 25.0..<30.0:
body ="1단계 비만"
case 30.0..<40.0 :
body ="2단계 비만"
default :
body ="3단계 비만"
}
print( "BMI:\(shortenedBmi), 판정:\(body)" )
}
calcBMI(weight:80, height: 168.8)
//BMI:28.1, 판정:1단계 비만
함수 : 일급 객체 실습
func up(num: Int) ->Int {
return num +1
}
func down(num: Int) ->Int {
return num -1
}
let toUp = up
print(up(num:12)) //13
print(toUp(10)) //num : 제외해야함 //11, 10(num) + 1
let toDown = down
func upDown(Fun: (Int) ->Int, value: Int) { //(Int) -> Int, 함수로 받는다.
let result = Fun(value)
print("결과 = \(result)")
}
upDown(Fun:toUp, value: 10) //toUp(10)
upDown(Fun:toDown, value: 10) //toDown(10)
print(type(of:upDown(Fun:value:))) //((Int) -> Int, Int) -> ()
func decideFun(x: Bool) -> (Int) ->Int {
//매개변수형 리턴형이 함수형
if x {
return toUp
}
else {
return toDown
}
}
let r = decideFun(x:true) // let r = toUp
print(type(of:r)) //(Int) -> Int
print(r(10)) // toUp(10)
클로저 표현식
func add(x: Int, y: Int) ->Int {
return(x +y)
}
print(add(x:10, y:20))
let add1 = { (x: Int, y: Int) ->Int in
return(x +y)
}
//print(add1(x:10, y:20)) //주의 error: extraneous(관련 없는) argument labels 'x:y:' in call
print(add1(10, 20)) //30
print(type(of:add1)) //(Int, Int) -> Int
후행 클로저 (trailing closure)
let onAction = UIAlertAction(title: "On", style: UIAlertAction.Style.default)
{
ACTION in self.lampImg.image =self.imgOn
self.isLampOn =true
} // trailing closure 사용
let removeAction = UIAlertAction(title: "제거", style: UIAlertAction.Style.destructive, handler:
{
ACTION in self.lampImg.image =self.imgRemove
self.isLampOn =false ////closure’s body
})
클로저의 축약 표현들 : 과제( 유사 예제 만들어 보기 )
let multiply = {(val1: Double, val2: Double) -> Double in
return val1 * val2
}
var result = multiply(10, 20)
print(result) //200.0
let add = {(val1: Double, val2: Double) -> Double in
return val1 + val2
}
result = add(10, 20)
print(result) //30.0
let division = {(val1: Double, val2: Double) -> Double in
return val1 / val2
}
result = division(10, 20)
print(result) //0.5
func math(x: Double, y: Double, cal: (Double, Double) -> Double) -> Double {
return cal(x, y)
}
result = math(x: 10, y: 20, cal: add)
print(result) //30.0
result = math(x: 10, y: 20, cal: multiply)
print(result) //200.0
result = math(x: 10, y: 20, cal: division)
print(result) //0.5
result = math(x: 10, y: 20, cal: {
$0 + $1 //return 생략
}) //리턴형 생략, 매개변수 생략하고 단축인자(shorthand argument name)사용
print(result) //30.0
result = math(x: 10, y: 20) {
$0 + $1 //return 생략
}//trailing closure, 매개변수 생략하고 단축인자(shorthand argument name)사용
print(result) //30.0
프로퍼티는 초기값이 있거나 옵셔널 변수(상수)로 선언
class Man1{
var age : Int =1 //stored property는 초기값이 있어야 함
var weight : Double =3.5
}
class Man2{
var age : Int? //stored property는 초기값이 있어야 함, nil
var weight : Double !
}
var Kim = Man1()
var Lee = Man2()
print(Kim.age) //1
//print(Lee.age) //nil //main.swift:14:7: warning: expression implicitly coerced from 'Int?' to 'Any'
print(type(of:Kim)) //Man1
print(type(of:Lee)) //Man2
인스턴스 만들고 메서드와 프로퍼티 접근
class Dog{
var age : Int =3
var weight : Double =10.5
func display(){
print("나이=\(age)살, 몸무게=\(weight)kg")
}
}
var DolDol : Dog = Dog()
DolDol.display() //나이=3살, 몸무게=10.5kg //인스턴스
DolDol.age =11 //프로퍼티
DolDol.display() //나이=11살, 몸무게=10.5kg
var Mung = Dog()
Mung.display() //나이=3살, 몸무게=10.5kg
'대학교 - 강의 > iOS프로그래밍기초' 카테고리의 다른 글
| iOS프로그래밍기초 7주차 레포트 (0) | 2021.10.16 |
|---|---|
| iOS프로그래밍기초 6주차 레포트 (0) | 2021.10.08 |
| iOS프로그래밍기초 4주차 레포트 (0) | 2021.09.26 |
| iOS프로그래밍기초 3주차 레포트 (0) | 2021.09.18 |
| iOS프로그래밍기초 2주차 레포트 (0) | 2021.09.10 |