일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- LiveData
- AWS
- elementAt
- CLASS
- vuex
- Service
- Interface
- map
- Kotlin
- Filter
- 생명주기
- docker
- union
- ConstraintLayout
- animation
- lifecycle
- mongoose
- ReactNative
- Generic
- enum
- function
- recyclerview
- react native
- class component
- Foreign Key
- list
- collection
- Swift
- docker-compose
- MINUS
- Today
- Total
개발 일기
기본적입 타입 소개 ? 본문
상수와 변수 :)
상수는 값을 설정한 뒤로는 변할수 없지만 변수는 값을 설정한 이후에도 변경이 가능합니다.
let maximumNumberOfLoginAttempts = 10 // 상수
var currentLoginAttempt = 0 // 변수
또는 한줄에 여러 상수 또는 변수 선언이 가능합니다.
var x = 0.0, y = 0.0, z = 0.0
타입 정의 :)
상수 또는 변수를 저장 할때 값의 종류를 명확하게 하고 싶은 경우에는 다음과 같이 사용 할수가 있습니다.
var welcomeMessage: String
동시의 한줄에 여러 상수 또는 변수 선언을 할려면 다음과 같이 할수 있습니다.
var red, green, blue: Double
상수 변수 이름 :)
상수 변수 이름에서는 거의 모든 문자가 포함이 가능합니다.
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"
하지만 그래도 안되는것이 몇가지가 있는데 일단 swift에서 지정한 키워드는 작동을 하지 않습니다.
할려면 방법은 있지만 안하시는게 좋습니다.
또는 공백 , 수학 기호 등등 몇가지 안되는 예외사항이 존재합니다.
주석 :)
아래와 같이 주석을 작성할수 있습니다.
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
세미콜론 :)
다른 언어에서는 세미콜론을 하는경우가 있는데 Swift는 써도 되고 안써도 상관없지만 한줄에 여러 줄을 표시할 때는 작성해야 합니다.
let cat = "🐱"; print(cat)
// Prints "🐱"
Swift 에서는 기존에 다른 언어들과 같이 여러 타입을 제공합니다.
-
Int , Uint , Double , Float
-
Boolean
-
Tuple
-
Collection Type
Optional :)
해당 변수에 nil일 수도 있고 값이 들어 있을수도 있을 수도 있어서 null 체크를 더 엄격하게 다룹니다.
[예시]
var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
위와 같이 ? 이라는 기호를 통해서 nil이 들어 갈수 있는 타입을 지정해줄수 있습니다.
강제로 풀고 싶은 경우에는 다음과 같이 하면 됩니다.
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!).")
}
그게 아니라 선택적으로 하고 싶으신 경우에는 다음과 같이 guard let or if let 을 사용하면 됩니다.
if let actualNumber = Int(possibleNumber) {
print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("The string \"\(possibleNumber)\" could not be converted to an integer")
}
예외 처리 :)
다른 언어와 비슷하게 이런 try catch문을 통해서 작성하실수 있습니다.
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
'컴퓨터 언어 > swift' 카테고리의 다른 글
Closures ? (0) | 2020.05.17 |
---|---|
Function ? (0) | 2020.05.16 |
Control Flow ? (0) | 2020.05.10 |
Collection Type ? (0) | 2020.05.03 |
Strings and Characters (0) | 2020.05.01 |