[인프런 강의] Swift 문법 - 1

2019. 7. 16. 20:49

Constanst and Variables

- Constanst 처음에 값을 설정하고 바꿀 수 없다

- Variable 처음에 값을 설정하고도 변경이 가능하다

 

이것들이 사용되기 전에는 반드시 선언을 해야한다.

상수를 선언하기 위해 let을 사용, 변수를 선언하기 위해서는 var를 사용한다.

 

let max = 10 //변경 불가

var min = 1  //변경 가능

 

모든 변수와 상수에는 데이터 타입을 정해주어야 한다.

타입: Int, double, string...

타입 선언시: var welcome : String

만약 설정을 안하게 되면 타입을 추정을 하게 된다.(자동으로 타입 추정 기능이 있다)

영어 이외에 언어로 변수를 설정은 가능하지만 영어 권장.

 

출력을 할 경우: print(변수명, 혹은 "문자열")

주석은 /*~*/

 

String 

 

문자열을 초기화 할 떄 : let some = "i am gruit"

문자열을 여러줄로 표시할 때(개행할 때): 쌍따옴표 세 개를 쓰면된다

ex) let question = """ 

this is one of the most example ...

this is test code!

"""

 

Speical Characters

\0 \n \\(백슬레쉬 표시하기 위해서) .. 등 그 외 표기법은 다른 언어와 비슷함

 

문자열 사용시 empty String을 초기화 할 때: 초기화 문법으로 초기화하는 방식, 리터럴 변수로 초기화 하는 방식

ex) var empty = ""

     var emtpy2 = String()

 

Concatenating String(문자 잇기)

1. var welcom = string1 + string2

2. var inst += string2

 

Counting char

let unsual = "a, b, c, d"

print(unsual.count) -> count는 문자의 개수를 세어주는 역할

 

isEmpty함수 사용시: if emptyString.isEmpty{ ...

 

Collection

배열, 집합, 사전(dictionery)를 기본으로 제공, 값들의 집합을 선언할 수 있음

- Array: 순서 있음

- Set: 중복 불가

- Dictionery

 

컬렉션 타입들의 가변성

값을 추가하거나 지우거나 바꿀 수 있는 특성

immutable 컬렉션을 만들수도 있다. 가변성을 지니지 않은 고정된 크기의 컬렉션을 선언할 수 있다는 뜻.(ver과 let의 차이 정도로 볼 수 있다)

 

Array>

같은 타입의 순서가 있는 리스트를 저장하는 것

몇 번째 자리에 들어가는 것인지간데 중복이 가능하다(같은 값을 배열 안 어디던지 인덱스 중복만 아니면 넣을 수 있다)

 

배열 선언 방식: Array<Element> OR [element]

ex) var someInts = [Int]()

     var shopping: [String] = ["e", "M"]

//배열이 만들어지고, 초기화하는 과정 (타입을 안붙여도 자동으로 배열이 만들어지기는 한다)

shopping.count -> 배열 크기를 카운팅할 때 쓰는 것(많이 쓰임)

shopping.append("A") //배열에 요소 추가

shopping += ["B"]  //배열에 요소 추가

shopping [4..6] = ["C", "D"] //정해진 배열 인덱스에 요소 추가

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//: Playground - noun: a place where people can play
 
import UIKit
 
var emptyArray = Array<String>()
var emptyArray2 = [String]() //empty array
 
print("1")
 
 
print(emptyArray2)
 
var emptyArray3: [String= ["A""B""C""D"]
 
emptyArray3 += ["Check"]
emptyArray3 += ["OK!"]
 
print(emptyArray3)
print(emptyArray3[3])
 
 

 

Collection - Dictionary

같은 타입의 키와 같은 타입의 value를 통해 연관된 정보를 저장하는 것

Dictionary<key, value> OR [key: value] 로 사용

ex) var name = [Int: String]() //empty로 초기화

     name =  [ : ] //empty 초기화의 다른 방법

 

레코드 삽입하는 방법: var airports: [String: String] = ["YYZ": "Toronto", "DUB": "Dublin"]

키 값으로 본래 값에 접근: let airport = airports["DUB"] //airport에서 DUB의 키값을 가지고 있는 value를 airport에 저장

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//: Playground - noun: a place where people can play
 
import UIKit
 
var emptyDic = Dictionary<String,Int>()
var emptyDic2 = [String:Int]() //create dictionary
 
if emptyDic2.isEmpty {
    print("noting in dic2")
}
 
print(emptyDic2.count) //non, empty
 
emptyDic2["ant"= 6 //insert
emptyDic2["snake"= 0
 
print(emptyDic2)
 
var emptyDic3 = ["ant":6"snake":0"cheetah":4]
 
emptyDic3["human"= 2
emptyDic3["snake"= 1 //change snake's value
print(emptyDic3)
 
print(emptyDic3["cheetah"]!//optional func -> ! reutrun 4
 
//if you use let --- this can't change
 
 
 

BELATED ARTICLES

more