###### tags: `study`
# 23.04.29 Optional
## 팀규칙
- 스터디 참여에 변동 사항이 있을 시 전날 미리 말해주기
- 스터디 전 실험실 유의사항 예습해오기(바로 실험 가능하게 준비해오기)
- 스터디 시간
| 시간 | 할 일 |
| :-----------: | :---: |
| 09:00 ~ 09:10 | 복습 리뷰 |
| 09:10 ~ 10:00 | 타임 1 |
| 10:00 ~ 10:10 | 브레이크타임 |
| 10:10 ~ 11:00 | 타임 2 |
| 11:00 ~ 11:10 | 브레이크타임 |
| 11:10 ~ 12:00 | 타임 3 |
## 참여자
| Hemg🐻 | hoon🤪 | [Serena🐷](https://github.com/serena0720) | 비모🤖 |
| -------- | -------- | -------- | ---- |
---
## Optional
### 실험 진행을 위해 알고 있어야 할 주요 개념
- 함수의 생성과 호출
- 함수의 전달인자(argument), 매개변수(parameter), 반환값(return)
- Swift 기본 자료형
- 비교 연산자
### 실험 1: 옵셔널 값을 사용해 봅시다.
```swift
var productsList: [String?] = ["볼펜", "텀블러", "다이어리", "에코백", "머그컵", "후드집업"]
```
### 실험 2: Optional을 활용한 경우 예외사항을 처리해 봅시다.
```swift
var budget: Int = 2000
var productsList: [String?] = ["볼펜", "텀블러", "다이어리", "에코백", "머그컵", "후드집업"]
func buy(productNumber: Int) {
// Todo
}
```
## 📚 참조링크
- [🍎Apple Docs: error handling](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/errorhandling)
- [🍎Apple Docs: optionalchaining](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/optionalchaining/)
- [🍎Apple Docs: Result](https://developer.apple.com/documentation/swift/result)
- [📘blog: result type](https://velog.io/@un1945/Swift-Result-Type)
# README
# :fire: 불타는 토요 스터디 9기 B반 :fire:
> 매주 토요일 오전 9시에 스터디를 진행합니다. 사전에 제공된 자료를 바탕으로 예습하고 토론합니다.
## 🍀 스터디원
|[Hemg🐻](https://github.com/hemg2)|[hoon🐶](https://github.com/Hoon94)|[Serena🐷](https://github.com/serena0720)|[비모🤖](https://github.com/bubblecocoa)|
|:-----:|:------:|:--------:|:----:|
|<Img src="https://avatars.githubusercontent.com/u/101572902?v=4" width="150"/>|<Img src="https://cdn.discordapp.com/avatars/353059967261081600/6c1f047a3c1a95ce042b29506d14e33c.webp?size=160" width="150"/>|<Img src = "https://i.imgur.com/q0XdY1F.jpg" width="150"/>|<img width="150" src="https://avatars.githubusercontent.com/u/67216784?v=4">|
---
## 팀규칙
- 스터디 참여에 변동 사항이 있을 시 전날 미리 말해주기
- 스터디 전 실험실 유의사항 예습해오기(바로 실험 가능하게 준비해오기)
- 스터디 시간
| 시간 | 할 일 |
| :-----------: | :---: |
| 09:00 ~ 09:10 | 복습 리뷰 |
| 09:10 ~ 10:00 | 타임 1 |
| 10:00 ~ 10:10 | 브레이크타임 |
| 10:10 ~ 11:00 | 타임 2 |
| 11:00 ~ 11:10 | 브레이크타임 |
| 11:10 ~ 12:00 | 타임 3 |
---
### 📅 2023.04.29 (토) Week#1
###### 👨👩👦👦 참여자 : Hemg, hoon, Serena, 비모
#### [금주 실험 주제🧑🏻🔬] **Optional** <br/>
[WIki URL](https://github.com/HongDaeroMoiSi-jo/weekendStudy/wiki/%5Bweek01%5D-Optional)
---
### 📅 2023.05.06 (토) Week#2
###### 👨👩👦 참여자 : Hemg, hoon, Serena, 비모
#### [금주 실험 주제🧑🏻🔬] **Type** <br/>
[WIki URL]()
---
# 1주차 토요스터디 / 주제: Optional / (23.04.29)
## 🎁 Optional Unwrapping
- If Statements and Forced Unwrapping
```swift
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!).")
}
```
- Optional Binding
```swift
if let <#constantName#> = <#someOptional#> {
<#statements#>
}
while let <#constantName#> = <#someOptional#> {
<#statements#>
}
guard let name = person["name"] else {
return
}
```
- Implicitly Unwrapped Optionals
```swift
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation point
```
- Optional Chaining
```swift
class Person {
var name: String
var job: Job?
init(name: String) {
self.name = name
}
}
class Job {
var jobName: String
var pay: Int
init(jobName: String) {
self.jobName = jobName
self.pay = 0
}
}
let hoon: Person? = Person(name: "hoon")
hoon?.job?.pay = 400000 // hoon.job은 nil이므로 실행되지 않음
print(hoon?.job?.pay) // -> nil
hoon?.job = Job(jobName: "developer")
hoon?.job?.pay = 400000
print(hoon?.job?.pay) // -> Optional(400000)
```
- nil-coalescing operator
```swift
var text:String?
var output = text ?? "Default value"
print(output) // Default value
text = "This is a string"
output = text ?? "Default String"
print(output) // This is a string
```
<br>
## 🔎 실험 1
<details>
<summary>예제 코드</summary>
<div markdown="1">
```swift
// Optional
var productsList: [String?] = ["볼펜", "텀블러", "다이어리", "에코백", "머그컵", "후드집업"]
// !
for (index, product) in productsList.enumerated() {
if product != nil {
print("\(index)번 상품은 \(product!)입니다.")
}
}
// Optional binding: if let
for (index, product) in productsList.enumerated() {
if let product {
print("\(index)번 상품은 \(product)입니다.")
}
}
// Optional binding: guard
for (index, product) in productsList.enumerated() {
guard let product else { continue }
print("\(index)번 상품은 \(product)입니다.")
}
// Optional pattern matching
for (index, product) in productsList.enumerated() {
if case let name? = product {
print("\(index)번 상품은 \(name)입니다.")
}
}
```
</div>
</details>
<br>
## 🔎 실험 2
<details>
<summary>예제 코드</summary>
<div markdown="1">
```swift
enum productError: Error {
case empty(Int)
case poor
}
var budget: Int = 2000
var productsList: [String?] = ["볼펜", "텀블러", "다이어리", "에코백", "머그컵", "후드집업"]
//do-catch
func buy(productNumber: Int) throws {
guard let product = productsList[productNumber] else { throw productError.empty(productNumber) }
guard budget >= 1000 else { throw productError.poor }
budget -= 1000
print("\(productsList[productNumber]!) 구매, 현재 잔고는 \(budget)")
productsList[productNumber] = nil
}
for index in [1, 2, 2, 3, 5] {
do {
try buy(productNumber: index)
} catch productError.empty(let index) {
print("\(index)번 상품이 없습니다.")
} catch productError.poor {
print("돈이 부족합니다.")
}
}
```
</div>
</details>
<details>
<summary>예제 코드</summary>
<div markdown="1">
```swift
enum productError: Error {
case empty(Int)
case poor
}
var budget: Int = 2000
var productsList: [String?] = ["볼펜", "텀블러", "다이어리", "에코백", "머그컵", "후드집업"]
//Result Type
func buy2(productNumber: Int) -> Result<String, productError> {
guard let product = productsList[productNumber] else { return .failure(.empty(productNumber)) }
guard budget >= 1000 else { return .failure(.poor) }
let productName: String = productsList[productNumber]!
budget -= 1000
productsList[productNumber] = nil
return .success(productName)
}
for index in [1, 2, 2, 3, 5] {
let a = buy2(productNumber: index)
switch a {
case .success(let name):
print("\(name) 구매")
case .failure(let error):
print(error)
// case .failure(let error(let x))
// print("aaaa", error)
}
}
```
</div>
</details>
## 📚 참조링크
- [🍎Apple Docs: error handling](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/errorhandling)
- [🍎Apple Docs: optionalchaining](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/optionalchaining/)
- [🍎Apple Docs: Result](https://developer.apple.com/documentation/swift/result)
- [📘blog: Result Type](https://velog.io/@un1945/Swift-Result-Type)