본문 바로가기
APP 개발 : 기본문법/SWIFT

SWIFT 기본문법

by FRIGATE 2021. 4. 24.

스위프트 플레이그라운드 1강

캐릭터에 움직임을 주기

moveForward()
moveForward()

moveForward()
collectGem()

-> 앞으로 3번 전진 후
    보석수집하는 모션

moveForward()

moveForward()

turnLeft()

moveForward()

collectGem()

-> 앞으로 2번 전진 후
    좌측으로 몸을돌리고
    앞으로 1번 전진 후
    보석수집

toggleSwitch()

-> 스위치 누르기

 

함수 정의하기

중괄호 "{,}" 안에 명령을 추가해서 동작을 부여한다

func tieMyShoe () {
loop()
swoop ()
pull ()
}
func tieMyShoe () {
고리만들기
매듭짓기
당기기
}

 

함수를 정의한 다음 

함수 이름을 호출해서 

함수 명령을 실행한다.

 

구성이란?

없는 명령을 수행하기 위해

기존 명령 (코드) 을 조합하는 기술이다.

 

정사각형 타일 위에서, 캐릭터가 우측을 바라보게 하려면

없는 코드인 turnRight() 대신에

turnLeft() 를 3번 사용하는 걸 뜻한다.

 

없는 코드 "turnRight ()" 를 만들기 위해
함수를 작성해보자.

func turnRight () {
turnLeft()
turnLeft()
turnLeft()
}
 // 새로운 함수 생성완료

turnRight()
turnLeft()
moveForward()
toggleSwitch()

// 새 함수 호출 및 명령 부여!!

 

반복 패턴의 함수 정의하고 호출하기

 

func gotCha() {

moveForward()

collectGem()

moveForward()

toggleSwitch()

}

// 새로운 함수 생성함.

 

gotCha()

moveForward()

turnLeft()

moveForward()

moveForward()

gotCha()

moveForward()

moveForward()

// 반복 패턴의 명령을 gotCha()로 정의하고 호출했다.

 

 

반복 패턴을 파악하고 함수 정의하기

 

func Dash() {

moveForward()

collectGem()

moveForward()

collectGem()

turnRight()

}

// 반복되는 패턴을 새로운 함수로 정의함

 

collectGem()

Dash()

Dash()

Dash()

moveForward()

collecrGem()

turnRight()

moveForward()

collectGem()

// 반복 패턴의 명령을 정의한 새 함수를 호출함

 

분해란?

큰문제를 작은 단위로 나누는것

 

func turnAround() {

turnLeft()

turnLeft()

}

// 좌측 2회 회선을 새 함수로 정의함

 

func solveStair() {

moveForward()

collectGem()

}

// 전진 후, 보석 수집을 새 함수로 정의함

 

solveStair()

turnArounf()

moveForward()

solveStair()

turnAround()

moveForward()

turnLeft()

solveStair()

turnAround()

moveForward()

solveStair() 

// 

 

분해 2탄

 

func collectGemTurnAround() {

moveForward()

moveForward()

collectGem()

turnLeft()

turnLeft()

moveForward()

moveForward()

}

// 앞 2회전진 후, 왼쪽으로 2회 회전 후, 앞 2회전진 후 왼쪽으로 2회 전진

 

func solveRow() {

collectGemTurnAround()

collectGemTurnAround()

}

// 위의 새 함수를 2회 반복하는 명령의 새 함수를 생성함.

 

solveRow()

turnRight()

moveForward()

moveForward()

turnLeft()

solveRow()

turnLeft()

moveForward()

turnLeft()

solveRow()

// 반복 패턴의 함수를 사용해서 명령 짬.