Swift 공식문서(1) - The Basics

Jiyoon·2022년 3월 19일
0

iOS

목록 보기
5/16
post-thumbnail

스위프트는 type-safe 언어
String type인 코드에 int를 전달하는 등, type과 관련된 실수들을 미연에 방지해 준다.

Constants and Variables

let Muss = "student" //상수 - 변경 불가능
var Ketchup = "worker" //변수 - 변경 가능
var x = 1, y = 2, z =3 //한 줄에 여러개 변수 선언 가능

ex) 로그인 횟수

상수 - 로그인 시도 최대 횟수(변하지 않아야 함)
변수 - 현재까지 로그인 시도한 횟수(시도할 때마다 값이 변해야됨)

Type Annotations

var welcomeMessage: String
var wlecomeText = "Hi" //type을 설정해주지 않아도 언어가 추론해준다.
var x, y, z : Int //한 줄에 여러개 변수 타입 지정 가능

Naming Constants and Variables

상수와 변수의 이름은 유니코드를 포함한 거의 모든 문자를 포함할 수 있다
하지만 공백, 수학 기호, 화살표, 개인적으로 쓰는 유니코드 스칼라 값, 등은 포함시킬 수 없다
숫자 또한 포함시킬 수 없다

let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"

한 번 상수나 변수를 특정 타입으로 선언하고 나면, 다시 똑같은 이름으로 선언하거나 다른 타입으로 값을 저장할 수 없으며 상수와 변수 사이를 왔다갔다 할 수도 없다.

let languageName = "Swift"
languageName = "Swift++"
// 컴파일 에러 - 상수는 값 변경 불가
// 변수는 값 변경 가능하다

Printing Constants and Variables

기본 설정으로 어떤 라인을 프린트할 때는 Line break를 주면서 한다.

print(someValue, terminator = "")
//line break를 주지 않으려면 terminator 파라미터에 빈 string을 넘겨준다.
print("The current value of friendlyWelcome is \(friendlyWelcome)") //string interpolation
// Prints "The current value of friendlyWelcome is Bonjour!"

Comments

//single line comment

/* multiple line
comments */

/* multiple line
/* inside comment*/
comment*/

comment를 서로 감쌀 수 있다 → 큰 덩어리의 코드안에 comment가 있어도 쉽게 주석 처리 할 수 있다

Semicolons

다른 언어와 달리, Swift는 semicolon을 쓰라고 요구하지 않는다

잘 쓰이지는 않지만, 한 줄에 여러가지 선언을 하고 싶을 때 semicolon을 쓴다

let cat = "🐱"; print(cat)
// Prints "🐱"

Float & Double

Double - 소수점 15째 자리까지 표현 가능
Float - 소수점 6째 자리까지 표현 가능

상황에 맞게 어떤 걸 쓸지 선택하면 되지만, 보통의 경우엔 Double을 쓴다.

Type Safety & Type Inference

처음 선언할 때의 타입이 아닌 다른 타입으로 정의하면 에러

선언할 때 타입을 넣어주지 않아도 넣어준 값을 보고 Swift가 알아서 추론해준다
!! 소수점이 있는 값을 넣을 땐 보통 float이 아닌 double값으로 추론한다

Numeric Literals

decimal number → 1.25e2 = 1.25 X 10^2 = 125.0

읽기 쉽게 추가적인 형태로 값을 넣을 수도 있다

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Integer and Floating-Point Conversion

사칙연산 할 때는 같은 타입끼리 해야 한다

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double

Floating point to integer에서는 항상 소수점 이하는 생략해서 정수로 만든다

Type Aliases

typealias AudioSample = UInt16

타입을 코드 맥락상 더 잘 들어맞는 변수명으로 변경시켜줄 수 있다

Booleans

파이썬과 달리 non-Boolean 타입으로 Boolean 타입을 대체하지 못 한다.
ex) 0 → false, 1 → true 불가능

Tuples

let http404Error = (404, "Not Found")

//각기 다른 변수명으로 분해할 수도 있다
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"

// 사용하지 않을 값은 _로 부여할 수 있다 
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"

//인덱싱도 가능
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"

//선언할 때부터 변수명을 넣을 수 있다
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"

Optionals

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"

String 값을 Int로 바꿀 때 → Int?타입으로 저장된다 ex) “123”

“123”이 아닌 문자열일 때는 아예 타입 전환 불가!

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value

어떤 값이 특정한 상황에서 값을 가지지 않을 때(nil값을 가질 때) → 옵셔널 타입을 부여해준다

Implicitly Unwrapped Optionals

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation point

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation point

만약 어떤 옵셔널이 항상 값이 있을 것이라고 판단할 경우, 그 값에 접근할 때마다 unwrap할 수 있는지 체크하는 것은 비효율적이다 → 항상 값을 가질 것이라고 확신하기 때문

이러한 옵셔널 타입은 필요하다면 강제로 언래핑 할 수 있다고 허락해주는 것

Error Handling

func makeASandwich() throws {
    //샌드위치를 만드는 과정
}

do {
    try makeASandwich()
    eatASandwich()
} catch SandwichError.outOfCleanDishes {
    washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
    buyGroceries(ingredients)
}

Debugging with Assertions

let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 isn't >= 0.

if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age >= 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

assert의 조건에 충족하지 않을 때, 프로그램을 종료시킨다

이미 조건을 확인한 후에는 assertionFailure을 실행시켜서 프로그램을 종료시킨다

Enforcing Preconditions

// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")

어떤 조건이 false가 될 가능성이 있지만, 프로세스를 진행하기 위해서는 꼭 참이 되어야 할 때 쓴다.

0개의 댓글