๐Ÿ“ฑ App Development Study/iOS๐ŸŽ

[Udemy iOS & Swift Bootcamp] Section4: Swift Programming Basics

ibelieveinme 2023. 2. 26. 23:11
728x90

Section4: Swift Programming Basics - Collections, Constants & Variables

 

[Code ๊ทœ์น™]

WHO.WHAT = VALUE

CamelCase

 

[๋™์ž‘ ์›๋ฆฌ]

Outlet ์€ storyboard <- code // IBOutlet allows me to reference a UI element

Action์€ storyboard -> code

 

[String Interpolation]

print("Text \(2+3) Text")

 

[Swift Cheat Sheet] - ๋ฌธ์ œ์‹œ ์‚ญ์ œ

let: ์ƒ์ˆ˜

var: ๋ณ€์ˆ˜

ํ•จ์ˆ˜ ํ˜ธ์ถœ์€ aFunction(input: 1) ์ด๋ ‡๊ฒŒ ๋ถ€๋ฅด๋Š” ๊ฒƒ. input๊ฐ’์— 1๋„ฃ์–ด ~

 

* ๋žœ๋ค ์ˆ˜ ์ƒ์„ฑ ๋ฐฉ๋ฒ•

: Int.random(in: lower...upper) or array.randomElement() or array.shuffle()

 

Int ๋ง๊ณ  ๋‹ค๋ฅธ ํ˜•์˜ random ์ˆ˜๋ฅผ ์ƒ์„ฑํ•  ๋• ์•ž์— ํ˜•์„ ๋ฐ”๊ฟ”์ฃผ๋ฉด ๋œ๋‹ค.

Int.random(in: lower..<upper)
Float.random(in: lower...upper)
Bool.random()

 

* ์†Œ์ˆ˜์  n์ž๋ฆฌ์—์„œ ์ž๋ฅด๊ธฐ

1) ๋ฐ˜์˜ฌ๋ฆผ ํ•จ์ˆ˜: round()

    ex) round(12.123456) // 12.12347

                                          // ๋ฐ˜์˜ฌ๋ฆผํ•ด์„œ ์†Œ์ˆ˜์  5์ž๋ฆฌ๊นŒ์ง€ ๋ณด์—ฌ์คŒ.

2) String format ์ด์šฉ

     ex) String(format: "%.2f", 145.332) // 145.33

                                                                  // ์†Œ์ˆ˜์  2์ž๋ฆฌ๊นŒ์ง€ ๋ณด์—ฌ์คŒ.

3) Int ํ˜•์œผ๋กœ ๋ฐ”๊พธ๊ธฐ

    ex) Int(123.2122) // 123

 

* switch ๋ฌธ case ์•ˆ์— ์กฐ๊ฑด์„ ๋ฒ”์œ„๋กœ ์ค„ ์ˆ˜๋„ ์žˆ๋‹ค

a...b // closed range
a..<b // half open range
...b // one sided range

 

* Dictionary ๋Š” ์ˆœ์„œ๊ฐ€ ์—†๋‹ค. ๋”ฐ๋ผ์„œ [0].key, [0].value ์ด๋Ÿฐ์‹์œผ๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์—†๋‹ค.

 

* Optionals ! ? ์˜ ๋œป

?: null ๊ฐ’์„ ํ—ˆ์šฉํ•˜๋Š” ๋ณ€์ˆ˜๋ผ๋Š” ๋œป.

!: null ๊ฐ’์ด ์—†๋‹ค๊ณ  ํ™•์‹ ํ•œ๋‹ค๋Š” ๋œป.

nil: null์˜ swift ํ‘œํ˜„

//var playerU1Username: String = nil

var playerU1Username: String? = nil

player1Username = "jackbauerisawesome"

print(player1Username)

 

* Struct ์˜ˆ์‹œ ์ฝ”๋“œ

init ํ•จ์ˆ˜๊ฐ€ ์ดˆ๊ธฐํ™” ํ•จ์ˆ˜๋‹ค. ์ƒ์„ฑ์ž ๊ฐ™์€.

Struct ํ•จ์ˆ˜ ๋‚ด์˜ ์ธ์ž ์ด๋ฆ„์„ Struct ์†์„ฑ ์ด๋ฆ„๊ณผ ๊ฐ™๊ฒŒ ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด Struct ์†์„ฑ์— ์ ‘๊ทผํ•  ๋•Œ self ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์—ฌ์ฃผ๋ฉด ๋œ๋‹ค.

struct Town{
    let name: String
    var citizens: [String]
    var resources: [String: Int]
    
    init(name: String, citizens: [String], resources: [String: Int]){
        self.name = name
        self.citizens = citizens
        self.resources = resources
    }
    func fortify(){
        print("Defences increased!")
    }
}

var anotherTown = Town(name: "Nameless Island", citizens: ["Tom Hanks"], resources: ["Coconuts": 100])
anotherTown.citizens.append("Matilda")

var ghostTown = Town(name: "Ghosty McGhostface", citizens: [], resources: ["Tunbleweed": 1])

 

* return ํ•จ์ˆ˜ ์˜ˆ์‹œ ์ฝ”๋“œ

return ํ•จ์ˆ˜๋Š” ๊ธฐ๋ณธ ํ•จ์ˆ˜์— return ํ™”์‚ดํ‘œ๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

func getMilk (money: Int) -> Int{
    let change = money - 2
    return change
}

 

* ์ˆ˜ํ•™ ํ•จ์ˆ˜

์ œ๊ณฑ: pow(3, 2) // 9

์ œ๊ณฑ๊ทผ: sqrt(9) // 3

 

728x90