2016. 8. 21. 12:25ㆍSwift
// The Basics
// 상수(Constants) 와 변수(Variables)
let 상수명 = 1 // 상수 선언에는 let
var 변수명 = 2 // 변수 선언에는 var
let π = 3.141592 // option + p : π
let 五 = 5 // option + return : 한자변환
let 🐶🐮 = "dogcow" // control + command + space : 이모티콘
// 한줄에 여러 변수 선언하기
var x = 0.0, y = 0.0, z = 0.0
// Type Annotations(데이터형 명시)
var welcomeMessage: String
welcomeMessage = "Hello"
var red, green, blue: Double // red, green, blue 모두 Double형
// The colon in the declaration means "...of type...,"
// so the code above can be read as:
// "Declare a varialbe called welcomeMessage that is of type String."
// \()를 String Interpolation이라고 함.
print("영어 인사: \(welcomeMessage)")
print("영어 인사: \(welcomeMessage)", terminator:".")
// 주석(Comments)
// This si a comment.
/* This is also a comment
but is written over multiple lines. */
/* This is the start of the first multiline comment.
/* This is the second, nested multiline comment. */
This is the end of the first multiline comment. */
// Semicolons
// 한줄에 여러라인을 작성하고 싶을 때 세미콜론(;)을 사용한다.
let cat = "🐱"; print(cat)
// Integer
var aa: UInt8 = 1 // unsigned integer
var bb: Int32 = 2 // signed Integer
// Integer Bounds
let minValue = UInt8.min; print(minValue)
let maxValue = UInt8.max; print(maxValue)
//Int
// 32bit 플레폼에서 Int는 Int32와 같다
// 64bit 플레폼에서 Int는 Int64와 같다
// 32bit 플레폼에서 UInt는 UInt32와 같다
// 64bit 플레폼에서 UInt는 UInt64와 같다
// 부동소수점(floating-point) 64비트는 Double, 32비트는 Float
// A decimal number, with no prefix
// A binary number, with a 0b prefix
// A octal number, with a 0o prefix
// A hexadecimal number, with a 0x prefix
let decimalInteger = 17
let binaryInteger = 0b10001 // 17
let octalInteger = 0o21 // 17
let hexadecimalInteger = 0x11 // 17
// 10exp
// 1.25e2 means 1.25 x 10², or 125.0.
// 1.25e-2 means 1.25 x 10⁻², or 0.0125.
// 0xFp2 means 15 x 2², or 60.0.
// 0xFp-2 means 15 x 2⁻², or 3.75.
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1 // 콤마 대신 _
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pi)
// Type Aliases
typealias UIT = UInt
let aba: UIT = 1
// Tuples 함수의 리턴값으로 특히 유용하게 사용 할 수 있다.
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)", terminator:"")
print("The status code is \(http404Error.0)")
print("The status message is \(statusMessage)")
print("The status message is \(http404Error.1)")
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")
// Optionals
// You use optionals in situations where a value may be absent(부재의)
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber는 데이터ㄴ형이 Int? 또는 Int 둘중에 어떤 것 일까?
// Int? 이다
// String은 변환했을때 String? 이 아니고 그냥 String이다.
var serverResponseCode: Int? = 404
serverResponseCode = nil
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
//In Swift, nil is not a pointer--it is the absense of value of a certain type.
//Optionals of any type can be set to nil, not just Object types.
//어떤 타입의 Optionals도 nil로 셋팅 할 수 있다, 꼭 Object types 아닌.
// If Statements and Forced Unwrapping
// == equal to, != not equal to 라고 읽는다.
if convertedNumber != nil {
print("convertedNumber contains some inter value.")
print("convertedNumber has an integer value of \(convertedNumber!).")
print("convertedNumber has an integer value of \(convertedNumber).")
}
// Optional Binding
// if let 상수명 = 옵션널변수명 {
// 구문
// }
if let actualNumber = Int(possibleNumber) {
print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("\"\(possibleNumber)\" could not be converted to an integer")
}
if let firstNumber = Int("4"), let secondNumber = Int("42") where firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
// Imlicitly Unwrapped Optionals
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString
if assumedString != nil { // exclamation mark(!) 를 사용하여 nil과 비교 할 수 있다.
print(assumedString)
}
if let definiteString = assumedString {
print(definiteString)
}
var optionalOne: Int? = 123
print(String(optionalOne))
print(String(optionalOne!))
var exclamationOne: Int! = 1234
var optionalTwo = Optional(2)
print(optionalTwo)
/*
* forced Unwrapping Keyword : !
* 1. Optional 변수는 연산이 되지 않는다. 연산을 하려면 Unwrapping을 해줘야한다.
* 2. Optional 변수는 Default값이 nil이다.
그리고 nil상태의 Optional 변수는 Unwrapping 할 수 없다.
* 3. Optional 변수를 Unwrapping하고 나면, forced Unwrappingd으로 nil값을 할당 할 수 없다.
Unwrapping 이후는 일반 변수가 되기 때문이다.
*/
print("two + 1 = \(optionalTwo! + 1)")
let nilString: String?
//print(nilString!) 2번의 이유로 에러가 발생한다.
var nilStringX: String? = nil
nilStringX = "hey"
print(nilStringX!)
var nilStringY = nilStringX
nilStringY = nil
// !에 의해 Unwrapping 됐을 뿐 변수자체가 변경된 것은 아니다.
// 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
let age = -3
//assert(age >= 0, "A person's age cannot be less than zero")
//assert(age >= 0)
// this causes the assertion to trigger, because age is not >= 0
출처 : The Swift Programming Language(iBook)