Intro
스위프트는 ios 환경을 위한 새로운 언어이다. 이것은 c,c++와 비슷하기 때문에 배우는데 큰 어려움은 없을 것이다.
swift는 세개의 데이터 타입을 제공한다.
array, tuple, and dictionary이다.
s는 원하는 타입을 전달하는데에 type safty를 하면 실수로 다른 타입을 전달하는 일이 없을 것입니다.
constants and variable
let 은 변하지 않는 것 var 은 변하는 것 , 둘다 초기화 해야됨.
아 글구 콤마를 사용해서 한줄에 정의 가능함. like var x = 0.0, y=0.0, z=0.0
type annotations
var welcomemessage : String
“Declare a variable called welcomeMessage that’s of type String.”
comments
// or /*comments*/
semicolon
let rat ="🐹" ;print(rat)
integer
integer bounds
let maxvalue = UInt.max
//256
let minvalue = UInt.min
//0
floating number
float 32bit
double. 64bit
type safety and type inference
int나 double같은 디테일한 사항은 컴파일하면서 알아서 지정해준다. 사용자는 오직 let과 var만 신경쓰면 된다.
- 1.25e2 means 1.25 x 102, or 125.0.
- 1.25e-2 means 1.25 x 10-2, or 0.0125.
- 0xFp2 means 15 x 22, or 60.0.
- 0xFp-2 means 15 x 2-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
numeric type conversion
최적화나 용량이 아주 큰 상황이 아니라면, 대부분을 int를 사용해라.
type alises
타입을 스스로 지정할 수 있다.
- typealias AudioSample = UInt16
- var minAmplitudeFound = AudioSample.min
- // minAmplitudeFound is now 0
booleans
true 혹은 false이고 데이터 타입을 지정하지 않아도 된다.
let i
if i {
it will not be working successfully
}
let i
if i==1{
it will be working successfully
}
tuples
다른 종류의 데이터를 한 변수에 저장할 수 있다. 주로 웹페이지에서 검색의 성공 혹은 실패를 사용자가 확인 하는데에 사용된다.
더 복잡한 것은 struct와 class을 사용하자.
- 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"
- 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"
optional
값이 없을 수 있는 경우에 사용.
- let possibleNumber = "123"
- let convertedNumber = Int(possibleNumber)
- // convertedNumber is inferred to be of type "Int?", or "optional Int"
int이거나 아니거나
error handling
실행중에 에러를 맞이했을 때, 어떻게 대처 할 것인가?에 대한 답
- func makeASandwich() throws {
- // ...
- }
-
- do {
- //no error was thrown
- try makeASandwich()
- eatASandwich()
- } catch SandwichError.outOfCleanDishes {
- // error was thrown
- washDishes()
- } catch SandwichError.missingIngredients(let ingredients) {
- buyGroceries(ingredients)
- }
assertions and preconditions
이것은 error handling와 같이 잘못된 가정이라던가 잘못된 것을 올바르게 고치지는 못한다. 다만, 확일할 뿐이다.
주장은 개발 중에 실수나 잘못된 가정을 찾는 데 도움이 되고 전제 조건은 생산의 문제를 탐지하는 데 도움이 됩니다.
주장과 전제조건의 차이는 검사할 때 나타난다.
주장은 디버그 빌드에서만 확인되지만 전제 조건은 디버그 및 프로덕션 빌드에서 모두 확인됩니다.
생산 빌드에서는 주장 내부의 상태를 평가하지 않습니다. 즉, 프로덕션 성능에 영향을 주지 않으면서 개발 프로세스 중에 원하는 만큼 주장을 사용할 수 있습니다
assertions
false일 경우, 메세지를 전달함.
- 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.")
- }
preconditions
조건이 거짓일 수도 있지만, 반드시 참이어야 할때, 올바른 함수 값을 주었는가??
- // In the implementation of a subscript...
- precondition(index > 0, "Index must be greater than zero.")