Swift - let, var, array, dictionary

2022. 6. 12. 15:34ใ†ios

Swift - let, var, array, dictionary

 

์Šค์œ„ํ”„ํŠธ์—์„œ ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ณ€์ˆ˜์ธ let, var์™€ ์ž๋ฃŒ๊ตฌ์กฐ์ธ array, dictionary์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

var vs let 

 

์Šค์œ„ํ”„ํŠธ์—์„œ var๋Š” "๋ณ€ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ’", let์€ "๋ณ€ํ•  ์ˆ˜ ์—†๋Š” ๊ฐ’"์œผ๋กœ ์“ฐ์ž…๋‹ˆ๋‹ค. 

 

var a = 2
a = 3

let b = 3
b = 4 //์˜ค๋ฅ˜

 b๋Š” ์ƒ์ˆ˜๊ธฐ ๋•Œ๋ฌธ์— ์ปดํŒŒ์ผ์—๋Ÿฌ๊ฐ€ ๋‚˜์˜ค๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

 

let label = "The worth is"
let worth = 100
let worthLabel = label + worth // ๋ฌธ์ž์—ด๊ณผ ์ˆซ์ž๊ฐ€ ๊ฒน์ณ ๋‚˜ํƒ€๋‚˜๋Š” ์—๋Ÿฌ.

 

๋ฌธ์ž์—ด๊ณผ ์ˆซ์ž๊ฐ€ ํ•ฉ์ณ์ ธ์„œ ๋‚˜์˜ค๊ธฐ ์œ„ํ•ด์„œ๋Š” ์œ„์™€๊ฐ™์€ ๋ฐฉ๋ฒ•์„ ์•„๋ž˜์™€ ๊ฐ™์ด ๊ณ ์ณ์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

let label = "The worth is"
let worth = 100
let worthLabel = label + String(worth)

 

์œ„์™€ ๊ฐ™์ด ๋ฌธ์ž์—ด์€ ๋ฌธ์ž์—ด๋กœ๋งŒ ์กฐํ•ฉํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ˆซ์ž๋ฅผ ๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•ด์ค˜์•ผ ์˜๋„ํ•˜๋Š” ๊ฐ’์ด ํ™”๋ฉด์— ๋…ธ์ถœ์ด ๋ฉ๋‹ˆ๋‹ค.

์ด ์ด์œ ๋Š” ์Šค์œ„ํ”„ํŠธ๋Š” ์ •์ ํƒ€์ดํ•‘ ์–ธ์–ด์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์ด๋Š” ๋™์ ํƒ€์ดํ•‘ ์–ธ์–ด์— ๋น„ํ•ด ํƒ€์ž…์— ๋Œ€ํ•ด ์—„๊ฒฉํ•œ ํŠน์ง•์„ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋งค๋ฒˆ String์„ ์จ์„œ ๋ณ€ํ™˜์‹œํ‚ค๋Š” ๊ฒƒ์€ ๋ฒˆ๊ฑฐ๋กœ์šด ์ผ์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ฐ„๋‹จํ•œ ๋ฌธ๋ฒ•์œผ๋กœ ๊ณ ์ณ๋ด…์‹œ๋‹ค.

 

let apple = 3
let appleSummary = "I have \(apple) apples."

 

์šฐ๋ฆฌ๋Š” \(๋ณ€์ˆ˜)๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ์ข€ ๋” ์œ ์—ฐํ•œ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

 

์—ฌ๋Ÿฌ ์ค„์˜ ๊ฒฝ์šฐ๋Š” ๋งจ ์•ž๋‹จ๊ณผ  ๋งจ ๋’ท๋‹จ์— """๋ฅผ ๋ถ™์—ฌ์คŒ์œผ๋กœ์จ ํ‘œ์‹œํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

let quotations = """
This test is
just test
"""

print(quotations) 

//output
This test is
just test

 

๋‹ค์Œ์€ Array์™€ Dictionary์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ด…๋‹ˆ๋‹ค.

 

Array vs Dictionary

 

Array๋Š” ๋™์ผํ•œ ํƒ€์ž…์˜ ๋ณ€์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์žˆ์„ ๋•Œ ์‚ฌ์šฉ๋˜๋Š”  ์ž๋ฃŒ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.

์šฐ๋ฆฌ๋Š” ์ด ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ†ตํ•ด์„œ ๊ฐ’์„ ์ถ”๊ฐ€, ์‚ญ์ œ, ์ˆ˜์ •, ์กฐํšŒ ๊ธฐ๋Šฅ์„ ์œ ์—ฐํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋Œ€ํ‘œ์ ์ธ ๊ธฐ๋Šฅ์œผ๋กœ๋Š” ์ถ”๊ฐ€์˜ ์—ญํ• ์ธ append๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

 

var fruitList = ["apple", "banana", "melon"]
print(fruitList) // [apple, banana, melon]

fruitList.append("watermelon")
print(fruitList) // [apple, banana, melon, watermelon)

 

Dictionary๋Š” key์™€ value๋กœ ๋˜์–ด์žˆ๋Š” ํ˜•ํƒœ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ๊ฐ€ ์žˆ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค. 

var occupations = [
    "seungJin": "supervisor",
    "jisu": "salesman"
]

๋น„์–ด์žˆ๋Š” array๋‚˜ Dictionary๋ฅผ ์ •์˜ํ•  ๋•Œ๋Š” ํƒ€์ž…์„ ๋ช…์‹œํ•ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

let emptyArray = [String] = []
let emptyDictionary = [String: Float] = [:]

'ios' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

swift - ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด  (0) 2022.07.05
Swift - ์—ด๊ฑฐํ˜•(enum), ์›์‹œ๊ฐ’, ์—ฐ๊ด€๊ฐ’  (0) 2022.06.30
Swift- inout  (0) 2022.06.28
Swift - ํ•จ์ˆ˜  (0) 2022.06.27
Swift - if let (Optional)  (0) 2022.06.12