Develop/Swift

Swift 요약 1

hsleedevelop 2022. 5. 8. 15:45
반응형

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

Numeric Literals

정수 리터럴

let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

부동 소수점 리터럴 - 10진수는 접두사가 없고, 16진수일 때 0x 접두사, e로 표시되는 지수를 가질 수 있음

10진수

  • 1.25e2 = 1.25 x 102, or 125.0.
  • 1.25e-2 = 1.25 x 10-2, or 0.0125.

16진수 - e가 아닌 p로 지수를 표현

  • 0xFp2 means 15 x 22, or 60.0.
  • 0xFp-2 means 15 x 2-2, or 3.75.

12.1875 10진수 를 부동 소수점 리터럴로 표현한 예

let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0

숫자 리터럴에 가독성을 위한 0 또는 _ 을 사용 가능하다.

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

some test

let sss = "1e3"
let fff: Float = Float(sss) ?? 0
let ddd = Double(sss)!
let iii = Int(ddd)

print("fff=\(fff)")
print("ddd=\(ddd)")
print("iii=\(iii)")

> fff=1000.0
> ddd=1000.0
> iii=1000

Numeric Type Conversion

Integer Conversion

범위를 벗어나는 경우

let cannotBeNegative: UInt8 = -1
// UInt8 can't store negative numbers, and so this will report an error
let tooBig: Int8 = Int8.max + 1
// Int8 can't store a number larger than its maximum value,
// and so this will also report an error

부호, 미부호 정수간의 연산 시 타입 캐스팅 필수

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

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

부동 소수점을 정수로 변환 시

let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int

Tuple

일부만 사용하는 경우,

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")
//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

nil

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

자동으로 nil로 설정

var surveyAnswer: String?
// surveyAnswer is automatically set to nil

Optional Binding

옵셔널에 값이 있을 경우, 해당 값을 가지는 상수나 변수를 만든다.
if, while 문에서 사용 가능

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

some tests

let someInt: Int! = nil //nil 초기화 가능
print("someInt=\(someInt!)") //Fatal error: Unexpectedly found nil while unwrapping an Optional value
var ioptional: Int! //nil 초기화
ioptional = nil     //nil 할당
print(ioptional!)   //Fatal error: Unexpectedly found nil while unwrapping an Optional value

unwrapping case

let optionalString = assumedString!
// The type of optionalString is "String?" and assumedString isn't force-unwrapped

if assumedString != nil {
    print(assumedString!)
}

if let definiteString = assumedString {
    print(assumedString)
}

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
}
func makeASandwich() throws {
    // ...
}

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

Assertions and Preconditions

Assertions - Debug 모드에서만 활성
Preconditions - Debug, Release 모든 모드에서 활성

Debugging with Assertions

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

assert(age >= 0) //메시지 생략도 가능

Enforcing Preconditions

앱 강제 종료라는 강력한 제제로 잘못된 사용을 미연에 방지하기 위한 방법

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

If you compile in unchecked mode (-Ounchecked), preconditions aren’t checked. The compiler assumes that preconditions are always true, and it optimizes your code accordingly. However, the fatalError(_:file:line:) function always halts execution, regardless of optimization settings.

You can use the fatalError(_:file:line:) function during prototyping and early development to create stubs for functionality that hasn’t been implemented yet, by writing fatalError("Unimplemented") as the stub implementation. Because fatal errors are never optimized out, unlike assertions or preconditions, you can be sure that execution always halts if it encounters a stub implementation.

반응형