[Swift] The Basics

East Silver·2021년 12월 24일
0

Swift 공식 문서 The Basics를 바탕으로 정리합니다!

Type Aliases

: an alternative name for an existing type
Type aliases are useful when you want to refer to an existing type by a name that’s contextually more appropriate, such as when working with data of a specific size from an external source

typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound is now 0

Tuples

: Tuples group multiple values into a single compound value.
같은 타입이 아니여도 튜플형태로 묶을 수 있다.

decompose a tuple’s contents into separate constants or variables

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"

access the individual element values in a tuple using index numbers starting at zero

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"

name the individual elements in a tuple when the tuple is defined

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

If you name the elements in a tuple, you can use the element names to access the values of those elements:

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

: 값이 있을 수도 있고 없을 수도 있는 상황에 사용합니다
Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

nil

can’t use nil with non-optional constants and variables.
If you define an optional variable without providing a default value, the variable is automatically set to nil for you

If Statements and Forced Unwrapping

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

Optional Binding !!(업데이트중)

if let constantName = someOptional {
    statements
}

Implicitly Unwrapped Optionals !!

Error Handling

func canThrowAnError() throws {
    // this function may or may not throw an error
}

do {
    try canThrowAnError()
    // no error was thrown
} catch {
    // an error was thrown
}

Assertions and Preconditions

: 런타임 시 발생하는 것들을 확인. Assertion은 개발과정에서 실수를 잡고 preconditions는 문제를 감지하는 데 도움을 줍니다.
assertion 또는 precondition 의 조건이 true 면 코드는 계속 실행되고 false 면 현재 프로그램 상태가 invalid 하다고 판단되어서 코드 실행이 멈추고 앱이 종료된다!

Debugging with Assertions

  • assert(::file:line:)
let age = -3 
assert(age >= 0, "A person's age can't be less than zero.") 
// This assertion fails because -3 is not >= 0.
  • assertionFailure(_:file:line:)
    이미 조건을 사용하고 있을때 사용
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.")
}

Enforcing Preconditions

: precondition은 조건이 거짓이 될 가능성이 있지만 코드가 실행되기 위해선 반드시 참이어야 할 때 사용합니다.

  • precondition(::file:line:)
// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")
  • preconditionFailure(_:file:line:)
    이미 조건을 사용하고 있을때 사용
profile
IOS programmer가 되고 싶다

0개의 댓글