<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>ds-k.mo</title>
        <link>https://velog.io/</link>
        <description></description>
        <lastBuildDate>Sat, 07 May 2022 11:57:50 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>ds-k.mo</title>
            <url>https://velog.velcdn.com/images/ds-k/profile/0ecc77e1-bcd7-41b3-b741-88034496dc2b/image.JPG</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. ds-k.mo. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/ds-k" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[Swift] 재귀함수]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%9E%AC%EA%B7%80%ED%95%A8%EC%88%98</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%9E%AC%EA%B7%80%ED%95%A8%EC%88%98</guid>
            <pubDate>Sat, 07 May 2022 11:57:50 GMT</pubDate>
            <description><![CDATA[<h2 id="재귀함수">재귀함수</h2>
<ul>
<li>하나의 함수에서 자신을 다시 호출하여 작업을 수행하는 방식으로 문제를 푸는 방법</li>
<li>반복무능로 구현되는 알고리즘은 재귀함수로 표현할 수 있다.</li>
</ul>
<blockquote>
<p>작은 문제를 먼저 해결하고 큰 문제를 해결하는게 재귀적 아이디어의 핵심
재귀함수는 반드시 탈출조건(base case)이 있어야 한다.</p>
</blockquote>
<h3 id="팩토리얼-예제">팩토리얼 예제</h3>
<ul>
<li><p>반복문 예제</p>
<pre><code class="language-swift">func factorial (_ n : Int) -&gt; Int {
  var answer = 1
  for i in 2...n {
      answer = answer * i
  }
  return answer
}
// 1 * 2 &lt;-- answer에 할당
// 2(기존 answer) * 3 &lt;-- answer에 할당
// 6(기존 answer) * 4 &lt;-- answer에 할당
// ... 이런식으로 반복해서 곱해주는 형식</code></pre>
</li>
<li><p>재귀 예제</p>
<pre><code class="language-swift">func factorialR (_ n : Int) -&gt; Int {
  if n == 1 { return 1 }
  return n * factorialR(n - 1)
}
</code></pre>
</li>
</ul>
<p>// factorialR(3) 일 경우
// 3 * factorialR(2)
//     2 * factorialR(1)
//         1
// n == 1 이 탈출조건(base case)이기 때문에 1을 리턴하면서 마무리</p>
<pre><code>
### 피보나치 예제
* 반복문 예제
```swift
func fibonacci(_ n : Int) -&gt; Int {
    if n == 1 || n == 0 { return n }
    var answer = 0
    var (a, b) = (0, 1)
    for _ in 2...n {
        answer = a + b
        a = b
        b = answer
    }
    return answer
}</code></pre><ul>
<li>재귀함수 예제<pre><code class="language-swift">func fibonacciR(_ n : Int) -&gt; Int {
  if n == 1 || n == 0 { return n }
  return fibonacciR(n - 1) + fibonacciR(n - 2)
}</code></pre>
</li>
</ul>
<h3 id="최대공약수-예제">최대공약수 예제</h3>
<blockquote>
<p><strong>유클리드 호제법</strong>
a를 b로 나눈 나머지를 r이라고 할때 (단, a &gt; b) a와 b의 최대 공약수는 b와 r의 최대 공약수와 같다는 성질을 이용하는 방법
<img src="https://velog.velcdn.com/images/ds-k/post/79e905f1-8b10-4d57-89e3-1f5a6e917554/image.gif" alt=""></p>
</blockquote>
<ul>
<li><p>재귀함수 예제</p>
<pre><code class="language-swift">func gcdR(a:Int, b:Int) -&gt; Int {
  if a == b { return a }
  else if a &gt; b { //
      if a % b == 0 { return b }
      else { return gcdR(a: b, b: a % b) }

  } else {
      if b % a == 0{ return a }
      else { return gcdR(a: a, b: b % a) }
  }
}
gcdR(a: 12, b: 16)</code></pre>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 튜플(Tuple)의 활용]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%8A%9C%ED%94%8CTuple%EC%9D%98-%ED%99%9C%EC%9A%A9</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%8A%9C%ED%94%8CTuple%EC%9D%98-%ED%99%9C%EC%9A%A9</guid>
            <pubDate>Fri, 29 Apr 2022 12:05:34 GMT</pubDate>
            <description><![CDATA[<h2 id="intro">Intro</h2>
<blockquote>
<p>Swift의 데이터 타입을 공부하던 중, 기존에 알고 있던 언어(Javascript)에는 없는 자료형을 발견해서, &#39;신기하다... 배열이랑 비슷하네&#39; 정도의 소감을 가지고 익혔는데 문득, 실제 개발시 튜플을 활용하면 좋은 상황을 미리 알아두면 좋겠다 싶어서 추가적으로 알아보기로 했다.</p>
</blockquote>
<h2 id="튜플이란">튜플이란?</h2>
<h3 id="기본-모양">기본 모양</h3>
<pre><code class="language-swift">let 우리고양이 = (&quot;까까&quot;, &quot;Black&quot;, 7)</code></pre>
<p>튜플이란 <code>()</code>안에 여러가지 표현식이 들어가 있는 자료형을 말한다.
<code>()</code> 안에는 위의 예시처럼 여러가지 타입이 섞여 들어가도 관계가 없다.</p>
<pre><code class="language-swift">print(type(of: 우리고양이)) // (String, String, Int)</code></pre>
<p><code>.</code>을 통해 멤버에 접근할 수 있다.</p>
<pre><code class="language-swift">우리고양이.0 == &quot;고양이&quot;
우리고양이.1 == &quot;Black&quot;
우리고양이.2 == 7</code></pre>
<h3 id="튜플에-이름-넣어주기">튜플에 이름 넣어주기</h3>
<pre><code class="language-swift">let 우리고양이 = (name: &quot;까까&quot;, color: &quot;Black&quot;, age: 7)</code></pre>
<p>라벨로 이름을 붙일 수 있고, <code>.</code>뒤에 index가 아닌 라벨을 통해 접근 가능하다.</p>
<pre><code class="language-swift">kkakka.name == &quot;까까&quot;
kkakka.color == &quot;Black&quot;
kkakka.age == 7</code></pre>
<h3 id="구조-분해-할당">구조 분해 할당</h3>
<pre><code class="language-swift">let 우리고양이 = (name: &quot;까까&quot;, color: &quot;Black&quot;, age: 7)

let (name, color, age) = 우리고양이</code></pre>
<p>이런식으로 구조를 분해해서 할당할 수 있다. </p>
<h2 id="다양한-튜플의-활용법">다양한 튜플의 활용법</h2>
<blockquote>
<p>위에 적은 내용이 튜플의 기본적인 활용법인데, 사실 튜플 안에는 배열도 함수도 들어갈 수 있다. 튜플을 보다 다양하게 사용하는 예시를 살펴보자</p>
</blockquote>
<h3 id="switch-문의-활용">switch 문의 활용</h3>
<pre><code class="language-swift">let 해상도 = (3840.0, 2160.0)

func 해상도알려주는함수 (가로: Double, 세로: Double) -&gt; String {
    let 해상도 = (가로, 세로)
    switch 해상도 {
    case(3840...10000, _):
        return &quot;와이드모니터 같은데요?&quot;
    case (3840.0, 2160.0):
        return &quot;4k&quot;
    case (2560, 1440) :
        return &quot;QHD&quot;
    case (1920, 1080) :
        return &quot;FHD&quot;
    case let (x, y) where x == y:
        return &quot;정사각형 모니터...?&quot;
    case let (x, y) where x &lt; y:
        return &quot;가로랑 세로를 잘못 입력하신거 같아요&quot;
    default:
        return &quot;이상한데요?&quot;
    }
}

print(해상도알려주는함수(가로: 2160, 세로: 5000))
</code></pre>
<h3 id="배열-안의-튜플">배열 안의 튜플</h3>
<p>튜플을 활용하면, 더 다양한 타입의 데이터 타입을 한 배열에 넣을 수 있다.</p>
<pre><code class="language-swift">var catArr : [(name: String, age: Int)] = []

catArr.append((name : &quot;까까&quot;, age : 7))
catArr.append((name : &quot;루&quot;, age : 4))

print(catArr)

print(catArr[0].name) // 까까

for (index, element) in catArr.enumerated() {
    print(&quot;\(index + 1)번째 고양이는 \(element.name)이고, 나이는 \(element.age)살 입니다.&quot;)
}
/*
1번째 고양이는 까까이고, 나이는 7입니다.
2번째 고양이는 루이고, 나이는 4입니다.
*/</code></pre>
<p>간단한 유저 정보 등을 배열 속에 넣어서 관리할 때 유용하게 사용할 수 있을 것 같다.</p>
<h3 id="튜플-안에-배열">튜플 안에 배열</h3>
<pre><code class="language-swift">let 우리고양이 = (name: &quot;고양이&quot;, color: &quot;Black&quot;, age: 7, likes: [&quot;츄르&quot;, &quot;냉장고&quot;, &quot;캣폴&quot;])

print(우리고양이.likes) // [&quot;츄르&quot;, &quot;냉장고&quot;, &quot;캣폴&quot;]

for 좋아하는거 in 우리고양이.likes {
    print(좋아하는거)
}</code></pre>
<p>이처럼 튜플 안에 배열을 넣어서 디테일한 정보를 담을 수 있다.</p>
<h3 id="튜플-안에-함수">튜플 안에 함수</h3>
<pre><code class="language-swift">func getName () -&gt; String {
    return &quot;김대성&quot;
}

func getAge () -&gt; Int {
    return 99
}

let userInfo = (name : getName(), age : getAge())

print(userInfo.name, userInfo.age) // 김대성 99

func 주식계산기 (name: String, price: Double, amount: Double) -&gt; (name: String, value: Double) {
    return (name, price * amount)
}

let 삼성전자 = 주식계산기(name: &quot;삼성전자&quot;, price: 67400, amount: 50)
let 현대자동차 = 주식계산기(name: &quot;현대자동차&quot;, price: 186000, amount: 20)
let 네이버 = 주식계산기(name: &quot;네이버&quot;, price: 286500, amount: 10)

let 내주식 = (삼성전자, 현대자동차, 네이버)

print(&quot;\(내주식.0.name)을 \(내주식.0.value)만큼 들고 있습니다.&quot;)</code></pre>
<p>함수 값을 튜플에 담는 것 역시 가능하다.</p>
<h3 id="멀티-리턴-함수">멀티 리턴 함수</h3>
<pre><code class="language-swift">func calculateTip(billAmount: Double, tipPercent: Double) -&gt; (tipAmount: Double, totalAmount:Double) {
    let tip = billAmount * (tipPercent / 100)
    let total = billAmount + tip
    return (tipAmount: tip, totalAmount: total)
}

print(calculateTip(billAmount: 1000, tipPercent: 10))

let (tipAmount, totalAmount) = calculateTip(billAmount: 1000, tipPercent: 20)

print(tipAmount, totalAmount)</code></pre>
<p>멀티 리턴 함수를 만들어서 활용할 수 있다.
리턴되는 타입이 복잡할 경우 <code>typealias</code>를 통해 관리할 수 있다.</p>
<pre><code class="language-swift">typealias TipType = (tipAmount: Double, totalAmount:Double)

func calculateTip(billAmount: Double, tipPercent: Double) -&gt; TipType {
    let tip = billAmount * (tipPercent / 100)
    let total = billAmount + tip
    return (tipAmount: tip, totalAmount: total)
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 고차함수]]></title>
            <link>https://velog.io/@ds-k/Swift-%EA%B3%A0%EC%B0%A8%ED%95%A8%EC%88%98</link>
            <guid>https://velog.io/@ds-k/Swift-%EA%B3%A0%EC%B0%A8%ED%95%A8%EC%88%98</guid>
            <pubDate>Fri, 29 Apr 2022 05:57:03 GMT</pubDate>
            <description><![CDATA[<h3 id="-공부해보기">! 공부해보기</h3>
<blockquote>
<p><a href="http://minsone.github.io/mac/ios/swift-map-filter-reduce-and-inference">http://minsone.github.io/mac/ios/swift-map-filter-reduce-and-inference</a></p>
</blockquote>
<h3 id="고차함수">고차함수</h3>
<blockquote>
<p>다른 함수를 전달 인자로 받거나 함수 실행의 결과를 함수로 반환하는 함수</p>
</blockquote>
<h3 id="map-filter-reduce">map, filter, reduce</h3>
<pre><code class="language-swift">
// map
let numbers = [0,1,2,3]
let mapArray = numbers.map { (number) -&gt; Int in
    return number * 2
}
print(&quot;map \(mapArray)&quot;) // map [0, 2, 4, 6]

// filter
let intArray = [10,5,20,13,4]
let filterArray = intArray.filter{ $0 &gt; 5} // 클로져 간소화
print(&quot;filter \(filterArray)&quot;) // filter [10, 20, 13]

//reduce
let someArray = [1,2,3,4,5]
let reduceResult = someArray.reduce(0) {
    (acc: Int, cur: Int) -&gt; Int in
    print(&quot;\(acc) + \(cur)&quot;)
    return acc + cur
}
/*
 0 + 1
 1 + 2
 3 + 3
 6 + 4
 10 + 5
 */

print(&quot;reduce \(reduceResult)&quot;) // reduce 15</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 클로저 (Closures)]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%A1%9C%EC%A0%80-Closures</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%A1%9C%EC%A0%80-Closures</guid>
            <pubDate>Fri, 29 Apr 2022 05:56:24 GMT</pubDate>
            <description><![CDATA[<h3 id="클로저">클로저</h3>
<blockquote>
<p>코드에서 전달 및 사용할 수 있는 독립 기능 블록이며, 일급 객체의 역할을 할 수 있음</p>
</blockquote>
<h4 id="일급-객체">일급 객체?</h4>
<p>전달 인자로 보낼 수 있고, 변수/상수 등으로 저장하거나 전달할 수 있으며, 함수의 반환값이 될 수도 있다.</p>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">import UIKit

/*
 { (parameters) -&gt; return type in
     statements
 }
 */

let hello = { () -&gt; () in
    print(&quot;hello&quot;)
}

hello()

let hello2 = { (name: String) -&gt; String in
    return &quot;Hello, \(name)&quot;
}

//hello2(name: &quot;Daeseong&quot;) // Error : 전달인자 레이블을 적으면 오류 발생

hello2(&quot;Daeseong&quot;) // &quot;Hello, Daeseong&quot;

func doSomething(closure: () -&gt; ()) {
    closure()
}

doSomething(closure : { () -&gt; () in
    print(&quot;hello&quot;)
}) // &quot;hello&quot;

func doSomething2() -&gt; () -&gt; () {
    return { () -&gt; () in
        print(&quot;hello!&quot;)
    }
}

doSomething2()() // hello!


// Closure의 축약
func doSomething3(closure: (Int, Int, Int) -&gt; Int) {
    closure(1,2,3)
}

doSomething3(closure: {(a,b,c) in
    return a+b+c
})

doSomething3(closure : {
    return $0+$1+$2
})

doSomething3(closure : {
    return $0+$1+$2
})

doSomething3(closure : {
    $0+$1+$2
})

doSomething3(){
    $0+$1+$2
}

doSomething3 {
    $0+$1+$2
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] try-catch]]></title>
            <link>https://velog.io/@ds-k/Swift-try-catch</link>
            <guid>https://velog.io/@ds-k/Swift-try-catch</guid>
            <pubDate>Fri, 29 Apr 2022 05:55:36 GMT</pubDate>
            <description><![CDATA[<h3 id="에러-처리">에러 처리</h3>
<blockquote>
<p>프로그램 내에서 에러가 발생한 상황에 대해 대응하고 이를 복구하는 과정</p>
</blockquote>
<h3 id="swift-에러-처리">Swift 에러 처리</h3>
<blockquote>
<ol>
<li>발생(throwing)</li>
<li>감지(catching)</li>
<li>전파(propagating)</li>
<li>조작(manipulating)</li>
</ol>
</blockquote>
<p>4가지의 일급 클래스를 제공</p>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">enum PhoneError : Error {
case unknown
case batteryLow(batteryLevel: Int)
}

// 에러를 던져준다.
//throw PhoneError.batteryLow(batteryLevel: 20)
/*
 ▿ PhoneError
   ▿ batteryLow : 1 element
     - batteryLevel : 20
*/


func checkPhoneBatteryStatus(batteryLevel: Int) throws -&gt; String {
    guard batteryLevel != -1 else {throw PhoneError.unknown}
    guard batteryLevel &gt; 20 else { throw PhoneError.batteryLow(batteryLevel: 20)}
    return &quot;배터리 상태가 정상입니다.&quot;
}

/*
 do {
 try 오류 발생 가능 코드
 } catch 오류 패턴 {
  처리 코드
 }
*/

do {
    try checkPhoneBatteryStatus(batteryLevel: 20)
} catch PhoneError.unknown{
    print(&quot;알수 없는 에러입니다.&quot;)
} catch PhoneError.batteryLow(let batteryLevel){
    print(&quot;배터리 전원 부족! 남은 배터리 : \(batteryLevel)&quot;)
} catch {
    print(&quot;그 외 오류 발생 : \(error)&quot;)
}

let status = try? checkPhoneBatteryStatus(batteryLevel: 30)
//print(status) // nil (in batteryLevel : -1)
print(status) // Optional(&quot;배터리 상태가 정상입니다.&quot;) (in batteryLevel : 30)

let status2 = try! checkPhoneBatteryStatus(batteryLevel: 30)
// 에러가 절대로 발생하지 못하는 상황
print(status2) // &quot;배터리 상태가 정상입니다.&quot;</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 옵셔널 체이닝(Optional Chaining)]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%98%B5%EC%85%94%EB%84%90-%EC%B2%B4%EC%9D%B4%EB%8B%9DOptional-Chaining</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%98%B5%EC%85%94%EB%84%90-%EC%B2%B4%EC%9D%B4%EB%8B%9DOptional-Chaining</guid>
            <pubDate>Fri, 29 Apr 2022 05:55:07 GMT</pubDate>
            <description><![CDATA[<h3 id="옵셔널-체이닝optional-chaining">옵셔널 체이닝(Optional Chaining)</h3>
<blockquote>
<p>옵셔널에 속해있는 nil일지도 모르는 프로퍼티, 메서드, 서브스크립션에 질의(query)를 하는 과정</p>
</blockquote>
<p>-&gt; 만약 옵셔널이 프로퍼티나 메소드 혹은 서브스크립트에 대한 값을 갖고 있다면 그 값을 반환하고 만약 값이 nil이면 nil을 반환한다. 여러 질의를 연결해서 할 수도 있는데, 연결된 질의에서 어느 하나라도 nil이면 전체 결과는 nil이 된다.</p>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">import UIKit

struct Developer {
    var name:String
}

struct Company {
    let name : String
    var developer : Developer?
}

var developer = Developer(name: &quot;Daeseong&quot;)

var company = Company(name: &quot;DK&quot;, developer: developer)

print(company.developer) // nil
//print(company.developer.name) // Error: 옵셔널을 벗기지 않아서
print(company.developer?.name) // Optional(&quot;Daeseong&quot;)
print(company.developer!.name) // &quot;Daeseong&quot; , 강제 언래핑</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 열거형(Enum)]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%97%B4%EA%B1%B0%ED%98%95Enum</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%97%B4%EA%B1%B0%ED%98%95Enum</guid>
            <pubDate>Fri, 29 Apr 2022 05:54:38 GMT</pubDate>
            <description><![CDATA[<h3 id="열거형enumerations이란">열거형(Enumerations)이란</h3>
<blockquote>
<p>열거형은 관련된 값으로 이루어진 그룹을 공통의 형으로(type) 선언해 형 안전성(type-safety)을 보장하는 방법으로 코드를 다룰 수 있게 해준다.
<code>enum</code>키워드를 사용하여 선언</p>
</blockquote>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">enum CompassPoint {
    case north
    case south
    case east
    case west
}

var direction = CompassPoint.east
direction = .west // west

// Switch 구문과 함께 다양하게 활용할 수 있다.

switch direction {
case .north:
    print(&quot;north&quot;)

case .south:
    print(&quot;south&quot;)

case .east:
    print(&quot;east&quot;)

case .west:
    print(&quot;west&quot;)
}

// 원시형 값도 넣을 수 있다.
enum CompassPoint2 : String {
    case north = &quot;북&quot;
    case south = &quot;남&quot;
    case east = &quot;동&quot;
    case west = &quot;서&quot;
}

var direction2 = CompassPoint2.north
direction2 = .west

switch direction2 {
case .north:
    print(direction2.rawValue)

case .south:
    print(direction2.rawValue)

case .east:
    print(direction2.rawValue)

case .west:
    print(direction2.rawValue)
} // 서

// 원시값으로 열거형을 반환하게 할 수 있다.
let direction3 = CompassPoint2(rawValue: &quot;남&quot;) // south

// 열거형은 연관값도 가질 수 있다. (각 항목 옆에 소괄호로 표현)

enum PhoneError {
    case unknown
    case batteryLow(String) // 연관값의 타입을 소괄호에 표현
}

let error = PhoneError.batteryLow(&quot;배터리가 곧 방전됩니다.&quot;)

// 연관값의 추출 (Switch)


switch error {
case .batteryLow(let message):
    print(message)

case .unknown:
print(&quot;알 수 없는 에러입니다.&quot;)
} // &quot;배터리가 곧 방전됩니다.
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] Extension]]></title>
            <link>https://velog.io/@ds-k/Swift-Extension</link>
            <guid>https://velog.io/@ds-k/Swift-Extension</guid>
            <pubDate>Fri, 29 Apr 2022 05:54:03 GMT</pubDate>
            <description><![CDATA[<h3 id="익스텐션이-타입에-추가할-수-있는-기능">익스텐션이 타입에 추가할 수 있는 기능</h3>
<blockquote>
<p>익스텐션을 이용해 클래스, 구조체, 열거형 혹은 프로토콜 타입에 기능을 추가할 수 있다.</p>
</blockquote>
<ul>
<li>연산 타입 프로퍼티 / 연산 인스턴스 프로퍼티</li>
<li>타입 메서드 / 인스턴스 메서드</li>
<li>이니셜라이저</li>
<li>서브스크립트</li>
<li>중첩 타입</li>
<li>특정 프로토콜을 준수할 수 있도록 기능 추가</li>
</ul>
<blockquote>
<p>익스텐션은 타입에 새 기능을 추가할 수 있지만 오버라이드는(override)는 할 수 없다.</p>
</blockquote>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">extension Int {
    var isEven : Bool {
        return self % 2 == 0
    }
    var isOdd : Bool {
        return self % 2 == 1
    }
}

var number = 3
number.isEven // false
number.isOdd // true


extension String {
    func convertToInt () -&gt; Int? {
        return Int(self)
    }
}

var string = &quot;0&quot;

string.convertToInt() // 0 (Int type)</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 프로토콜(Protocol)]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%94%84%EB%A1%9C%ED%86%A0%EC%BD%9CProtocol</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%94%84%EB%A1%9C%ED%86%A0%EC%BD%9CProtocol</guid>
            <pubDate>Fri, 29 Apr 2022 05:53:20 GMT</pubDate>
            <description><![CDATA[<h3 id="프로토콜">프로토콜</h3>
<blockquote>
<p>특정 역할을 하기 위한 메서드, 프로퍼티, 기타 요구사항 등의 청사진</p>
</blockquote>
<ul>
<li>클래스, 구조체, 열거형 등이 정의한 요구사항을 준수하도록 요구한다.</li>
<li>프로토콜을 만족시키는 타입을 프로토콜을 따른다(conform)고 말한다.</li>
<li>프로토콜에 필수 구현을 추가하거나 추가적인 기능을 더하기 위해 프로토콜을 확장(extend)하는 것이 가능하다.</li>
</ul>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">protocol SomeProtocol {

}

protocol SomeProtocol2 {

}

struct SomeStructure : SomeProtocol, SomeProtocol2 {

}

class SomeSuperclass {

}

class SomeClass : SomeSuperclass, SomeProtocol, SomeProtocol2 {

}</code></pre>
<p>이와같이 프로토콜을 따르도록 한다.</p>
<pre><code class="language-swift">protocol FirstProtocol {
    var name : Int { get set }
    var age : Int { get } // 읽기 전용
}

protocol AnotherProtocol {
    static var someTypeProperty : Int { get set }
}

protocol FullyNames {
    var fullName : String { get set }
    func printFullName()
}

struct Person : FullyNames {
    var fullName : String
    func printFullName () {
        print(fullName)
    }
}

protocol SomeProtocol3 {
    func someTypeMethod()
}

protocol SomeProtocol4 {
    init(someParameter : Int)
}

protocol SomeProtocol5 {
    init()
}

class SomeClass : SomeProtocol5 {
    required init() { // class에서 생성자 요구사항을 채택하려면 required 키워드가 필요하다. struct는 x

    }
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] assert & guard]]></title>
            <link>https://velog.io/@ds-k/Swift-assert-guard</link>
            <guid>https://velog.io/@ds-k/Swift-assert-guard</guid>
            <pubDate>Fri, 29 Apr 2022 05:52:26 GMT</pubDate>
            <description><![CDATA[<h3 id="assert">assert</h3>
<ul>
<li>특정 조건을 체크하고, 조건이 성립되지 않으면 메세지를 출력하게 할 수 있는 함수</li>
<li>주로 디버깅 중 조건의 검증을 위하여 사용</li>
</ul>
<h3 id="guard">guard</h3>
<ul>
<li>조건문을 검사하여 그 다음에 오는 코드를 실행할지 말지 결정 하는 것</li>
<li>guard 문에 주어진 조건문이 <strong>거짓</strong>일때 구문이 실행됨 -&gt; 방어 코드로 많이 사용</li>
</ul>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">// assert

var value = 0
assert(value == 0)

value = 2
assert(value == 0, &quot;값이 0이 아닙니다.&quot;)
 Assertion failed: 값이 0이 아닙니다.


// guard
/*
 guard 조건 else {
  // 조건이 false면 else 구문이 실행되고
 return or throw or break를 통해 이후 코드를 실행하지 않도록 만든다.
 }
 */

func guardTest(value : Int) {
    guard value == 0 else {return} // value가 0이 아닐 경우 코드 종료
    print(&quot;안녕하세요&quot;)
}

guardTest(value: 0) // 안녕하세요
guardTest(value : 2) // 아무 일도 없었다..


func guardTest2(value : Int?) {
    guard let value = value else {return} // value가 0이 아닐 경우 코드 종료
    print(value)
}

guardTest2(value : 2) // 2
guardTest(value : nil) // 함수가 종료, </code></pre>
<blockquote>
<p>guard문을 활용하면 옵셔널 바인딩된 상수를 조건문 범위 바깥에서도 사용할 수 있다.</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 타입 캐스팅]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%83%80%EC%9E%85-%EC%BA%90%EC%8A%A4%ED%8C%85</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%83%80%EC%9E%85-%EC%BA%90%EC%8A%A4%ED%8C%85</guid>
            <pubDate>Fri, 29 Apr 2022 05:51:53 GMT</pubDate>
            <description><![CDATA[<h3 id="타입-캐스팅">타입 캐스팅</h3>
<blockquote>
<p>인스턴스의 타입을 확인하거나 어떠한 클래스의 인스턴스를 해당 클래스 계층 구조의 슈퍼 클래스나 서브 클래스로 취급하는 방법</p>
</blockquote>
<h3 id="서브-클래싱">서브 클래싱</h3>
<pre><code class="language-swift">class MediaItem {
    var name : String
    init(name: String) {
        self.name = name
    }
}</code></pre>
<p><code>MediaItem</code> 클래스를 서브클래싱 해서 두개의 다른 서브클래스를 만든다.</p>
<pre><code class="language-swift">class Moive : MediaItem {
    var director : String
    init(name: String, director:String){
        self.director = director
        super.init(name: name)
    }
}

class Song : MediaItem {
    var artist : String
    init(name: String, artist: String){
        self.artist = artist
        super.init(name: name)
    }
}
</code></pre>
<p><code>Movie</code>와 <code>Song</code> 클래스를 아이템으로 갖는 <code>library</code> 배열을 선언한다.</p>
<pre><code class="language-swift">let library = [
Movie(name: &quot;Casablanca&quot;, director: &quot;Michael Curtiz&quot;),
Song(name: &quot;Blue Suede Shoes&quot;, artist: &quot;Elvis Presley&quot;),
Movie(name: &quot;Citizen Kane&quot;, director: &quot;Orson Welles&quot;),
Song(name: &quot;The One And Only&quot;, artist: &quot;Chesney Hawkes&quot;),
Song(name: &quot;Never Gonna Give You Up&quot;, artist: &quot;Rick Astley&quot;)
]</code></pre>
<h3 id="형-확인-checking-type">형 확인 (Checking Type)</h3>
<p><code>is</code>연산자를 이용해 인스턴스의 타입을 확인 할 수 있다.</p>
<pre><code class="language-swift">var movieCount = 0
var songCount = 0

for item in library {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}

print (&quot;영화 갯수 : \(movieCount), 노래 갯수 : \(songCount)&quot;) // 영화 갯수 : 2, 노래 갯수 : 3</code></pre>
<h3 id="다운캐스팅-downcasting">다운캐스팅 (Downcasting)</h3>
<p>특정 클래스 타입의 상수나 변수는 특정 서브클래스의 인스턴스를 참조하고 있을 수 있다. 
<code>as?</code>와 <code>as!</code> 연산자를 통해 어떤 타입의 인스턴스인지 확인할 수 있다.
<code>as?</code> -&gt; 특정 타입이 맞는지 확신할 수 없을 때 사용
<code>as!</code> -&gt; 특정 타입이 맞는지 확신할 때 사용 (만약 지정한 타입이 아니라면 런타임 에러가 발생하니 주의)</p>
<pre><code class="language-swift">for item in library{
    if let movie = item as? Movie {
        print(&quot;영화 제목 : \(movie.name), 감독 : \(movie.director)&quot;)
    } else if let song = item as? Song {
        print(&quot;노래 제목 : \(song.name), 창작자 : \(song.artist)&quot;)
    }
}
/*
영화 제목 : Casablanca, 감독 : Michael Curtiz
노래 제목 : Blue Suede Shoes, 창작자 : Elvis Presley
영화 제목 : Citizen Kane, 감독 : Orson Welles
노래 제목 : The One And Only, 창작자 : Chesney Hawkes
노래 제목 : Never Gonna Give You Up, 창작자 : Rick Astley
*/
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 상속]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%83%81%EC%86%8D</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%83%81%EC%86%8D</guid>
            <pubDate>Fri, 29 Apr 2022 05:51:17 GMT</pubDate>
            <description><![CDATA[<h3 id="상속">상속</h3>
<blockquote>
<p>클래스가 다른 클래스로부터 프로퍼티나 메소드 등을 상속받는 것
상속받는 클래스 : 자식 클래스, 서브 클래스
상속하는 클래스 : 부모 클래스, 슈퍼 클래스</p>
</blockquote>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">// base class
class Vehicle {
    var currentSpeed = 0.0
    var description : String {
        return &quot;traveling at \(currentSpeed) miles per hour&quot;
    }
    func makeNoise(){
        print(&quot;부아앙아아아아앙&quot;)
    }
}

/*
 // sub class
 class 클래스 이름 : 부모클래스 이름 {
   // 하위 클래스 정의
 }
*/

class Bicycle : Vehicle {
    var hasBasket = false
}

var bicycle = Bicycle()

bicycle.currentSpeed = 15.0
bicycle.currentSpeed // 15
bicycle.makeNoise() // in Console : 부아앙아아아아앙

// 오버라이딩 : 서브클래스에서 슈퍼클래스의 기능을 자신만의 기능으로 바뀌는 것
// override 키워드를 사용

class Train : Vehicle {
    override func makeNoise() {
        super.makeNoise() // 슈퍼클래스에서 정의된 것부터 나오고 다음에 오버라이딩 된 특성이 나온다.
        print(&quot;추추~~&quot;)
    }
}

let train = Train()
train.makeNoise() // 부아앙아아아아앙, 추추~~

class Car : Vehicle {
    var gear = 1
    override var description : String {
        return super.description + &quot; in gear \(gear)&quot;
    }
}

let car = Car()
car.currentSpeed = 30.0
car.gear = 2
print(car.description) // traveling at 30.0 miles per hour in gear 2


class AutomaticCar: Car {
    override var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10) + 1
        }
    }
}

let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
print(&quot;AutomaticCar : \(automatic.description)&quot;)
// AutomaticCar : traveling at 35.0 miles per hour in gear 4
// 프로퍼티 옵저버 didSet으로 슈퍼클래스인 Car의 프로퍼티인 gear를 변경한다.


class SomeClass {
    // final 키워드를 사용하면 상속이 불가능해진다.
    final var something : 1
}
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 클래스와 구조체의 차이]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4%EC%9D%98-%EC%B0%A8%EC%9D%B4</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4%EC%9D%98-%EC%B0%A8%EC%9D%B4</guid>
            <pubDate>Fri, 29 Apr 2022 05:50:32 GMT</pubDate>
            <description><![CDATA[<h3 id="클래스와-구조체의-공통점">클래스와 구조체의 공통점</h3>
<ul>
<li>값을 저장할 프로퍼티를 선언할 수 있다.</li>
<li>함수적 기능을 하는 메서드를 선언할 수 있다.</li>
<li>내부값에 .을 사용하여 접근할 수 있다.</li>
<li>생성자를 사용해 초기 상태를 설정할 수 있다.</li>
<li>extension을 사용하여 기능을 확장할 수 있다.</li>
<li>Protocol을 채택하여 기능을 설정할 수 있다.</li>
</ul>
<h3 id="클래스와-구조체의-차이점">클래스와 구조체의 차이점</h3>
<ol>
<li>클래스</li>
</ol>
<ul>
<li>참조 타입</li>
<li>할당 또는 파라미터 전달 시에 객체를 가리키고 있는 메모리의 주소 값이 복사</li>
<li>Heap Memory에 저장되어 속도가 느리다.</li>
<li>상속이 가능</li>
</ul>
<ol start="2">
<li>구조체</li>
</ol>
<ul>
<li>값 타입</li>
<li>할당 또는 파라미터 전달 시 value copy가 일어남</li>
<li>Stack Memory에 저장되어 속도가 빠르다.</li>
<li>상속이 불가능</li>
</ul>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">class SomeClass {
    var count : Int = 0
}

var class1 = SomeClass()
var class2 = class1
var class3 = class1

class3.count = 2
class1.count // 2 , 참조 타입이기 때문에 복사본과 원본값이 같게 된다.

struct SomeStruct {
    var count : Int = 0
}

var struct1 = SomeStruct()
var struct2 = struct1
var struct3 = struct1

struct2.count = 2
struct3.count = 3

struct1.count // 0
struct2.count // 2
struct3.count // 3 , 값 타입이기 때문에 매번 새로운 메모리가 할당되어서 값을 변경해도 다른 구조체에 영향을 주지 않는다.</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 프로퍼티]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%94%84%EB%A1%9C%ED%8D%BC%ED%8B%B0</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%94%84%EB%A1%9C%ED%8D%BC%ED%8B%B0</guid>
            <pubDate>Fri, 29 Apr 2022 05:49:53 GMT</pubDate>
            <description><![CDATA[<h2 id="프로퍼티">프로퍼티</h2>
<blockquote>
<p>클래스, 구조체 또는 열거형 등에 관련된 값 -&gt; 인스턴스의 값</p>
</blockquote>
<h3 id="저장-프로퍼티-클래스-구조체">저장 프로퍼티 (클래스, 구조체)</h3>
<blockquote>
<p>클래스나 구조체에 저장된 값</p>
</blockquote>
<pre><code class="language-swift">/ in struct...
struct Pig {
    var name: String
    let gender:String
}

var pig = Pig(name: &quot;꿀꿀이&quot;, gender: &quot;수컷&quot;)

pig.name = &quot;멧돼지&quot;
// pig.gender = &quot;암컷&quot; // Error : gender가 상수로 선언

// 인스턴스 자체를 상수로 선언했을 때,
let pig2 = Pig(name: &quot;왕돼지&quot;, gender: &quot;수컷&quot;)
//pig.name = &quot;작은돼지&quot; // Error : 프로퍼티도 모두 상수로 되어서 에러 발생, 구조체는 value 타입이기 때문!

// in Class

class Cow {
    var name:String
    let gender:String

    init(name:String, gender: String) {
        self.name = name
        self.gender = gender
    }
}

let cow = Cow(name: &quot;물소&quot;, gender : &quot;수컷&quot;)
cow.name = &quot;황소&quot;
print(cow.name) // &quot;황소&quot; 에러가 나지 않는 이유 : Class는 참조 타입라서 가능하다.
</code></pre>
<h3 id="연산-프로퍼티-클래스-구조체-열거형">연산 프로퍼티 (클래스, 구조체, 열거형)</h3>
<blockquote>
<p>값을 직접적으로 저장하는 대신에, getter와 setter를 사용해서 다른 프로퍼티에 접근 가능</p>
</blockquote>
<pre><code class="language-swift">struct Stock {
    var averagePrice: Int
    var quantity: Int
    var purchasePrice : Int {
        get {
            return averagePrice * quantity
        }

        set(newPrice) {
            averagePrice = newPrice / quantity
        }
    }
}

var stock = Stock(averagePrice: 2300, quantity : 3)

stock.purchasePrice // 6900, 연산 프로퍼티에 접근하면 get 블록 안의 코드가 실행된다.
stock.purchasePrice = 3000
stock.averagePrice // 1000, 연산 프로퍼티의 값이 바뀌면 set 블록 안의 코드가 실행된다.</code></pre>
<h3 id="프로퍼티-옵저버">프로퍼티 옵저버</h3>
<pre><code class="language-swift">class Account {
    var credit : Int = 0 {
    // 소괄호로 이름 지정 가능 (default : newValue / oldValue)
        willSet {
            print(&quot;변경 예정 : \(newValue)&quot;)
        }
        didSet {
            print(&quot;변경 전 : \(oldValue)&quot;)
        }
    }
}

// willSet - 값이 저장되기 직전에 불리는 옵저버
// didSet - 값이 저장된 직후에 불리는 옵저버

var account = Account()
account.credit = 1000 // 변경 예정 : 1000 , 변경 전 : 0
</code></pre>
<h3 id="타입-프로퍼티">타입 프로퍼티</h3>
<pre><code class="language-swift">struct SomeStructure {
    static var storedTypeProperty = &quot;Some value.&quot;
    static var computedTypeProperty : Int {
        return 1
    }
}

SomeStructure.computedTypeProperty // 1
SomeStructure.storedTypeProperty // Some value.
SomeStructure.storedTypeProperty = &quot;Daeseong&quot;
SomeStructure.storedTypeProperty // Daeseong</code></pre>
<blockquote>
<p>변수에 클래스나 구조체를 할당해 인스턴스 없이도 값에 접근이 가능하다.</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 클래스]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4</guid>
            <pubDate>Fri, 29 Apr 2022 05:49:00 GMT</pubDate>
            <description><![CDATA[<h2 id="정의">정의</h2>
<p>다른 글에 정리되어 있습니다.</p>
<blockquote>
<p><a href="https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4">클래스와 구조체의 정의와 차이점</a></p>
</blockquote>
<h2 id="코드-예시">코드 예시</h2>
<pre><code class="language-swift">class 클래스 이름 {
 프로퍼티와 메서드
}</code></pre>
<blockquote>
<p>구조체와 거의 동일하다</p>
</blockquote>
<pre><code class="language-swift">class Cat {
    var name : String = &quot;&quot;
    var age: Int = 0

    init() {
        // 인스턴스가 생성되면 호출
    }

    func introduce() {
        print(&quot;name \(name) age : \(age)&quot;)
    }
}


var cat = Cat()
cat.name = &quot;kkakka&quot;
cat.age = 7
cat.introduce() // name kkakka age : 7</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 구조체]]></title>
            <link>https://velog.io/@ds-k/Swift-%EA%B5%AC%EC%A1%B0%EC%B2%B4</link>
            <guid>https://velog.io/@ds-k/Swift-%EA%B5%AC%EC%A1%B0%EC%B2%B4</guid>
            <pubDate>Fri, 29 Apr 2022 05:48:00 GMT</pubDate>
            <description><![CDATA[<h2 id="정의">정의</h2>
<p>다른 글에 정리되어 있습니다.</p>
<blockquote>
<p><a href="https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4">클래스와 구조체의 정의와 차이점</a></p>
</blockquote>
<h3 id="코드-예시">코드 예시</h3>
<pre><code class="language-swift">struct 구조체 이름 {
프로퍼티와 메소드
}</code></pre>
<blockquote>
<p>프로퍼티와 메소드를 묶어 멤버라고도 하며, 멤버 변수는 프로퍼티 멤버 함수는 메소드를 의미한다.</p>
</blockquote>
<pre><code class="language-swift">// 구조체나 클래스는 카멜케이스로 정의
struct User {
    var nickname: String
    var age: Int

    func information() {
        print(&quot;별명은 \(nickname)이고, 나이는 \(age)입니다.&quot;)
    }

}

// 인스턴스 생성 - 클래스나 구조체를 사용하기 위해서 메모리에 생성하는 것
// 클래스나 구조체의 실체

var user = User(nickname: &quot;Daeseong&quot;, age : 30)

user.nickname // &quot;Daeseong&quot;
user.nickname = &quot;DK&quot;
user.nickname // &quot;DK&quot;

user.information() // 별명은 DK이고, 나이는 30입니다.</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 클래스와 구조체]]></title>
            <link>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4</link>
            <guid>https://velog.io/@ds-k/Swift-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B5%AC%EC%A1%B0%EC%B2%B4</guid>
            <pubDate>Fri, 29 Apr 2022 05:47:22 GMT</pubDate>
            <description><![CDATA[<h2 id="클래스와-구조체">클래스와 구조체</h2>
<blockquote>
<p>프로그램의 코드를 추상화 하기 위해 사용
property와 method를 이용해 구조화된 데이터와 기능을 가질 수 있음</p>
</blockquote>
<h3 id="공통점">공통점</h3>
<ul>
<li>프로퍼티와 메소드를 사용하여 구조화된 데이터와 기능을 가짐</li>
<li>새로운 사용자 정의 타입을 만들어줌</li>
<li>초기화(Init)를 통해 초기 상태를 설정할 수 있음</li>
<li>확장할 수 있음</li>
<li>프로토콜 사용이 가능</li>
<li>특정 값에 접근할 수 있는 서브스크립트 문법 사용 가능</li>
</ul>
<h3 id="차이점">차이점</h3>
<ol>
<li>클래스</li>
</ol>
<ul>
<li>참조 타입</li>
<li>할당 또는 파라미터 전달 시에 객체를 가리키고 있는 메모리의 주소 값이 복사</li>
<li>Heap Memory에 저장되어 속도가 느리다.</li>
<li>상속이 가능</li>
</ul>
<ol start="2">
<li>구조체</li>
</ol>
<ul>
<li>값 타입</li>
<li>할당 또는 파라미터 전달 시 value copy가 일어남</li>
<li>Stack Memory에 저장되어 속도가 빠르다.</li>
<li>상속이 불가능</li>
</ul>
<h3 id="언제-구조체를-사용해야-할까">언제 구조체를 사용해야 할까?</h3>
<ul>
<li>연관된 값들의 집합을 캡슐화하는 것이 목적일 경우</li>
<li>캡슐화된 값을 참조하는 것보다 복사하는 것이 좋을 때</li>
<li>상속이 필요하지 않을때
등등...</li>
</ul>
<h3 id="초기화-init">초기화 init</h3>
<blockquote>
<p>클래스 구조체 또는 열거형의 인스턴스를 사용하기 위한 준비 과정</p>
</blockquote>
<pre><code class="language-swift">// init
/*
 init(매개변수: 타입, ...) {
    // 프로퍼티 초기화
    // 인스턴스 생성시 필요한 설정을 해주는 코드 작성
 }
 */


class Member {
    var nickname:String
    var age: Int

    init(nickname: String, age: Int) {
        self.nickname = nickname
        self.age = age
    }

    init(age: Int){
        self.nickname = &quot;self&quot;
        self.age = age
    }

    // 인스턴스가 메모리에서 해제될 때 실행, !! 클래스에서만 가능
    deinit {
        print(&quot;deinit member&quot;)
    }

}

var member = Member(nickname: &quot;DK&quot;, age: 30)
member.nickname // &quot;DK&quot;
member.age // 30

var member2 = Member(age: 50) // Member
member2.nickname // &quot;self&quot;
member2.age = 50

// member를 메모리에서 해제시키는 과정, member3가 nil이 될수 있으므로 옵셔널 타입으로 지정
var member3: Member? = Member(age:23)
member3 = nil // In console : deinit member
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 옵셔널]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%98%B5%EC%85%94%EB%84%90</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%98%B5%EC%85%94%EB%84%90</guid>
            <pubDate>Fri, 29 Apr 2022 05:46:55 GMT</pubDate>
            <description><![CDATA[<h2 id="옵셔널이란">옵셔널이란?</h2>
<blockquote>
<p>값이 있을 수도 있고 없을 수도 있다.</p>
</blockquote>
<h3 id="지정하는-방법">지정하는 방법</h3>
<p>변수의 타입을 설정할때 <code>?</code>키워드를 삽입하고, <code>nil</code>을 할당해준다.</p>
<pre><code class="language-swift">var number:Int? = nil
var name:String? = nil</code></pre>
<p>값이 없는 변수에 접근을 하면 다른 언어에서는 일반적으로 런타임 에러가 발생하지만, swift에서 옵셔널로 설정한 변수에는 접근해도 오류가 발생하지 않는다.</p>
<ul>
<li>옵셔널로 선언된 값의 형태<pre><code class="language-swift">var optionalName: String? = &quot;Daeseong&quot;
print(optionalName) // Optional(&quot;Daeseong&quot;)</code></pre>
<code>Optional(&quot;Daeseong&quot;)</code></li>
<li><blockquote>
<p>이처럼 바로 String이 아니라 Optional이라는 포장지에 둘러쌓인 형태로 나온다. 이 변수를 사용하기 위해서는 옵셔널 바인딩이라는 과정이 필요하다.</p>
</blockquote>
</li>
</ul>
<h3 id="옵셔널의-해제-방법">옵셔널의 해제 방법</h3>
<ol>
<li>명시적 해제</li>
</ol>
<ul>
<li>강제 해제</li>
<li>비강제 해제(<strong>옵셔널 바인딩</strong>)</li>
</ul>
<ol start="2">
<li>묵시적 해제</li>
</ol>
<ul>
<li>컴파일러에 의한 자동 해제</li>
<li>옵셔널의 묵시적 해제</li>
</ul>
<h4 id="명시적-해제---강제해제">명시적 해제 - 강제해제</h4>
<p>옵셔널 해제 연산자 <code>!</code>를 통해 해결할 수 있다.</p>
<pre><code class="language-swift">var number: Int? = 11
print(number) // Optional(11)
print(number!) // 11</code></pre>
<p>강제해제는 만약 값이 nil인 변수를 강제 해제할 경우 오류가 발생하게 되므로 위험하다.</p>
<h4 id="명시적-해제---옵셔널-바인딩">명시적 해제 - 옵셔널 바인딩</h4>
<p>if문과 guard문을 통해 바인딩 할 수 있다.</p>
<pre><code class="language-swift">var number: Int? = 3

// if 문
if let result = number {
    print(result)
} else {
    // 값 추출이 실패할 경우
} // 3

// guard 문
func test() {
    let number: Int? = 5
    guard let result = number else { return }
    print(result)
}

test() // 5</code></pre>
<h4 id="묵시적-해제---컴파일러에-의한-자동-해제">묵시적 해제 - 컴파일러에 의한 자동 해제</h4>
<p>비교연산자를 이용해서 다른 값이랑 비교하면 컴파일러가 자동으로 해제하게 된다.</p>
<pre><code class="language-swift">let value : Int? = 10

if value == 10 {
    print(&quot;value는 10이다&quot;)
} else {
    print(&quot;Nah..&quot;)
}</code></pre>
<h4 id="묵시적-해제---옵셔널의-묵시적-해제">묵시적 해제 - 옵셔널의 묵시적 해제</h4>
<pre><code class="language-swift">let string = &quot;12&quot;
var stringToInt: Int! = Int(string)
print(stringToInt) // Optional(12)
print(stringToInt + 1) // 13

// ? Case...
let string = &quot;12&quot;
var stringToInt: Int? = Int(string)
print(stringToInt)
print(stringToInt + 1) // Error : Value of optional type &#39;Int?&#39; must be unwrapped to a value of type &#39;Int&#39;
// 해제가 안되는 것을 볼 수 있다.</code></pre>
<p>string을 Int화시킬 때 string이 숫자가 아닌 경우
nil이 되기 때문에 Optional로 타입을 지정할 필요가 있음
이때 옵셔널 <code>?</code> 대신 <code>!</code>을 사용하면 옵셔널을 묵시적으로 해제한 상태로 사용할 수 있음.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 반복문]]></title>
            <link>https://velog.io/@ds-k/Swift-%EB%B0%98%EB%B3%B5%EB%AC%B8</link>
            <guid>https://velog.io/@ds-k/Swift-%EB%B0%98%EB%B3%B5%EB%AC%B8</guid>
            <pubDate>Fri, 29 Apr 2022 05:46:21 GMT</pubDate>
            <description><![CDATA[<h2 id="반복문">반복문</h2>
<blockquote>
<p>반복적으로 코드가 실행되게 만드는 구문
swift에서는 for-in, while, repeat-while의 세가지 구문이 있다.</p>
</blockquote>
<h3 id="for-in-문">for-in 문</h3>
<pre><code class="language-swift">for 루프상수 in 순회대상 {
    // 실행할 구문...
}</code></pre>
<pre><code class="language-swift">// 루프상수는 순회대상에 포함되는 아이템을 넘겨받는다
// 순회대상에는 Array, Dictionary, Set , 범위 데이터, 문자열과 같은 타입을 사용할 수 있다.

// 범위 데이터
for i in 1...4 {
    print(i)
}
//1,2,3,4

// 배열 상수
let array = [1,2,3,4,5]

for i in array {
    print(i)
}
//1,2,3,4,5</code></pre>
<h3 id="while-문">while 문</h3>
<pre><code class="language-swift"> while 조건식 {
  실행할 구문
 }</code></pre>
<pre><code class="language-swift">
var number = 5

while number &lt; 10 {
    number+=1
}

number // 10</code></pre>
<h3 id="repeat-while-문">repeat while 문</h3>
<pre><code class="language-swift"> repeat {
    실행할 구문
 } while 조건식</code></pre>
<pre><code class="language-swift">var x = 6

repeat {
    x+=2
} while x &lt; 5

print(x) // 8 , repeat...while문은 적어도 한번은 실행된다.</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Swift] 조건문]]></title>
            <link>https://velog.io/@ds-k/Swift-%EC%A1%B0%EA%B1%B4%EB%AC%B8</link>
            <guid>https://velog.io/@ds-k/Swift-%EC%A1%B0%EA%B1%B4%EB%AC%B8</guid>
            <pubDate>Fri, 29 Apr 2022 05:45:50 GMT</pubDate>
            <description><![CDATA[<h2 id="조건문">조건문</h2>
<blockquote>
<p>주어진 조건에 따라 다르게 동작하도록 하는 것
swift에는 if, switch, guard의 세가지 종류가 있음</p>
</blockquote>
<h3 id="if-문">if 문</h3>
<ul>
<li><p>사용법</p>
<pre><code class="language-swift">if 조건식 {
  실행할 구문
} else if 조건식 2 {
  조건식 2를 만족할 때 실행할 구문
} else {
  만족하지 않으면 해당 구문 실행
}
</code></pre>
<ul>
<li>예시<pre><code class="language-swift">func feedAnimal (animal : String) {
if animal == &quot;dog&quot; {
    print(&quot;강아지 사료주기&quot;)
} else if animal == &quot;cat&quot; {
    print(&quot;고양이 사료주기&quot;)
} else {
    print(&quot;해당하는 동물 사료가 없음&quot;)
}
}
</code></pre>
</li>
</ul>
</li>
</ul>
<p>feedAnimal(animal: &quot;cat&quot;) // 고양이 사료주기
feedAnimal(animal: &quot;pig&quot;) // 해당하는 동물 사료가 없음</p>
<pre><code>### switch 문    

* 사용법
```swift
switch 비교대상 {
case 패턴1:
    패턴1 일치할 때 실행되는 구문
case 패턴2, 패턴3
    패턴2, 3이 일치할 때 실행되는 구문
default :
    어느 비교 패턴과도 일치하지 않을 때 실행되는 구문
}</code></pre><ul>
<li>예시<pre><code class="language-swift">func findColor(color : String) {
  switch color {
  case &quot;blue&quot; :
      print(&quot;파란색입니다.&quot;)
  case &quot;green&quot; :
      print(&quot;초록색입니다.&quot;)
  case &quot;yellow&quot; :
      print(&quot;노란색입니다.&quot;)
  default :
      print(&quot;찾는 색상이 없습니다.&quot;)
  }
}
</code></pre>
</li>
</ul>
<p>findColor(color: &quot;blue&quot;) // 파란색입니다.
findColor(color: &quot;yellow&quot;) // 노란색입니다.</p>
<p>// 범위 지정 (...키워드(!!!!편리하다))
func getSeasons (temp : Int) -&gt; String {
    switch temp {
    case -20...9:
        return &quot;겨울 입니다.&quot;</p>
<pre><code>case 10...14:
    return &quot;가을 입니다.&quot;

case 15...25:
    return &quot;봄 입니다.&quot;

case 26...35:
    return &quot;여름 입니다.&quot;

default:
    return &quot;이상 기후입니다.&quot;
}</code></pre><p>}</p>
<p>getSeasons(temp: 20) // &quot;봄 입니다.&quot;
getSeasons(temp: 200) // &quot;이상 기후입니다.&quot;</p>
<pre><code></code></pre>]]></description>
        </item>
    </channel>
</rss>