본문 바로가기
iOS앱개발

iOS프로그래밍 기초 - Swift 2주차

by 김경래 2025. 9. 8.

mac 외워야 하는 키

 

 

 

 

 

 

FlappySwift 소스 코드

//
//  GameViewController.swift
//  FlappyBird
//
//  Created by Nate Murray on 6/2/14.
//  Copyright (c) 2014 Fullstack.io. All rights reserved.
//

import UIKit        // iOS의 사용자 인터페이스를 구성하는 데 사용하는 기본 프레임워크
import SpriteKit    // SpriteKit은 2D 게임을 만들 수 있게 해주는 애플의 프레임워크

// MARK: - SKNode 확장 (extension)
// 게임 씬을 .sks 파일에서 불러오는 커스텀 메서드를 정의합니다.
extension SKNode {
    class func unarchiveFromFile(_ file : String) -> SKNode? {
        
        // .sks 파일 경로를 찾습니다. (.sks는 SpriteKit에서 만든 씬 파일입니다)
        let path = Bundle.main.path(forResource: file, ofType: "sks")
        
        let sceneData: Data?
        do {
            // 해당 경로의 파일을 Data 형태로 불러옵니다
            sceneData = try Data(contentsOf: URL(fileURLWithPath: path!), options: .mappedIfSafe)
        } catch _ {
            // 실패 시 nil 저장
            sceneData = nil
        }

        // 데이터를 통해 NSKeyedUnarchiver를 초기화 (아카이빙된 데이터를 복원하는 객체)
        let archiver = NSKeyedUnarchiver(forReadingWith: sceneData!)
        
        // SKScene 클래스 정보를 등록 (디코딩 시 어떤 클래스로 해석할지 지정)
        archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
        
        // 아카이브된 루트 객체를 GameScene으로 디코딩합니다
        let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! GameScene
        archiver.finishDecoding()
        
        return scene
    }
}

// MARK: - GameViewController 클래스
// UIViewController는 iOS 앱에서 화면 하나를 담당하는 클래스입니다.
class GameViewController: UIViewController {

    // view가 로드될 때 호출되는 함수 (앱 시작 시 가장 먼저 실행됨)
    override func viewDidLoad() {
        super.viewDidLoad()

        // "GameScene.sks" 파일을 불러와서 GameScene 객체로 변환
        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            
            // 현재의 view를 SKView (SpriteKit을 사용할 수 있는 뷰)로 캐스팅
            let skView = self.view as! SKView
            
            // FPS(초당 프레임 수)와 노드 개수 표시 설정 (디버깅 용도)
            skView.showsFPS = true
            skView.showsNodeCount = true
            
            // 렌더링 최적화 설정: 노드의 순서를 무시하고 성능을 우선시함
            skView.ignoresSiblingOrder = true
            
            // 씬의 크기 조정 방식 설정 (.aspectFill은 화면에 맞게 잘라서 맞춤)
            scene.scaleMode = .aspectFill
            
            // 씬을 SKView에 표시
            skView.presentScene(scene)
        }
    }

    // 화면 회전을 허용할지 여부 설정 (true면 회전 허용)
    override var shouldAutorotate : Bool {
        return true
    }

    // 지원하는 화면 방향 설정
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            // iPhone인 경우, 위쪽 거꾸로 모드는 제외
            return UIInterfaceOrientationMask.allButUpsideDown
        } else {
            // iPad 등은 모든 방향 허용
            return UIInterfaceOrientationMask.all
        }
    }

    // 메모리 부족 경고 시 호출되는 메서드
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // 캐시된 데이터 등을 해제하여 메모리 절약
    }
}

 

 

 

 

 

스위프트 스타일 가이드

https://github.com/swift-kr/swift-style-guide-raywenderlich/blob/master/ko_style_guide.md

 

swift-style-guide-raywenderlich/ko_style_guide.md at master · swift-kr/swift-style-guide-raywenderlich

The official Swift style guide for raywenderlich.com. - swift-kr/swift-style-guide-raywenderlich

github.com

 

 

 

 

현재 가장 최근 버전인 6.2버전을 이용해보고 싶다면

https://swiftfiddle.com/

 

Swift Online Playground

SwiftFiddle is an online playground for creating, sharing and embedding Swift fiddles (little Swift programs that run directly in your browser).

swiftfiddle.com

 

 

 

Xcode 자동 수정 기능

 

Xcode 사용 중 오류가 뜰 시 빨간 아이콘을 누르고 Fix클릭하면 자동으로 수정해준다.

 

 

 

print 함수 사용 예시

print("안녕") // 문자열 출력
print(123) // 정수 출력
var age = 20
var name = "Smile"
print(age)
print(age, name) //공백으로 구분
print("나이는 \(age)입니다") // 문자열 보간 (string interpolation), \(변수명 or 상수명)
print(1, 2, 3) //공백으로 구분
print(1, 2, 3, separator: "-") //공백 구분자를 변경
print("Smile")
print("Han")
print("Hello", terminator: " ") // 줄 바꿈(\n) 대신 공백을 끝에 추가
print("World!")
print("다음", terminator: "") // 줄 바꿈도, 공백도 추가하지 않음
print("입니다.")

 

 

위 코드를 출력하면 다음 같은 결과가 나온다.

 

 

 

 

 

Swift에서 separator는 공백 구분자를 변경하고, terminator는 줄 바꿈도, 공백도 추가하지 않는다.

'iOS앱개발' 카테고리의 다른 글

iOS프로그래밍 3주차  (0) 2025.09.15