어흥
[Swift] 기초 문법/ 지식 본문
1. let(constant) v.s var
- 가장 큰 차이점: var은 변수값이 바뀔 수 있으나, let은 바뀔 수 없다
- var을 남발하면 서비스에서 버그가 발생할 수 있으니 let을 권장!
2. Local 변수 v.s. Instance 변수
- Local: 특정 Method 내에서만 사용되는 변수
- Instance: Object안에서 전반적으로 사용되는 변수
3. 사진 업로드
1) 작업하는 폴더에 있는 Assets.xcassets 폴더를 더블클릭 한 이후, 이미지를 드래그해서 넣는다
2) Code View Controller쪽에 ImageView를 하나 만든 후, Attributes inspector>Image에 업로드한 파일을 더블클릭
3) ImageView에 가득 차길 원한다면 Attributes inspector>View>Content Mode의 값을 Aspect Fill로 설정한다
4. Tuple
1) 목적: 한번에 2개 혹은 3개의 값을 저장하거나 넘기고 싶을 때 사용
2) 사용법
//1. default일 때
let coordinates = (6,8)
let x = coordinates.0
let y = coordinates.1
//2. 특정 변수에 값을 저장할 때
let coordinatesNamed = (x:2, y:3)
let x2 = coordinatesNamed.x
let y2 = coordinatesNamed.y
//3. 2번보다 더 효율적인 방법
let (x3,y3) = coordinatesNamed
5. 함수
- Swift의 경우 한글도 지원한다
//1
func printTotalPrice(_ price: Int,_ count: Int){
print("Total Price: \(price*count)")
}
printTotalPrice(1500,5)
//2
func printTotalPrice(가격 price: Int,개수 count: Int){
print("Total Price: \(price*count)")
}
printTotalPrice(가격: 1500,개수: 5)
//1과 2 둘다 가능
//3
func totalPrice(price: Int, count: Int) -> Int{
let totalPrice = price * count
return totalPrice
}
//4
//In-Out parameter
var value=3
func incrementAndPrint(_ value: inout Int){
value+=1
print(value)
}
incrementAndPrint(&value)
- 3번의 경우, Return 타입이 Int
- 4번의 경우, 함수에서 적힌 매개변수는 Constant(상수) 형태로, 변경이 불가능해서 바꾸고 싶다면 inout을 사용하고 넘길때 &를 붙여서 넘긴다
[참조]
- https://medium.com/@jgj455/%EC%98%A4%EB%8A%98%EC%9D%98-swift-%EC%83%81%EC%8B%9D-closure-aa401f76b7ce
'iOS' 카테고리의 다른 글
[Swift] Flow Control (0) | 2020.08.23 |
---|---|
[Swift] 레이아웃 + 기본설정 (2) | 2020.08.21 |
[Swift] String + Variable(변수) (0) | 2020.08.20 |
[Swift] 팝업 (2) | 2020.08.12 |
[Swift] View Controller (0) | 2020.08.11 |