The Basics(기초)

apwierk·2022년 5월 18일
0

SwiftGuideLine

목록 보기
1/2

Swift는 iOS, macOS, watchOS 및 tvOS 앱 개발을 위한 새로운 프로그래밍 언어입니다.

C, Objective-C 개발 경험은 Swift의 많은 부분과 비슷합니다.

상수 및 변수

상수와 변수는 이름을 특정 유형의 과 연결합니다. 상수 값은 한 번 설정되면 변경할 수 없지만 변수는 나중에 다른 값으로 설정할 수 있습니다.

상수 및 변수 선언

상수와 변수는 사용하기 전에 선언해야 하빈다. 키워드로 상수를 선언하고 let키워드로 변수를 선언합니다. 다음은 사용자의 로그인 시도 횟수를 추저가힉 위해 상수와 변수를 사용하는 방법의 예입니다.

let name = 10
var bonf = 0

쉼표로 구분하여 한 줄에 여러 상수 또는 여러 변수를 선언할 수 있습니다.

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

코드에 저장된 값이 변경되지 않으면 항상 let키워드를 사용하여 상수로 선언하십시오. 변경할 수 있어야 하는 값을 저장하는 경우에만 변수를 사용하십시오.

상수 및 변수 이름 지정

상수 및 변수 이름에는 유니코드 문자를 포함하여 거의 모든 문자가 포함될 수 있습니다.

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

상수 및 변수 이름에는 공백 문자, 수학 기호, 화살표, 전용 유니코드 스칼라 값 또는 선 및 상자 그리기 문자를 사용할 수 없습니다. 숫자가 이름의 다른 곳에 포함될 수 있지만 숫자로 시작할 수도 없습니다.

특정 유형의 상수 또는 변수를 선언한 후에는 동일한 이름으로 다시 선언하거나 다른 유형의 값을 저장하도록 변경할 수 없습니다. 또한 상수를 변수로, 변수를 상수로 변경할 수 없습니다.

변수와 달리 상수 값은 설정 후에 변경할 수 없습니다. 그렇게 하려고 하면 코드가 컴파일될 때 오류로 보고됩니다.

let languageName = "Swift"
languageName = "Swift++"
// This is a compile-time error: languageName cannot be changed.

세미콜론

한 줄에 여러 개의 별도 명령문을 작성하려면 세미콜론이 필요합니다.

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

정수

정수 는 42-23와 같이 분수 구성요소가 없는 정수입니다. 정수는 부호가 있거나 (양수, 0 또는 음수) 부호가 없습니다(양수 또는 0).

정수 경계

min및 max속성 을 사용하여 각 정수 유형의 최소값 및 최대값에 액세스할 수 있습니다 .

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

유형 별칭

유형 별칭 은 기존 유형의 대체 이름을 정의합니다. typealias키워드 로 유형 별칭을 정의합니다 .

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

Boolean

Swift는 두 가지 Boolean 상수 값을 제공 하며 true과 false가 있습니다.

let orangesAreOrange = true
let turnipsAreDelicious = false

if turnipsAreDelicious {
    print("Mmm, tasty turnips!")
} else {
    print("Eww, turnips are horrible.")
}
// Prints "Eww, turnips are horrible."

Swift의 유형 안전성은 Bool이 아닌 값이 입력될 경우 다음 컴파일 오류를 보고합니다.

let i = 1
if i {
    // this example will not compile, and will report an error
}

하지만, 대체 예가 존재합니다.

let i = 1
if i == 1 {
    // this example will compile successfully
}

튜플 (Tuple)

튜플 은 여러 값을 단일 복합 값으로 그룹화합니다. 튜플 내의 값은 모든 유형이 될 수 있으며 서로 동일한 유형일 필요는 없습니다.

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (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"

또는 0에서 시작하는 인덱스 번호를 사용하여 튜플의 개별 요소 값에 액세스합니다.

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)

값이 없을 수 있는 상황에서 Optional을 사용 합니다. 옵셔널은 두 가지를 나타냅니다. 값이 있거나 값이 없습니다(nil).

String타입을 Int형으로 변환해 줄 경우 변환이 될 지 안될 지 모르기 때문에 Optinal값을 반환합니다.

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

nil

nil이라는 값을 할당하여 값이 없는 상태로 설정합니다.

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

변수 타입이 옵셔널 ? 상태에서 nil 값을 할당 가능합니다.

if 문과 강제 언래핑(Forced Unwrapping)

if 문을 사용하여 옵셔널에 값이 있는지 없는지 확인할 수 있습니다.

옵셔널에 값이 포함되어있다고 확신하면 !를 이름 끝에 추가하여 강제 언래핑을 해줍니다.

if convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}
// Prints "convertedNumber has an integer value of 123."

단, 강재 언래핑을 사용하는 경우 만약 존재하지 않는 값이 있다면 런타임 오류가 발생됩니다.

옵셔널 바인딩 (Optional Binding)

옵셔널 바인딩을 사용하여 옵셔널에 값이 포함되어 있는지 확인하고, 포함되어 있다면 임시 상수나 변수로 사용합니다.

if let actualNumber = Int(possibleNumber) {
    print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("The string \"\(possibleNumber)\" couldn't be converted to an integer")
}
// Prints "The string "123" has an integer value of 123"

쉼표로 구분하여 필요한 만큼 if 문 하나에 여러 상수나 변수를 할당할 수 있습니다.

if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}
// Prints "4 < 42 < 100"

오류처리 (Error Handling)

오류 처리를 사용하여 프로그램 실행 중에 발생할 수 있는 오류 상황에 전파합니다.

func makeASandwich() throws {
    // ...
}

enum SandwichError {
		case outOfCleanDishes
		case missingIngredients(_ ingredients: IngredintsType)
}

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

예와 같이 makeASandwich함수가 실행될 때 발생할 수 있는 오류 케이스를 SandwichError에 정의하고, do-try문에서 함수를 실행합니다. 실행 중에 발생되는 오류는 catch SandwichError.ErrorCase로 throw해줍니다.

catch SandwichError.missingIngredients(let ingredients) 문 처럼 throw해주면서 파라미터로 값을 넘겨줄 수도 있습니다.

profile
iOS 꿈나무 개발자

0개의 댓글