[Swift] Playgrounds Learn to Code 1-06. While Loops

BOMY·2022년 9월 22일

Playgrounds

목록 보기
6/6
post-thumbnail

<TIL 작성 목표>

  • Playgrounds Learn to Code 1, 2의 챕터, 목차를 내 언어로, 한 문장으로 설명할 수 있을 때까지 해보기! 초등학생한테 이해시킬 수 있을 정도로!
  • 주변 개념까지 정리하고 Playground의 설명으로 충분하지 않으면 검색해서 찾아보고 내 생각을 찾아서 정리해 보기!
    ex) 논리 연산자가 뭐예요? 왜 써요? 종류는요?


나의 iOS 개발 커리큘럼

  • Playgrounds Learn to Code 1
    - Commands ✔
    - Functions ✔
    - For loops ✔
    - Conditional Code ✔
    - Logical Operators ✔
    - While Loops ✔
    - Algorithms
  • Playgroubds Learn to Code 2
    - Variables
    - Types
    - Initialization
    - Parameters
    - World Building
    - Arrays
  • iOS App Dev Tutorials - 3개월간 2~3회독
  • Boostcourse - 6개월


Playground Learn to Code 1

👉 While Loops (While 반복문)

  • While loop is A block of code that runs for as long as a given condition is true. When the condition changes to false, the loop stops running. While 반복문은 주어진 조건이 true인 동안 실행되는 코드 블럭이다. 조건이 false로 바뀌면 반복은 멈춘다!

    When you're hammering a nail, you can't just hit it a certain
    number of times and expect it to go all the way in.
    
    Instead, you continue hitting the nail while the nail is
    sticking out.
    
    You can use a while loop to repreat a command,
    or set of commands, while a condition is true.
    
    while nailIsStickingOut {
    	hammerNail()
    }
    
    
    
  • Using while loops is already making your code simpler. By pairing a while loop and conditional code, you can write code that's much more adaptable.

  • While Loops part words

    • nail: a small metal spike with a broadened flat head, driven typically into wood with a hammer to join things together or to serve as a peg or hook
      넓고 납작한 머리를 가진 작고 뾰족한 금속(못), 일반적으로 나무에 망치와 함께 다른 것들을 연결하거나 고정하거나 갈고리로 제공된다.
    • spike: a thin, pointed piece of metal, wood, or another rigid material.
      금속이나 나무, 다른 재질의 얇고 뾰족한 조각
    • rigid: unable to bend or be forced out of shape; not flexible
      구부러지지 않고 모양이 유동적이지 않고 고정된 모양, 단단한
    • broaden: become larger in distance from side to side; widen
      옆으로 확장되는 것
    • stick out: be extremely noticeable
      극도로 명확한, 눈에 띄는
    • adapt: able to be modified for a new use or purpose
      새로운 용도나 목적에 맞게 수정할 수 있는, 유동적인, 적응할 수 있는! (충전할 때 사용하는 어댑터 생각!)
    • modified: make partial or minor changes to (something), typically so as to improve it or to make it less extreme
      부분적이고 작은 부분들을 어떤 것으로 바꾸는 것, 수정하다
    • reusablility: A characteristic of code that allows it to be used in different situations within an application.
      응용프로그램 내에서 다른 상황에서도 사용할 수 있게 허가하는 코드의 특성, 재사용성

👉 예제문제 - While Loops

(예제 문제들 중 더 클린하게 작성할 수 있을 지 고민이 필요한 코드 모음)

  • Turned Around

    func collectGemAndTurnLeftAndMoveForward() {
      collectGem()
      turnLeft()
      moveForward()
    }
    
    for i in 1 ... 4 {
        moveForward()
        while isOnGem {
            collectGemAndTurnLeftAndMoveForward()
        }
        if !isBlocked && !isBlockedLeft && !isBlockedRight {
            turnRight()
        }
    }
    
  • Land of Bounty (switch/gem 개수 바뀜)

    func moveForwardAndCollectOrToggle() {
        if isOnClosedSwitch {
            toggleSwitch()
        } else if isOnGem {
            collectGem()
        } else {
            moveForward()
        }
    }
    
    for i in 1 ... 3 {
        while !isBlocked {
            moveForwardAndCollectOrToggle()
        }
        if isBlocked && isBlockedLeft {
            turnRight()
            moveForward()
            turnRight()
        } else if !isBlockedLeft && !isBlockedRight {
            turnLeft()
            moveForward()
            turnLeft()
        }
    }
  • You're Always Right

    while !isOnGem {
        while !isBlocked {
            if isOnClosedSwitch {
                toggleSwitch()
            } else {
                moveForward()
            }
        }
        turnRight()
    }
    collectGem()
    • 마지막 예제의 collectGem()을 while 조건문 안에 넣어보고 싶은데 방법이 없을까...? 🤔

👉 한 줄로 요약한 While Loops

While Loops(While 반복문)주어진 조건이 참(true)일 경우에만 반복하는 코드이다.

  • 추가적으로, While Loops의 조건은 Boolean값으로 참(true) 혹은 거짓(false)이다.



22.09.30, 10.03, 12 TIL 끝!


썸네일은 Banner Maker로 제작하였습니다.

profile
한 걸음 한 걸음!

1개의 댓글

comment-user-thumbnail
2022년 12월 29일

기초를 탄탄히!! 잘보았습니다! 👍🏻

답글 달기