소피it블로그

[Swift 공식문서] The Basics 정리 (4) - Type Safety and Type Inference 타입 세이프티와 타입 추론 본문

개발_iOS/스위프트

[Swift 공식문서] The Basics 정리 (4) - Type Safety and Type Inference 타입 세이프티와 타입 추론

sophie_l 2022. 5. 10. 21:57

https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

 

The Basics — The Swift Programming Language (Swift 5.6)

The Basics Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. Swift provides its own versions of all fundamental

docs.swift.org

스위프트는 type-safe한 언어이므로, 코드에 사용하는 값들의 타입에 엄격하다. 스위프트는 컴파일 과정에서 type check를 수행하여 오류가 있으면 찾아낸다. 이를 통해 개발의 이른 단계에서 오류를 찾아내고 고칠 수 있다.

 

그렇지만 모든 상수와 변수에 일일이 타입을 지정해줄 필요는 없다. 스위프트는 컴파일시 타입 추론을 통해 제공된 값들의 타입을 추론해낸다.

let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int

let pi = 3.14159
// pi is inferred to be of type Double

let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

스위프트는 실수형 값에 대해서 항상 Float가 아닌 Double로 추론한다. 또한 정수와 실수를 같은 수식에 사용한다면 이는 Double로 추론된다. 숫자 3에 타입이 지정되어있지 않기 때문에 뒤에 더해진 실수형에 따라 Double로 추론되는 것.