728x90
반응형

스위프트는 정수형 타입인 Int와 실수형 타입인 Double, Float와 참과 거짓을 나타내는 Bool과 문자열을 나타내는 String의 데이터 타입이 있고 Collection 타입인 Array, Set, Dictionary도 제공합니다. 또한 Objective-C에서 제공하던 Tuple도 제공합니다. 그리고 새로 추가된 Optional을 제공합니다. Optional타입은 nil값을 저장 할 수 있습니다.


스위프트에서 데이터는 상수 또는 변수로 나타낼 수 있습니다. 상수는 let 키워드를 사용하고 변수는 var 키워드를 사용합니다.


let maximumNumberOfLoginAttempts = 10

var currentLoginAttempt = 0


이 코드는 아래와 같이 해석 할 수 있습니다.

maximumNumberOfLoginAttempts 상수를 선언 했고 10으로 초기화 했다.

currentLoginAttempt 변수를 선언 했고 0으로 초기화 했다.


그리고 한 줄에 여러개의 변수를 선언함과 동시에 초기화도 같이 할 수 있습니다.


var x = 0.0, y = 0.0, z = 0.0


만약에 우리가 변수를 선언하고 값을 초기화 하지 않으면 어떤 일이 발생할까요?


var x

이렇게 type annotation이 빠졌다고 에러를 보여주게 됩니다.


그럼 Type Annotation이란 무엇일까요?

Type Annotation은 변수나 상수의 이름 뒤에 "이것이 어떤 타입이다"라고 명시적으로 알려주는 것입니다.


var welcomeMessage: String

바로 이렇게 말이죠.


여기서 :은 of type라는 의미를 가지고 있습니다. welcomeMessage는 String type의 var라는 거죠.


Integer(정수)는 소수점이 없는 숫자를 나타낼 수 있습니다.

기본적으로 Int는 32비트 플랫폼에서는 Int32처럼 동작하고 64비트 플랫폼에서는 Int64처럼 동작합니다.

UInt는 unsigned int로 0이상의 자연수를 나타낼 수 있습니다. 다른말로 음수값은 가질 수 없는 거죠.

UInt도 Int와 마찬가지로 32비트, 64비트 플랫폼에 따라 UInt32, UInt64로 동작합니다.


실수는 Double과 Float로 나타낼 수 있습니다.

Double은 64비트 범위를 나타낼 수 있고 Float는 32비트 범위를 나타낼 수 있습니다.



정수는 Literal을 이용하면 2진수, 8진수, 16진수로 나타낼 수 있습니다.


let decimalInteger = 17

let binaryInteger = 0b10001       // 17 in binary notation

let octalInteger = 0o21           // 17 in octal notation

let hexadecimalInteger = 0x11     // 17 in hexadecimal notation


실수도 Literal을 이용해서 만들 수 있습니다.


let literalDecimal1 = 1.25e2    // 125

let literalDecimal2 = 1.25e-2   // 0.0125

let literalDecimal3 = 0xfp0     // 15

let literalDecimal4 = 0xfp2     // 60

let literalDecimal5 = 0xfp-2    // 3.75


e는 10^이고 p는 2^ 입니다.

1번은 1.25 * 10^2

2번은 1.25 * 10^-2

3번은 15 * 2^0

4번은 15 * 2^2

5번은 15 * 2^-2


튜플은 여러개의 값을 그룹화 시킬 수 있습니다.

예를 들어서 HTTP status code인 404는 "Not Found" 입니다.

이것은 (404, "Not Found")라고 튜플형태로 만들 수 있습니다.


let http404Error = (404, "Not Found")


이것을 사용하기 위해서는

1.

let (statusCode, statusMessage) = http404Error

print("The status code is \(statusCode)")

// Prints "The status code is 404"

print("The status message is \(statusMessage)")

// Prints "The status message is Not Found


2.

let (justTheStatusCode, _) = http404Error

print("The status code is \(justTheStatusCode)")

// Prints "The status code is 404


3. 

print("The status code is \(http404Error.0)")

// Prints "The status code is 404"

print("The status message is \(http404Error.1)")

// Prints "The status message is Not Found


4.

let http200Status = (statusCode: 200, description: "OK")

print("The status code is \(http200Status.statusCode)")

// Prints "The status code is 200"

print("The status message is \(http200Status.description)")

// Prints "The status message is OK


이런식으로 사용 할 수 있습니다.


튜플을 사용하게 되면 함수에서 여러개의 값을 한번에 리턴 시킬 수 있습니다.


Optional은 C나 Objective-C에서는 없던 개념입니다.

이것은 값의 부재를 나타냅니다. 다른 말로 값이 있던지, 값이 없던지 입니다.

값이 있는 것은 정수형에서는 0이나 19로 나타내는 것이고 값이 없다는 것은 nil로 값을 설정해주는 것입니다.


var serverResponseCode: Int? = 404

// serverResponseCode contains an actual Int value of 404

serverResponseCode = nil

// serverResponseCode now contains no value


Optional은 타입뒤에 ?를 붙여줍니다.

serverResponseCode는 Optional Int타입이며 404 값으로 초기화 되었습니다.

그 다음에 nil로 값을 비워줬습니다.


nil은 Optional 타입이 아닌 변수에 설정 할 수 없습니다.

Optional 타입의 변수에 값을 초기화 해주지 않으면 스위프트는 자동으로 nil값으로 초기화 해줍니다.


728x90
반응형

'Language > Swift' 카테고리의 다른 글

(Swift) 스위프트 연산자(Operator) 기초  (0) 2017.10.09
(Swift) 스위프트 맛보기  (0) 2017.10.07

+ Recent posts