Swift
Swift
Apple's iOS/macOS development language. Focuses on safety and performance.
Swift
Apple's iOS/macOS development language. Focuses on safety and performance.
Swift is a general-purpose programming language announced by Apple at WWDC in 2014, designed for developing iOS, macOS, watchOS, and tvOS applications. Built on a modern and safe language design philosophy, it helps developers write faster and more reliable code.
Swift was developed to replace Objective-C, the mainstay language of the Apple ecosystem. It removes the complexity that came from Objective-C's 30-year history and its C language compatibility, and thanks to LLVM compiler optimization it delivers up to 2.6x faster performance than Objective-C. It was open-sourced in 2015 and can also be used on Linux and Windows.
Swift's key characteristics are Safety, Performance, and Expressiveness. Optional types prevent nil reference errors at compile time, and ARC (Automatic Reference Counting) manages memory automatically. It also encourages code reuse that is more flexible than inheritance through Protocol-Oriented Programming.
In practice, Swift is the standard language for iOS/macOS app development and, combined with SwiftUI, supports declarative UI development. Recently it has been expanding into server-side development through frameworks such as Vapor and Kitura, and into machine learning through Swift for TensorFlow.
// Swift 기본 문법 예제
// 1. 변수와 상수
var mutableVariable = "변경 가능" // var: 변수
let immutableConstant = "변경 불가" // let: 상수 (권장)
// 2. 타입 추론과 명시적 타입
let inferredInt = 42 // 타입 추론: Int
let explicitDouble: Double = 3.14 // 명시적 타입 선언
// 3. 문자열 보간
let name = "Swift"
let version = 5.9
print("Hello, \(name) \(version)!") // "Hello, Swift 5.9!"
// 4. 컬렉션
let fruits = ["Apple", "Banana", "Cherry"] // 배열
let scores = ["Alice": 95, "Bob": 87] // 딕셔너리
// 5. 조건문과 반복문
for fruit in fruits {
print(fruit)
}
if let score = scores["Alice"] {
print("Alice's score: \(score)")
}
// 6. 함수
func greet(person name: String, from city: String = "Seoul") -> String {
return "Hello \(name) from \(city)!"
}
let greeting = greet(person: "Kim", from: "Busan") // 외부 파라미터명 사용
// 7. 클로저
let numbers = [3, 1, 4, 1, 5, 9]
let sorted = numbers.sorted { $0 < $1 } // 축약 문법
let doubled = numbers.map { $0 * 2 }
// Swift Optional - nil 안전성의 핵심
// Optional 선언: 값이 있을 수도, nil일 수도 있음
var nickname: String? = nil
var age: Int? = 25
// 1. Optional Binding (if let) - 가장 안전한 방법
if let unwrappedAge = age {
print("나이: \(unwrappedAge)살") // 안전하게 언래핑
} else {
print("나이 정보 없음")
}
// 2. Guard let - 조기 반환 패턴 (함수 내에서 권장)
func processUser(name: String?) {
guard let validName = name else {
print("이름이 필요합니다")
return // 조기 반환
}
// 여기서 validName은 non-optional
print("처리 중: \(validName)")
}
// 3. Nil Coalescing Operator (??) - 기본값 제공
let displayName = nickname ?? "Guest" // nil이면 "Guest"
// 4. Optional Chaining - 연쇄적 접근
struct User {
var address: Address?
}
struct Address {
var city: String?
}
let user: User? = User(address: Address(city: "Seoul"))
let city = user?.address?.city // 중간에 nil이면 전체가 nil
// 5. 강제 언래핑 (!) - 위험! 피해야 함
// let forcedAge = age! // age가 nil이면 크래시!
// 6. Implicitly Unwrapped Optional - IBOutlet 등에서 사용
var button: UIButton! // 초기화 후에는 항상 값이 있다고 가정
// 7. Optional Map/FlatMap
let stringNumber: String? = "42"
let parsedNumber = stringNumber.flatMap { Int($0) } // Int?
// Swift Protocol - 프로토콜 지향 프로그래밍
// 1. 프로토콜 정의
protocol Drawable {
var color: String { get set }
func draw()
}
protocol Resizable {
func resize(scale: Double)
}
// 2. 프로토콜 채택 (클래스, 구조체, 열거형 모두 가능)
struct Circle: Drawable, Resizable {
var color: String
var radius: Double
func draw() {
print("\(color) 원을 그립니다 (반지름: \(radius))")
}
func resize(scale: Double) {
// 구조체는 mutating 키워드 필요 없이 새 인스턴스 반환
}
}
// 3. 프로토콜 확장 - 기본 구현 제공
extension Drawable {
func printDescription() {
print("색상: \(color)")
}
}
// 4. 프로토콜 상속
protocol Shape: Drawable, Resizable {
var area: Double { get }
}
// 5. 제네릭과 프로토콜 제약
func drawAll(_ items: [T]) {
for item in items {
item.draw()
}
}
// 6. 프로토콜 타입으로 사용 (existential type)
var shapes: [any Drawable] = [Circle(color: "Red", radius: 5)]
// 7. Codable - 가장 많이 사용되는 프로토콜
struct User: Codable {
let id: Int
let name: String
let email: String
}
// JSON 인코딩/디코딩
let user = User(id: 1, name: "Kim", email: "kim@example.com")
let jsonData = try? JSONEncoder().encode(user)
let decoded = try? JSONDecoder().decode(User.self, from: jsonData!)
"This is an iOS-only app and needs to make deep use of Apple ecosystem features, so Swift is the right choice. Flutter is cross-platform and good for building both apps quickly, but for Core ML, HealthKit, and Apple Watch integration, native Swift is far more reliable. And with SwiftUI's declarative UI, you can develop as fast as with Flutter."
"Please change the part where you used force unwrapping (!) to guard let. The server response can be nil, so it could crash. It's Swift convention to assume API responses are always Optional and handle them safely with if let or guard let."
"Swift's Optional is a way of explicitly expressing, in the type system, that a value may be absent. Internally it is implemented as an enum, so it has two cases: .some(value) and .none. Because it enforces nil checks at compile time, it eliminates runtime null pointer exceptions at the source. In Objective-C, messages to nil were ignored, but Swift catches this as a compile error."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Force unwrap (!) crashes the app when the value is nil. Use if let, guard let, or nil coalescing (??). Except for IBOutlet, using ! will get your code rejected in code review. Optional binding is the core of Swift's safety.
Swift manages memory with ARC, but retain cycles can occur in closures and delegates. Use [weak self] or [unowned self] in closures, and declare delegates as weak.
Swift evolves quickly and has breaking changes between major versions. Migrating from Swift 4 to 5 required fixes such as changes to String handling. Use the latest version for new projects, and use Xcode's migration tool for existing ones.