<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jinwoo Choi on Medium]]></title>
        <description><![CDATA[Stories by Jinwoo Choi on Medium]]></description>
        <link>https://medium.com/@JinwooChoi?source=rss-575d0599ddd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CiNNFIX3xcdzEAGG.jpg</url>
            <title>Stories by Jinwoo Choi on Medium</title>
            <link>https://medium.com/@JinwooChoi?source=rss-575d0599ddd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:56:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@JinwooChoi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reactive Programming으로 전화번호 인증 구현하기]]></title>
            <link>https://medium.com/@JinwooChoi/reactive-programming%EC%9C%BC%EB%A1%9C-%EC%A0%84%ED%99%94%EB%B2%88%ED%98%B8-%EC%9D%B8%EC%A6%9D-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-6670e835ad77?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6670e835ad77</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[reactivecocoa]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 11:35:50 GMT</pubDate>
            <atom:updated>2018-03-14T11:35:50.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyLjEXgdDViFQJarHsi7lw.jpeg" /></figure><h3>전화번호 인증</h3><p>수많은 모바일 애플리케이션들은 회원가입이 필요하다. 그중 대부분의 앱이 사용자 인증 기능을 제공한다. 중복 가입을 방지하거나 비밀번호를 변경할 때 이용 중인 사용자가 가입자와 동일인인지 확인해야 하기 때문이다. 모바일 애플리케이션은 대부분 전화번호가 있는 휴대폰에서 실행된다는 점을 이용해 전화번호로 사용자를 인증한다.</p><p>전화번호 인증은 전체 과정이 몇 개의 단계로 나누어지기 때문에 상태 관리가 필요하며 그에 따라 UI를 변경해야 한다. 또한, 인증 코드를 요청하고 사용자가 입력한 값을 서버에 전달하는 등, 비동기 이벤트에 대한 처리도 필요하다.</p><p>그러므로 전화번호 인증은 그 자체로 개발 스킬에 관한 글의 아주 좋은 소재가 될 수 있다. 이 글에서는 우선 전화번호 인증을 구현하는 일반적인 방식을 알아보고 Reactive 방식으로 개선해 봄으로써 Reactive Programming에 대한 이해를 넓혀 보고자 한다.</p><h3>전화번호 인증 중 UI 변화</h3><p>일반적인 전화번호 인증 과정은 다음 그림과 같다. 전화번호를 입력하고 서버에 인증번호를 요청하면 SMS를 통해서 인증번호를 전달받는다. 그 후, 전달받은 인증번호를 입력하고 서버에 인증 요청 후 결과를 전달받는다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOEtnAFE5I6BatRw0swIqA.png" /></figure><p>인증 과정 중에는 각 단계에 맞게 사용자 UI가 변경되어야 한다. 예를 들어, 입력값의 존재 여부에 따라서 관련 버튼이 활성화되어야 하고 인증 단계에 따라서 UI 컴포넌트가 표시되거나 숨겨져야 한다. 또, 상황에 맞게 Tip도 표시되어야 한다. 이 글에서는 유형별로 다음 3가지 처리만 다루어 보기로 한다.</p><ul><li>전화번호 입력이 시작될 때 [인증번호 받기] Button 활성화 처리 (1번 단계)</li><li>인증이 성공했을 때 [인증번호] TextField와 [인증하기] Button 숨기기 (4번 단계)</li><li>인증을 완료하거나 실패했을 때 관련 메시지 표시 (5번 단계)</li></ul><h3>기본구조 만들기</h3><p>전화번호 인증의 각 단계를 다음과 같이 5개의 상태로 나누어서 Enum을 정의했다. Swift 클래스의 프로퍼티로 정의한 후 didSet 옵저버에서 상태가 바뀌었을 때의 UI 변경을 할 수 있도록 하였다.</p><pre>enum PhoneNumberVerifyStep {<br>    case inputPhoneNumber, inputVerifyNumber, verifying, succeed, failed<br>}</pre><p>UI 컴포넌트는 다음과 같이 2개의 TextField, 2개의 Button, 하나의 Label로 구성하였다. 모두 InterfaceBuilder를 통해서 정의한 후 IBOutlet으로 연결하였다. 앞서 언급한 대로 verifyStep이라는 상태 저장용 클래스 프로퍼티를 만들고 UI 변경 처리를 위해 didSet 옵저버를 추가하였다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/430df5ce3a46e71602953ad9e3ce859f/href">https://medium.com/media/430df5ce3a46e71602953ad9e3ce859f/href</a></iframe><h3>인증 상태에 따라 UI 변경하기</h3><p>다음은 실제로 UI를 변경하는 부분이다. verifyStep의 변경된 값에 따라서 [인증번호] TextField와 [인증하기] Button의 isHidden 속성을 설정해주고 [Tip] Label의 텍스트를 변경해 준다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1d72ee2869728f6dcf8f4e39e74d352/href">https://medium.com/media/f1d72ee2869728f6dcf8f4e39e74d352/href</a></iframe><p>[인증하기] Button의 액션 메서드에서 관련된 Restful API를 호출한 후 수신한 결과에 따라서 verifyStep에 알맞은 값을 설정해 준다. <strong>didSet 옵저버를 이용해서 UI를 변경하기 때문에 UI 관련 코드와 데이터 처리 코드가 분리될 수 있는 장점</strong>이 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156128ba7e0c5cf1d3a07b46f47464ca/href">https://medium.com/media/156128ba7e0c5cf1d3a07b46f47464ca/href</a></iframe><p>[인증번호 요청] Button의 활성화 여부는 인증 상태가 아닌 [전화번호] TextField의 실시간 입력값에 따라서 달라져야 한다. 그러므로 phoneNumberTextField에 액션 핸들러를 추가해서 requestVerifyNumberButton의 isEnabled 속성을 설정해 주었다.</p><p>이렇게 해서 일반적인 방식으로 전화번호 인증 단계별 UI 변경 처리를 구현해 보았다. 최대한 Cocoa Touch와 Swift의 기능만을 사용하였는데, 이 글의 주제가 Reactive Programming의 소개이기 때문에 :-) 기존 방식의 단점을 몇 가지 찾아보고 새로운 방식으로 전환하는 단계로 넘어가 보도록 하겠다.</p><p>우선, <strong>verifyStep의 didSet 옵저버 내부 구현이 너무 커질 수 있다는 단점이 존재한다. </strong>하나의 View를 설정하는 코드가 Switch 문의 여러 case에 걸쳐서 존재하기 때문에 특정 View를 제거하거나 새로운 View를 추가하려면 여려 부분을 수정해 주어야 하는 불편함이 생기며 무엇보다 코드가 길어지면 알아보기 힘들다.</p><p>또한, TextField의 값에 따라서 Button의 상태를 바꿔야 하는 requestVerifyNumberButton의 isEnable 변경처리의 경우, <strong>비슷한 처리가 필요한 TextField와 Button이 많아질수록 텍스트 입력 핸들러가 계속 추가되어야 하는 불편함이 존재</strong>한다. 만약, TextField에 입력값에 대한 실시간 검증 로직이 추가되어야 하기라도 한다면 액션 핸들러 내부가 복잡해질 수도 있다.</p><p>이제 위의 구현을 Reactive Programming 방식으로 변경해 이런 단점들을 개선해 보자. 여기서는 오픈소스 라이브러리인 <a href="https://github.com/ReactiveCocoa/ReactiveCocoa"><strong>ReactiveCocoa</strong></a>를 사용해 보도록 한다.</p><h3>Reactive Programming에 대한 간단한 소개</h3><p>Reactive Programming은 모든 데이터의 흐름을 시간 순서에 따라 전달되는 스트림으로 보고 그에 반응하는 함수를 구현해서 프로그램을 구성하는 방식을 말한다. 다음의 참조 문과 같이 기본적인 개념은 새로운 것이 아니다. 버튼의 클릭 이벤트도 기본적으로 비동기 이벤트를 관찰하다가 콜백 메서드를 통해 전달받는 것이기 때문이다. 또한, Cocoa는 UI Event뿐만 아니라 데이터에 대해서도 Observer Pattern을 구현할 수 있는 여러 가지 도구들을 이미 제공하고 있기도 하다.</p><blockquote><a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754#reactive-programming-is-programming-with-asynchronous-data-streams"><strong>Reactive programming is programming with asynchronous data streams.</strong></a></blockquote><blockquote>In a way, this isn’t anything new. Event buses or your typical click events are really an asynchronous event stream, on which you can observe and do some side effects. Reactive is that idea on steroids. You are able to create data streams of anything, not just from click and hover events</blockquote><p>하지만 Reactive Programming은 앞서 얘기한 도구들을 필요한 곳에 사용하는 것에 그치지 않고 Observer Pattern을 프로그래밍의 핵심으로 활용하는 것까지 나아간다.</p><p>Cocoa가 제공하는 기본적인 도구인 UI Control Action, Notification, Delegate, KVO 등에서 다루는 모든 유형의 원시 데이터의 흐름을 스트림이라는 하나의 개념으로 추상화시키고 흘러 다니는 데이터를 가공하거나 필터링 할 수 있는 함수들을 제공해 다양한 부분에서 쉽게 활용할 수 있도록 한다.</p><p>다시 말해, 리액티브 프로그래밍은 기존 방식보다 더욱 통합적이고 쉽고 유연하게 상태 변경에 따른 <strong>연쇄 반응 처리</strong>를 처리할 방법을 제시하고 이를 기반으로 프로그래밍을 해나가는 것을 말한다.</p><p>기본적으로 함수형 코딩을 통해 스트림에 연결된 함수가 하나의 역할을 수행하는 것을 지향하는데 이를 통해 앞선 예제의 verifyStep didSet 옵저버와 같은 복잡한 Stateful 프로그램을 피할 수 있으며 비동기 처리의 에러 핸들링과 동시성 제어를 쉽게 할 수 있다는 장점도 있다. 자세한 내용은 <a href="http://reactivex.io/">ReactiveX.io</a>를 참조하길 바란다.</p><h3>Reactive Programming 방식으로 구현해 보기</h3><p>길고 지루한 이론 설명은 여기까지. 지금부터 오픈 소스 라이브러리인 ReactiveCocoa를 이용해 전화번호 인증 예제를 개선해 보도록 하자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14bcd947f66b72425056d70ddf9c76a3/href">https://medium.com/media/14bcd947f66b72425056d70ddf9c76a3/href</a></iframe><p>일단 앞선 예제 중 인증 단계에 따라 UI를 변경하기 위한 코드는 모두 제거하고 ViewController의 기본 뼈대만 남겼다. verifyStep의 didSet 옵저버, TextField의 editing 액션 핸들러, [인증하기] Button의 액션 메서드 등이 모두 제거되었다.</p><p>다음은 정리된 뼈대를 기반으로 ReactiveCocoa를 이용해 구현한 코드이다. 길지 않기 때문에 전체 코드를 첨부하였다. 우선 ReactiveSwift의 Property에 대해서 살펴보고, 앞선 예제와 같이 3가지 유형으로 나누어서 구현 방식을 살펴보도록 하겠다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d189287058f25cd9de3a656d7259ac9/href">https://medium.com/media/3d189287058f25cd9de3a656d7259ac9/href</a></iframe><h3>ReactiveSwift의 (Mutable) Property</h3><p>Property 는 ReactiveCocoa가 기반으로 하는 ReactiveSwift에서 제공되는 클래스인데, 데이터를 스트림으로 다룰 수 있는 기능을 제공한다. 예를들어 예제 코드의 verifyStep은 PhoneNumberVerifyStep 타입 변수의 Holder 역할을 하며, 값이 변경되었다는 Signal을 발생시키거나 다른 데이터 변경에 반응해 변경되도록 할 수 있다.</p><pre>var verifyStep = MutableProperty&lt;PhoneNumberVerifyStep(...)</pre><p>즉, Property(verifyStep)의 값이 변하면 UI를 변경시키거나 TextField의 입력값이 변경될 때 변수(verifyStep)의 값을 함께 변경시키는 작업을 할 수 있는 것이다. <strong>Swift 클래스 프로퍼티의 didSet 옵저버도 비슷한 기능을 제공하지만, MutableProperty는 앞서 설명한 것처럼 스트림을 통해 전달된 값에 대한 변경이나 필터링이 가능하고 훨씬 간결한 구문으로 UI 변경 코드로 연결될 수 있다는 장점이 있다.</strong></p><h3>ReactiveCocoa의 UI Binding과 &lt;~ 연산자</h3><p>ReactiveCocoa는 Property가 변경됨에 따른 UI 상태 변경을 쉽게 처리하기 위한 Binding 기능을 제공한다. UI 컴포넌트의 설정 가능한 속성마다 BindingTarget을 생성할 수 있게 하였는데, 이것은 일종의 Command pattern의 형태를 하고 있다.</p><p>예를 들어, ReactiveCocoa는 UILabel의 text 속성을 변경시키는 Command인 BindingTarget을 생성할 수 있도록 해두었다. BindingTarget은 Binding 되어있는 스트림으로부터 Signal이 발생하면 실행되는데, 전달받은 값을 UILabel의 text 속성으로 설정하는 처리를 한다.</p><p>Signal을 BindingTarget에 연결하는 처리를 간편하게 처리하기 위해 <strong>&lt;~</strong> 연산자가 제공된다. 예를 들어 아래의 코드는 textField의 값이 변경될 때마다 발생하는 Signal로부터 전달된 값(입력값)을 label의 텍스트로 설정하라는 의미가 된다.</p><pre>label.reactive.text &lt;~ textField.reactive.continuousTextValues</pre><p>label.reactive.text는 text를 변경시키는 <strong>BindingTarget</strong> 객체를 반환하고 textField.reactive.continuousTextValues는 입력값이 변경될 때마다 이벤트를 발생시키는 <strong>Signal</strong> 객체를 반환한다. <strong>BindingTarget</strong> 객체와 <strong>Signal</strong> 객체를 <strong>&lt;~</strong>를 통해서 <strong>Binding</strong> 하였고 그 결과 textField의 입력값이 변하면 label의 text가 변경되는 것이다.</p><p><strong>ReactiveCocoa의 UI Binding은 MVVM 설계를 구현하는 데 있어서 핵심적인 역할을 수행하는 중요한 개념이기도 하다. ViewModel의 프로퍼티와 View 내부의 UI 컴포넌트와의 바인딩을 통해서 데이터 처리 코드와 UI 처리 코드의 분리가 가능해지기 때문이다.</strong></p><h3>Reactive한 연쇄 반응 처리</h3><p>이제 다시 예제 코드로 돌아가서 Property와 UI Binding을 어떻게 사용하고 있는지 살펴보자. 우선 전화번호가 입력될 때 [인증번호 받기] Button이 활성화되는 처리부터 살펴보자. 여기서는 앞서 설명한 TextField의 continuousTextValues를 통해 생성된 입력값 변경 Signal을 구독할 것이다.</p><pre>requestVerifyNumberButton.reactive.<strong>isEnabled</strong> <strong>&lt;~</strong> <br>    phoneNumberTextField.reactive.<strong>continuousTextValues</strong><br>    .<strong>map { !($0?.isEmpty ?? true) }</strong></pre><p>requestVerifyNumberButton의 isEnabled BindingTarget을 phoneNumberTextField의 입력값 변경 Signal과 Binding 시켰고 그 과정에서 &lt;~ 연산자를 사용하였다.</p><p>Button의 isEnabled 속성은 Bool 타입의 속성인데 TextField의 입력값은 문자열 타입이므로 값을 직접 할당할 수는 없다. 그래서 Signal의 map 메서드를 사용해 문자열 값이 전달되면 유효성 여부를 나타내는 Bool 값으로 변경되도록 하였다. <strong>Reactive Programming의 핵심 장점인 스트림 데이터를 가공하기 쉽다는 점과 기존 방식 대비 짧고 간결하게 표현할 수 있다는 점이 드러난다.</strong></p><p>이제 기존방식 예제 중 가장 많은 부분을 차지하고 있는 verifyStep의 값에 따라 Button과 TextField, Label의 상태를 변경하는 처리를 살펴보자.</p><pre>var verifyStep = MutableProperty&lt;PhoneNumberVerifyStep&gt;(...)</pre><p>우선 verifyStep을 데이터 스트림으로 설정하고 값 변경 Signal을 구독할 수 있도록 MutableProperty로 선언하였다. 원시값을 직접 참조, 변경하기 위해서는 value 프로퍼티를 이용할 수 있다.</p><p>다음은 verifyStep의 Signal에 UI 컴포넌트를 바인딩한 모습이다. 마찬가지로 &lt;~ 연산자를 이용해 MutableProperty의 Signal과 Button과 TextField의 isHidden, Label의 text 변경을 수행하는 BindingTarget을 연결했다. 즉, verifyStep의 value가 바뀌면 그것에 맞게 isHidden, text 등의 UI 속성이 변경되도록 연결된 것이다.</p><pre>verifyNumberTextField.reactive.isHidden &lt;~ verifyStep<br>    .map { $0 == .succeed }</pre><pre>verifyButton.reactive.isHidden &lt;~ verifyStep.map { $0 == .succeed }</pre><pre>statusLabel.reactive.isHidden &lt;~ verifyStep.map { !$0.isVerifiedStep }</pre><pre>statusLabel.reactive.text &lt;~ verifyStep.signal<br>    .filter { $0.isVerifiedStep }.map { $0 == .succeed ? ... }</pre><p>Bool 타입 속성에 PhoneNumberVerifyStep이라는 Enum 값을 바인딩하기 위해서 <strong>map</strong>을 통해 상황에 맞는 값으로 변경해 주고 있으며, statusLabel의 텍스트는 .succeed 혹은 .failed 일때만 값을 설정하기 위해서 <strong>filter</strong> 메서드를 통해서 특정 상황일 때만 구독할 수 있도록 하고 있다.</p><p>여기까지 Reactive Programming을 적용해 전화번호 인증 처리 구현 중 데이터와 UI, UI 상호 간의 연쇄 반응 처리를 개선해 보았다. 이제 더이상 didSet 옵저버는 필요하지 않다. <strong>하나의 메서드에 변수의 값에 따른 UI 변경 처리가 모여있는 복잡한 코드는 사라졌다. 간결한 표현을 통해 하나의 UI 컴포넌트가 미래에 어떻게 변경될지를 정의할 수 있게 되었고 그로 인해 코드의 가독성이 좋아졌다. 또한, 특정 UI 컴포넌트를 추가하거나 삭제해야 할 때 변경해야 할 부분도 훨씬 적어졌다.</strong></p><p>이제 마지막으로 ReactiveCocoa를 통해서 UI Control Event를 처리하는 방식에 대해서 알아보자.</p><h3>ReactiveCocoa를 이용해 UI Control Event 처리하기</h3><p>ReactiveCocoa는 UI의 Control Event도 스트림으로 다룰 수 있는 방법을 제공한다. 앞서 알아보았던 TextField의 continuousTextValues와 같이 UI 컴포넌트에 Control Event에 대한 Signal 객체를 반환하는 프로퍼티를 추가해 두었다. UI Event에 대한 Signal을 BindingTarget과 Binding하거나 직접 Signal에 Observer를 추가할 수 있다.</p><pre>verifyButton.reactive.controlEvents(.touchUpInside).observeValues { <br>    self.api.getUsersVerify(...)<br>        .on(value: { _ in<br>            self.verifyStep.value = .succeed<br>        })<br>        .on(failed: { error in<br>            self.verifyStep.value = .failed<br>        })<br>}</pre><p>우리의 전화번호 인증 예제에서는 UI Event Signal에 직접 Observer를 추가하였다. 위 코드의 controlEvents 메서드는 touchUpInside 이벤트에 대한 Signal을 반환하고 observeValues 메서드를 통해 핸들러를 추가하였다.</p><p>Button을 터치하면 Label의 텍스트가 변경되는 것처럼 간단한 처리를 하려면 아래와 같이 &lt;~ 연산자를 통해 Binding 하면 된다.</p><pre>label.reactive.text &lt;~ button.reactive.controlEvents(.touchUpInside)<br>    .map { _ in &quot;hello&quot; }</pre><p>여기까지의 과정을 다시 한번 정리해 보자. <strong>UI Event 스트림을 구독 중 Signal이 발생하면 Remote API를 호출한다. 비동기 호출의 결과 처리 핸들러에서 전달된 값에 맞게 MutableProperty의 value를 변경한다. 동시에 MutableProperty의 스트림의 값 변경 Signal이 발생하고 그에 Binding 되어있는 UI가 변경되는 형태로 프로그램 상태 변경에 대한 연쇄 반응 처리는 이루어진다. </strong>스트림 구독과 UI 바인딩으로 대부분의 처리를 했다는 점에서 어느 정도 Reactive Programming의 정의에 부합하게 전화번호 인증 예제가 변경되었다고 볼 수 있을 것 같다.</p><h3>결론</h3><p>이것으로 전통적인 방식의 전화번호 인증 구현을 Reactive 방식으로 변경해 보았다. Reactive Programming은 그 자체는 새로운 개념이 아니다. 이미 Swift와 Cocoa는 비동기 처리나 UI Event 핸들링, Observer Pattern 구현을 할 수 있는 많은 도구를 제공한다. 하지만 Reactive 방식을 사용하는 것은 기존 방식보다 더 세련되고 간결하게 코드를 표현할 수 있고 MVVM 같은 프로그램 구조 설계에도 이용할 수 있는 장점이 있다.</p><p><strong>프로그래밍 세계에서 모든 것은 얼마나 적은 코드를 이해하기 쉽게 표현하느냐와 관련이 있다. 얼마나 편하게 유지보수 할 수 있는지가 매우 중요한 요소이기 때문이다. 그런 면에서 Reactive 방식을 도입하는 것은 아주 효과적인 결정이라고 할 수 있다. </strong>비록 처음 사용해 볼 때는 다소 어려운 것은 사실이긴 하지만 어느 정도 익숙해지면 기존 방식보다 훨씬 간결하게 코딩할 수 있고 편하게 UI와 사용자 로직을 구현할 수 있다고 확신한다.</p><p>이 글의 예제인 전화번호 인증의 기존 방식 구현에서 제시했던 단점은 Reactive 방식을 통해 아래와 같은 장점을 가지도록 변경되었다. 다시 한번 정리해 보면서 마무리해보도록 하자.</p><ul><li>특정 데이터나 UI 컴포넌트의 변경에 반응하는 코드가 간결해 진다.</li><li>UI를 변경하는 코드가 집중된 비대한 메서드를 만들지 않아도 되기 때문에 새로운 상태에 대응하거나 UI 컴포넌트를 추가하거나 삭제하기 쉬워 진다.</li><li>함수형 코딩을 통해서 상황과 역할에 집중할 수 있는 코드를 작성할 수 있다.</li><li>Observing과 Binding을 이용하면 ViewController를 ViewModel과 View로 분리할 수 있고 이는 MVVM 설계를 적용하는데 핵심 요소가 된다.</li></ul><p>Reactive Programming을 잘 활용해서 더 많은 개발자가 행복한 코딩을 할 수 있기를 바라며 이만 줄입니다. 긴 글 읽어 주셔서 감사합니다.</p><p>Swift를 이용한 iOS 애플리케이션 개발에 대한 글을 쓰고 있습니다. 아래의 글들도 관심 가지고 읽어봐 주시면 감사하겠습니다.</p><ul><li><a href="https://medium.com/@JinwooChoi/reactiveswift%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%B4-promise-%EA%B5%AC%EB%AC%B8-%EB%94%B0%EB%9D%BC%ED%95%98%EA%B8%B0-7a20bcb441f0">ReactiveSwift를 이용해 Promise 구문 따라하기</a></li><li><a href="https://medium.com/@JinwooChoi/swift%EC%97%90%EC%84%9C-%EC%97%B4%EA%B1%B0%ED%98%95-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0-aaf69148e08d">Swift에서 열거형 활용하기</a></li><li><a href="https://medium.com/@JinwooChoi/swift-codable%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-restful-api-%ED%98%B8%EC%B6%9C-21de0fffa84a">Swift codable을 이용한 restful api 호출</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6670e835ad77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phone Number Authentication with Reactive Programming]]></title>
            <link>https://medium.com/free-code-camp/phone-number-authentication-with-reactive-programming-6e89a2a651d2?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e89a2a651d2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 11:28:11 GMT</pubDate>
            <atom:updated>2018-03-21T07:14:14.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyLjEXgdDViFQJarHsi7lw.jpeg" /></figure><h3>Phone Number Authentication</h3><p>Many mobile applications require membership. Most of them provide user authentication. This is because you need to check whether the user in use is the same as the subscriber when preventing duplicate subscriptions or changing passwords.</p><p>Most mobile applications use a phone number to authenticate users, since they run on mobile phones. Phone number authentication consists of several steps, which means state management is required. You must also change the UI accordingly. This also requires asynchronous event handling, such as requesting a verification code and passing user-entered code to the server.</p><p>Therefore, phone number authentication can be a very good topic for writing about development skills. In this article, I will first implement phone number authentication in the usual way. Then I will introduce Reactive Programming.</p><h3>UI flow of Phone Number Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOEtnAFE5I6BatRw0swIqA.png" /></figure><p>During the authentication process, you must change the user interface for each step. For example, the related Button should be activated depending on the presence of the input value. And the UI component should be displayed or hidden according to the authentication step. Also, the Tip should be displayed to suit the situation. This article focuses on the following three cases.</p><ul><li>Activate [Request verification code] Button when entering a phone number (Step 1)</li><li>Hide [Verification code] TextField and [Authenticate] Button when authentication is successful (Step 4)</li><li>Display related message (tip) when authentication is completed or failed (step 5)</li></ul><h3>Basic structure</h3><p>First, we’ll define an Enum with five states for each authentication step as follows. We declare it as a property of the Swift class and it has a didSet observer. We’ll add the code that changes the UI according to the authentication step here.</p><pre>enum PhoneNumberVerifyStep {<br>    case inputPhoneNumber, inputVerifyNumber, verifying, succeed, failed<br>}</pre><p>UI components consist of two TextFields, two Buttons, and one Label as follows. All are created through InterfaceBuilder and connected to IBOutlet. As mentioned earlier, we’ve declare a class property for storing the authentication step named verifyStep, and we’ve added a didSet observer to handle UI changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/430df5ce3a46e71602953ad9e3ce859f/href">https://medium.com/media/430df5ce3a46e71602953ad9e3ce859f/href</a></iframe><h3>Change UI based on authentication step</h3><p>Here is the part that actually changes the UI. Set the isHidden property of the [Verification code] TextField and the [Authentication] Button according to the changed value of <strong>verifyStep</strong>, and change the text of the [Tip] Label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1d72ee2869728f6dcf8f4e39e74d352/href">https://medium.com/media/f1d72ee2869728f6dcf8f4e39e74d352/href</a></iframe><p>After calling the Restful API from the [Authentication] Button’s action method, set the appropriate value for <strong>verifyStep</strong> according to the response. <strong>Since we used the didSet observer for changing the UI, there is an advantage to separating the UI code and data processing code.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156128ba7e0c5cf1d3a07b46f47464ca/href">https://medium.com/media/156128ba7e0c5cf1d3a07b46f47464ca/href</a></iframe><p>Whether the [Request verification code] Button is active depends on the real-time input value of the [Phone number] TextField, not the authentication step. Therefore, we add an action handler to <strong>phoneNumberTextField</strong> that sets the <strong>isEnabled</strong> of <strong>requestVerifyNumberButton</strong> according to the input value.</p><p>In this way, we’ve implemented the UI changes according to the phone number authentication step in the usual way. Now, after looking at some of the disadvantages of the old method, I will modify the example and do it in the Reactive way, which is the subject of this article.</p><p>First, <strong>the internal implementation of the didSet observer in verifyStep may be too large</strong>. And the code that sets up one View can exist across multiple cases in the Switch statement. Many parts need to be modified to remove a specific View or add a new View. Above all, it is hard to read if the code gets longer.</p><p>Changing the enable property of the Button according to the input value of TextField can be inconvenient: <strong>the text input event handler should be added continuously if the number of the TextField and Button that need similar processing is increased</strong>. If you need to add real-time validation logic to the input value in the TextField, the inside of the event handler can be complicated.</p><p>Now, let’s improve these shortcomings by applying Reactive Programming. Here we use the open source library <a href="https://github.com/ReactiveCocoa/ReactiveCocoa"><strong>ReactiveCocoa</strong></a>.</p><h3>Reactive Programming</h3><p>Reactive Programming is the process of constructing a program using a function that responds to the stream of data in a time-sequential manner. The basic concept is not new — consider the following use cases. For example, the Button’s click event is basically observing asynchronous events and subscribing through callbacks. In addition, Cocoa has already provided a number of tools to implement Observer Patterns for data as well as UI Events.</p><blockquote><a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754#reactive-programming-is-programming-with-asynchronous-data-streams"><strong>Reactive programming is programming with asynchronous data streams.</strong></a></blockquote><blockquote>In a way, this isn’t anything new. Event buses or your typical click events are really an asynchronous event stream, on which you can observe and do some side effects. Reactive is that idea on steroids. You are able to create data streams of anything, not just from click and hover events</blockquote><p>However, Reactive Programming goes beyond just using the tools mentioned above, to the use of Observer Pattern as the core of programming.</p><p>It abstracts the flow of all types of primitive data handled by the UI — Control Action, Notification, Delegate, and KVO, which are basic tools provided by Cocoa, as a stream. It also provides functions to process and filter the data flowing through it, which can be easily used in various areas.</p><p>In other words, reactive programming is a <strong>more integrated and easier way to handle chain reaction processing (and programming based on it) due to state changes</strong> than traditional methods.</p><p>Basically, its function-oriented coding aims to perform a single role in a function connected to a stream. This avoids complicated stateful programs such as the verifyStep didSet observer of the previous example, and makes it easy to handle error handling and concurrency control of asynchronous processing. See <a href="http://reactivex.io/">ReactiveX.io</a> for more information.</p><h3>Implement Reactive Programming</h3><p>Ok, it’s time to stop explaining long, boring theories. From now on, let’s improve the phone number authentication example using the open source library ReactiveCocoa.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14bcd947f66b72425056d70ddf9c76a3/href">https://medium.com/media/14bcd947f66b72425056d70ddf9c76a3/href</a></iframe><p>First of all, we remove the code that changes the UI according to the authentication step of the previous example, and only the basic skeleton of ViewController is left. We also remove the didSet observer for verifyStep, the editing action handler for the TextField, and the action method for the [Authenticate] Button.</p><p>Implement the following code using ReactiveCocoa based on the skeleton. The entire code was attached because it was not long. Let’s first look at <strong>Property</strong> of ReactiveSwift, and let’s look at the implementation by dividing the authentication step process into three types as shown in the previous example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d189287058f25cd9de3a656d7259ac9/href">https://medium.com/media/3d189287058f25cd9de3a656d7259ac9/href</a></iframe><h3>(Mutable) Property of ReactiveSwift</h3><p>Property is a class provided by ReactiveSwift, which is the base of ReactiveCocoa. It provides the ability to handle data as a stream. For example, in the example code, <strong>verifyStep</strong> is a Holder for PhoneNumberVerifyStep type data. It can generate a signal when changing the value, or change the value in response to other data changes.</p><pre>var verifyStep = MutableProperty&lt;PhoneNumberVerifyStep(...)</pre><p>That is, when the value of Property (verifyStep) changes, the UI can be changed. Or when the input value of TextField is changed, the value of variable (verifyStep) can be changed with it.<strong> The didSet observer of the Swift class property provides similar functionality. </strong>However, MutableProperty has the advantage of being able to<strong> change or filter the values ​​passed through the stream</strong> as described above,<strong> </strong>and to<strong> connect with the UI change code much more concisely.</strong></p><h3>UI Binding and &lt;~ operator of ReactiveCocoa</h3><p>ReactiveCocoa provides Binding to easily handle UI changes due to Property changes. The UI component can create a BindingTarget for each of its configurable attributes. And this has a form of Command Pattern.</p><p>For example, ReactiveCocoa provides BindingTarget, which is the command that changes UILabel’s text. The BindingTarget is executed when a Signal is generated from the stream and sets the received value to the text of the UILabel.</p><p>The &lt;~ operator is provided to make it easier to connect the Signal to the BindingTarget. For example, the code below sets the value (input value) passed from the Signal (that is generated when the value of textField changes) to the text of the label.</p><pre>label.reactive.text &lt;~ textField.reactive.continuousTextValues</pre><p><strong>label.reactive.text</strong> returns a <strong>BindingTarget</strong> instance that changes the text, and <strong>textField.reactive.continuousTextValues</strong> ​​returns a <strong>Signal</strong> instance that raises an event when the input value changes. The <strong>BindingTarget</strong> instance and the <strong>Signal</strong> instance are bound through <strong>&lt;~</strong>, so when the input value of the textField changes, the text of the label changes with it.</p><p>ReactiveCocoa’s UI Binding is also an important concept playing a key role in implementing the MVVM design. This is because it is possible to separate the data processing code from the UI processing code by binding the properties of the ViewModel with the UI components in the View.</p><h3>Reactive Chain Reaction</h3><p>Now go back to the example code and see how the Property and UI Binding are being used. Let’s start with the process of activating the [Request verification code] Button when a phone number is entered. The Button’s BindingTarget subscribes to the input value change Signal generated by the continuousTextValues ​​of the TextField described above.</p><pre>requestVerifyNumberButton.reactive.<strong>isEnabled</strong> <strong>&lt;~</strong> <br>    phoneNumberTextField.reactive.<strong>continuousTextValues</strong><br>    .<strong>map { !($0?.isEmpty ?? true) }</strong></pre><p>The isEnabled BindingTarget of requestVerifyNumberButton was bound to the input value change Signal of phoneNumberTextField and the &lt;~ operator was used in the process.</p><p>The isEnabled property of the Button is a Bool type property. The input value of TextField is a string type, so the value can not be directly assigned.</p><p>Therefore, when the string value is passed, it is changed to a Bool type through Signal’s map method.<strong> </strong>It is clear that<strong> stream data, </strong>which is a key advantage of Reactive Programming<strong>, is easy to process and can be expressed in a short and concise manner.</strong></p><p>Let’s take a look at the state change of Button, TextField, and Label depending on the value of verifyStep which occupies the greater part of the example.</p><pre>var verifyStep = MutableProperty&lt;PhoneNumberVerifyStep&gt;(...)</pre><p>First, verifyStep is declared as a MutableProperty. verifyStep can now serve as a data stream, and UI Components can subscribe to a value change Signal from it. The value property returns the primitive value of verifyStep.</p><p>The following is UI Component Bindings to the Signal of verifyStep. Similarly, the &lt;~ operator connects the BindingTarget that changes the isHidden and text properties of the UI Components with the Signal from verifyStep. That is, if the value of verifyStep is changed, the UI attributes such as isHidden and text are changed accordingly.</p><pre>verifyNumberTextField.reactive.isHidden &lt;~ verifyStep<br>    .map { $0 == .succeed }</pre><pre>verifyButton.reactive.isHidden &lt;~ verifyStep.map { $0 == .succeed }</pre><pre>statusLabel.reactive.isHidden &lt;~ verifyStep.map { !$0.isVerifiedStep }</pre><pre>statusLabel.reactive.text &lt;~ verifyStep.signal<br>    .filter { $0.isVerifiedStep }.map { $0 == .succeed ? ... }</pre><p>Use the <strong>map</strong> method to bind the Enum type value called PhoneNumberVerifyStep to the Bool type property. Use the <strong>filter</strong> method to ensure that the text in the statusLabel changes only when verifyStep is .succeed or .failed.</p><p>Up to this point, the chain reaction between data and UI has been improved in a reactive way during the implementation of Phone Number Authentication. No more didSet observers are needed. <strong>Complex UI change methods have also disappeared.</strong></p><p>The Reactive approach allows us to define how a single UI component will change in the future with a concise representation. It also improves the readability of the code. Also, there are fewer things to change when adding or removing UI components.</p><p>Finally, let’s look at how to handle the UI Control Event through ReactiveCocoa.</p><h3>Handling UI Control Events with ReactiveCocoa</h3><p>ReactiveCocoa also provides a way to handle UI control events as streams. Like the continuousTextValues ​​of the TextField we saw earlier, ReactiveCocoa has added a property that returns a Signal instance for the control event of the UI component. The Signal for the UI Event can be bound to the BindingTarget, or it can have an observer directly.</p><pre>verifyButton.reactive.controlEvents(.touchUpInside).observeValues { <br>    self.api.getUsersVerify(...)<br>        .on(value: { _ in<br>            self.verifyStep.value = .succeed<br>        })<br>        .on(failed: { error in<br>            self.verifyStep.value = .failed<br>        })<br>}</pre><p>In the example, we added the Observer directly to the UI Event Signal. The controlEvents method returned a Signal for the touchUpInside event, and the observer handler was added via the observeValues ​​method.</p><p>The simple process of changing the Label’s text when the Button is touched is possible by binding through the &lt;~ operator.</p><pre>label.reactive.text &lt;~ button.reactive.controlEvents(.touchUpInside)<br>    .map { _ in &quot;hello&quot; }</pre><p>Let’s recap the process so far. If a signal occurs while subscribing to a stream of the UI Event, it calls the Remote API. Change the value of MutableProperty according to the value passed to the response handler of the asynchronous call. At the same time, a value change signal is generated from the stream of MutableProperty, and the UI that is bound to the change signal is changed.</p><p>Now we’ve changed the Phone Number Authentication example to conform to the definition of Reactive Programming. Most of the processing is done with stream subscription and UI binding.</p><h3>Conclusion</h3><p>We have changed the traditional Phone Number Authentication to use Reactive programming. It’s not a new concept — Swift and Cocoa already provide many tools for asynchronous processing, UI event handling, and observer pattern implementation. However, using the Reactive way is more elegant and concise than the classic way. Also, there is an advantage that it can be used to design program structure like MVVM.</p><p>Everything in the programming world is related to <strong>how well we understand the code. </strong>It is important that it is easy it is to maintain. In this respect, adopting the reactive approach is a very smart decision. It is true that it is rather difficult to use for the first time. However, I am convinced that if you get used to it, you can code much more succinctly than before, and easily implement UI and user logic.</p><p>Let’s look again at the advantages of Reactive programming:</p><ul><li>The code that responds to changes in specific data or UI components is simplified.</li><li>Because you do not have to create a huge method of focused code that changes the UI, it becomes easier to deal with new states or add or remove UI components.</li><li>Functional coding allows you to write code that can focus on situations and roles.</li><li>With Observing and Binding, you can separate ViewController into ViewModel and View, which is a key factor in applying MVVM design.</li></ul><p>I hope that many developers will be able to code more happily through Reactive Programming. Thank you for reading this story.</p><p>I am writing about developing iOS applications using Swift. I would also appreciate your interest in the following articles.</p><ul><li><a href="https://medium.com/@JinwooChoi/promise-syntax-with-reactiveswift-ae9b397a1bef">Promise Syntax with ReactiveSwift</a></li><li><a href="https://medium.com/@JinwooChoi/using-enums-in-swift-7d9cd7729758">Using Enums in Swift</a></li><li><a href="https://medium.com/@JinwooChoi/passing-parameters-to-restful-api-with-swift-codable-d78eb78f7b1">Passing parameters to Restful API with Swift Codable</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e89a2a651d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/phone-number-authentication-with-reactive-programming-6e89a2a651d2">Phone Number Authentication with Reactive Programming</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise Syntax with ReactiveSwift]]></title>
            <link>https://medium.com/@JinwooChoi/promise-syntax-with-reactiveswift-ae9b397a1bef?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9b397a1bef</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Mon, 26 Feb 2018 08:47:10 GMT</pubDate>
            <atom:updated>2018-02-27T05:43:49.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Oo1Din32plTMdI8GypK4Q.jpeg" /></figure><h3>Receiving the result of an asynchronous operation using a closure</h3><p>Receiving the results of asynchronous operations has long developed. On iOS, it started with Delegate, Notification. Since Objective-C’s block was introduced, it has evolved to use Swift’s Closure. In particular, Closure is the core of functional coding. It is also used in almost every aspect of Swift coding because of its compact representation and its various short formulas based on the powerful inference capabilities of the compiler.</p><p>There are a variety of ways to handle the results of your work with Closure. You can think about handling the results of user actions, such as handling UI events or handling Alert selection results. In addition, it can receive results after performing asynchronous operations through GCD, and can also be used for processing when data is received through the network.</p><p>Let’s think about the process of receiving a result after calling a Restful API using Closure. Basically, you need a closure to receive the result when the call succeeds and a closure to receive the error when it fails. You must pass two closure objects as parameters to the method that calls the Restful API.</p><pre>func getUserProfile(userId: Int, complete: ((JSON) -&gt; Void), failure: ((Error) -&gt; Void)) {<br>   // call complete on success, call failure on failure<br>}</pre><p>This is the easiest way to think. However, there is a disadvantage in this type of closure delivery and result reception. The syntax for calling the getUserProfile function above would look like this.</p><pre>getUserProfile(userId: 123, complete: { json in <br>    // success action<br>}, failure: { error in <br>    // failure action<br>})</pre><p>If a handler for another state is to be added to getUserProfile, it is inconvenient to change all other parts that call this method. Also, if you pass multiple closures as method parameters, it is not easy to understand the signature of the method itself, and it is not so good to read.</p><h3>Apply Promise syntax</h3><p>Consider the Promise of JavaScript. The traditional way to handle the results of JS’s asynchronous operations was to pass the Callback function as a parameter to the work function. However, the JS applications became more complex and the callback function became larger. Also, if we had to do asynchronous processing in a row, several callback functions had to be nested. So it caused the problem that the code was hard to read.</p><p>Promise has emerged to solve this problem. Instead of passing the Callback function as a parameter to the work function, you can create a Promise object to pass the Task and add a Handler to it. As a result, code such as processing results or performing another task can be added as a chain. This approach solves the disadvantages of the callback function.</p><pre>somePromise(task).then((result) =&gt; {<br>    // do other task <br>}).then((result) =&gt; {<br>    // result handling<br>})</pre><p>With the above chain structure, one function can contain only the code related to one task, and it can solve the nesting problem of the callback function. In iOS development, closure objects rarely nested.</p><p>However, in iOS, as mentioned in the previous example, it is similar that the function call syntax is complicated when the closure is passed as a parameter of the function, and it is difficult to modify the signature. So, let’s create a Promise object similar to JavaScript to improve the code for asynchronous processing and use it to call the Restful API.</p><p>In other words, I want to show you how to use getUserProfile with the following syntax.</p><pre>getUserProfile().value { json in<br>}<br>.completed {<br>}<br>.failed {<br>}</pre><h3>Using ReactiveSwift’s SignalProducer and Observer</h3><p>The basic part of the Promise implementation is ReactiveSwift. This is an open source library that allows reactive programming in Swift. See the link below for more information.</p><p><a href="https://github.com/ReactiveCocoa/ReactiveSwift">GitHub - ReactiveCocoa/ReactiveSwift: Streams of values over time</a></p><p>ReactiveSwift and ReactiveCocoa can be used for asynchronous tasks or UI event handling. They are also used for binding between View components and ViewModel components in application design patterns such as MVVM, which are heavily used recently.</p><p>SignalProducer can generate a signal and perform a certain task at the same time. You can inject a state-specific Side Effect (a kind of callback) from the outside, which can be generated via Observer inside the Task.</p><p>In this case, we simply try to use the SignalProducer to execute the task and receive the results. The following is a simple example of asynchronous processing using SignalProducer and Observer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c093aed120fb8a40305cf7f46eadab55/href">https://medium.com/media/c093aed120fb8a40305cf7f46eadab55/href</a></iframe><p>In a very simple way, I create a SignalProducer with a Task and register event handlers such as on (value: _). Later, when the start method is executed, the task will be executed and the value (300) will be passed through Observer after 10 seconds.</p><p>This alone can overcome the drawbacks of passing the closures as parameters to the asynchronous task execution method. However, there is the inconvenience of calling the start function every time, and it is not a perfect Promise form either. Now let’s make this more similar to Promise.</p><h3>Defining the Promise class</h3><p>First we defined a Wrapper class called Promise which has a SignalProducer type object as a property. And it only makes use of some features of SignalProducer. Promise receives the Task as a parameter of the constructor. It runs together when the SignalProducer is started, and can dispatch events to the Observer object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca14b6101b015c214652467c6e285bb/href">https://medium.com/media/1ca14b6101b015c214652467c6e285bb/href</a></iframe><h3>Immediately execute the task delivered to Promise</h3><p>The reason the SignalProducer has a start method is to allow the developer to define the signal and start it at a desired point in time. JS Deferred object is similar to calling a predefined Promise at a desired point in time. However, since the subject of this article is simply to follow JS’s Promise, let’s ignore the timing of the signal and let the start method execute immediately after defining the task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/093f2840555e0680a5be5e7594f6734c/href">https://medium.com/media/093f2840555e0680a5be5e7594f6734c/href</a></iframe><p><strong>Here we use the deinit of the Swift class. When an instance of a class is created in the local scope of a function or method, it is destroyed when the execution of the scope ends.</strong> For example, if Promise is created on the local scope as shown below, the instance will be destroyed when it goes out of scope, and then the SignalProducer will be started by calling the start method inside deinit.</p><pre>func myFunc() {<br>    let p = Promise( ... ) <br>}</pre><pre>func myFunc1() -&gt; Promise {<br>    return Promise( ... )<br>}</pre><pre>func myFunc2() {<br>    myFunc1().foo().bar()<br>}</pre><p>The p generated inside myFunc is destroyed at the end of the function call, and the Promise object returned by myFunc1 is destroyed at the end of execution of myFunc2. Using this approach, we create a Promise object and have the task execute as soon as the scope to which we added the Handler is over.</p><p>Of course, you can do similar things with Swift’s defer syntax, but I think it’s more concise to write everything you need on one line rather than the other. And the disadvantage is that you should not store instances of Promise in properties of other classes. However, since it is a feature of Promise syntax that the task is executed <strong>immediately</strong> and the result is delivered, this can also be neglected.</p><h3>Adding a Handler to Promise</h3><p>The ReactiveSwift’s SignalProducer can inject a side effect (event handler) for each state, which is a closure object that is called for each state of the Producer. For example, SignalProducer executes the received startHandler (Task) while generating a signal. It calls closure injected for “<strong>started</strong>” state immediately before generation and “<strong>started</strong>” state after execution.</p><p>Our Promise class uses SignalProducer internally, so we can add a handler to it by adding a side effect. The following code adds methods to the Promise class that inject side effects into the sp object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/356a100735df99d4fda196c7d8a445c6/href">https://medium.com/media/356a100735df99d4fda196c7d8a445c6/href</a></iframe><p>Now, the myFunc2 function can be improved as follows.</p><pre>func myFunc1() -&gt; Promise {<br>    return Promise( ... )<br>}</pre><pre>func myFunc2() {<br>    <strong>myFunc1().started {</strong><br>        doSomethingOnStarted()<br>    <strong>}.value { v in </strong><br>        doSomethingWithValue(v)<br>    <strong>}</strong><br>}</pre><h3>Using Promise syntax</h3><p>The following is an example of using the Promise defined above to call the Restful API. We used Alarmofire for network processing and SwiftyJSON for JSON processing. You can see that it is very similar to the Promise classification of JS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b861aa5697b676da792b2669443e37b3/href">https://medium.com/media/b861aa5697b676da792b2669443e37b3/href</a></iframe><p>Now the two disadvantages of passing the Closure object for callback processing to the methods listed above have been resolved. <strong>And adding the additional Promise Handler like “started” to the example above is very simple, and the code itself is much more readable.</strong></p><p>Again, <strong>the technical point is to use the ReactiveSwift’s SignalProducer </strong>and <strong>the Promise class’s deinit to call the start method so that it runs when the local scope expires.</strong></p><h3>Conclusion</h3><p>The use of Promise syntax in Swift can vary widely depending on implementation, and there have been open source libraries from the past. In recent years, ReactiveSwift has been inevitably used due to the many design patterns such as Reactive method and MVVC.</p><p>In this environment, it is inefficient to use a separate library for the Promise syntax. If you look inside, you will find that it implements similar concepts and philosophies, and you will find that implementations overlap. So if we have to use ReactiveSwift anyway, I think it’s a good idea to build our own Promise class based on it. I hope you can write more flexible and expressive code with this.</p><p>Hope this helps a little to some people. Thank you very much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9b397a1bef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactiveSwift를 이용해 Promise 구문 따라하기]]></title>
            <link>https://medium.com/@JinwooChoi/reactiveswift%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%B4-promise-%EA%B5%AC%EB%AC%B8-%EB%94%B0%EB%9D%BC%ED%95%98%EA%B8%B0-7a20bcb441f0?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a20bcb441f0</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactiveswift]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Fri, 23 Feb 2018 11:19:39 GMT</pubDate>
            <atom:updated>2018-02-26T08:42:39.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Oo1Din32plTMdI8GypK4Q.jpeg" /></figure><h3>Closure 구문을 사용해 비동기 작업의 결과 수신하기</h3><p>비동기 작업의 결과를 전달받는 방법은 오랫동안 발전해 왔다. iOS 개발 분야에서는 Delegate, Notification에서 시작해 Objective-C의 Block을 이용하는 방식으로 발전하고 Swift가 소개되면서 Closure를 사용하는 방식으로 발전하였다. 특히, Closure는 함수 위주 코딩의 핵심이며 간단한 표현과 컴파일러의 강력한 추론 기능에 기반을 둔 다양한 축약형 표현으로 인해서 Swift 코딩의 거의 모든 부분에서 사용된다.</p><p>Closure를 이용해서 작업의 결과를 처리하는 예는 다양하다. UI 컨트롤의 액션에 대해 핸들러를 추가하거나 Alert의 선택 결과를 처리하는 등의 사용자 행동의 결과에 대한 처리를 생각해 볼 수 있다. 또, GCD를 통해 비동기 작업을 수행 후 결과를 수신할 수도 있으며 네트워크를 통해 데이터를 전달받았을 때의 처리에도 활용할 수 있다.</p><p>Closure를 사용해서 Restful API 호출 후 결과를 전달받는 처리에 대해서 생각해 보자. 기본적으로 호출이 성공했을 때 결과를 전달받을 Closure와 실패했을때 Error를 전달받을 Closure가 필요하다. 두 개의 Closure 객체를 Restful API를 호출하는 메서드의 파라미터로 전달해야 한다.</p><pre>func getUserProfile(userId: Int, complete: ((JSON) -&gt; Void), failure: ((Error) -&gt; Void)) {<br>   // api 호출 후 성공시에 complete 호출, 실패시에 failure 호출<br>}</pre><p>가장 쉽게 생각할 수 있는 것이 위와 같은 형태이다. 그런데 이런 구조의 Closure 전달, 결과 수신 방식은 단점이 존재한다. 위의 getUserProfile 함수를 호출하는 구문은 다음과 같을 것이다.</p><pre>getUserProfile(userId: 123, complete: { json in <br>    // success action<br>}, failure: { error in <br>    // failure action<br>})</pre><p>getUserProfile에 compete, failure가 아닌 또 다른 상태에 대한 Handler가 추가되어야 한다면 이 메서드를 호출하는 다른 모든 부분을 변경해야하는 불편함이 발생한다. 또한, 메서드의 파라미터로 여러 개의 Closure를 전달하면 메서드 자체의 Signature를 파악하기 불편해질뿐더러 보기에도 그다지 좋지 않다.</p><h3>Promise 구문 적용해 보기</h3><p>JavaScript의 Promise를 생각해 보자. JS에서의 전통적인 비동기 작업 처리 방식은 Callback 함수를 작업 처리 함수에 파라미터로 전달하는 것이었다. 그러나 JS 기반의 애플리케이션이 점점 복잡해짐에 따라 비동기 처리 후 Callback 함수가 비대해지고 또 다른 비동기 처리를 이어서 해야 할 경우, 여러 개의 Callback 함수가 중첩되어야 해서 코드의 가독성이 떨어지는 등의 문제가 발생하는 경우가 많아졌다. 이런 문제를 해결하기 위해 Promise가 등장했다.</p><p>Callback 함수를 작업 함수의 파라미터로 전달하는 대신, Promise 객체를 만들어 Task를 전달하고 Handler도 추가할 수 있도록 한 것이다. 그 결과 Task의 결과를 처리하거나 또 다른 Task를 수행하는 등의 코드가 체인 형태로 추가될 수 있게 되었다. 이 방법으로 기존 방식의 단점을 해결한 것이다.</p><pre>somePromise(task).then((result) =&gt; {<br>    // do other task <br>}).then((result) =&gt; {<br>    // result handling<br>})</pre><p>위와 같은 구조로 코딩을 하면 하나의 함수는 하나의 작업에 관련된 코드만 포함할 수 있게 되었고 Callback 함수가 중첩되어서 코드를 파악하기 힘든 문제를 해결할 수 있다. iOS 개발 시에는 Closure 객체가 중첩되어서 정의되는 경우는 거의 없다.</p><p>하지만 iOS의 경우도 앞선 예제에서 언급했듯이 Closure를 함수의 파라미터로 전달할 경우 함수 호출 구문이 복잡해지고 Signature를 수정하기 힘든 문제가 있는 점은 비슷하다. 그러므로 JavaScript와 유사하게 Promise 객체를 만들어서 비동기 처리에 대한 코드를 개선해 보고 이를 이용해 Restful API를 호출하는 예까지 제시해 보고자 한다.</p><p>즉, getUserProfile을 아래와 같은 구문으로 사용할 수 있는 방법을 제시해 보고자 한다.</p><pre>getUserProfile().value { json in<br>}<br>.completed {<br>}<br>.failed {<br>}</pre><h3>ReactiveSwift의 SignalProducer와 Observer 사용해 보기</h3><p>Promise 구현의 기초적인 부분은 ReactiveSwift를 사용한다. 이는 Swift에서 반응형 프로그래밍을 가능하게 해주는 오픈 소스 라이브러리이다. 자세한 내용은 아래 링크를 참조 바란다.</p><p><a href="https://github.com/ReactiveCocoa/ReactiveSwift">GitHub - ReactiveCocoa/ReactiveSwift: Streams of values over time</a></p><p>ReactiveSwift와 ReactiveCocoa는 비동기 작업이나 UI 이벤트 처리에 다양하게 활용할 수 있다. 최근에 많이 사용되는 MVVM 같은 애플리케이션 디자인 패턴에서도 View 구성요소와 ViewModel 구성요소 사이의 바인딩에 활용되고 있으며 특정 객체의 상태 변경을 이벤트를 수신하는 처리 등도 가능하다.</p><p>SignalProducer는 Signal을 생성하고 그와 동시에 일정한 작업(Task)을 수행시킬 수 있다. 외부에서 이 SignalProducer에 상태별 Side Effect(일종의 콜백)을 주입할 수 있는데 이는 Task 내부에서 Observer를 통해 발생시킬 수 있다.</p><p>여기서는 단순히 이 SignalProducer를 이용해 Task를 실행하고 결과를 수신하는 기능만 사용해 보기로 한다. 다음은 SignalProducer와 Observer를 이용해 비동기 처리를 수행하는 간단한 예이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ee07b1f79e774afc2cef31f38e7db02/href">https://medium.com/media/8ee07b1f79e774afc2cef31f38e7db02/href</a></iframe><p>아주 간단하게 설명해 보자면, SignalProducer를 (일종의) Task를 넘겨서 생성하고 on(value: _ ) 등의 이벤트 핸들러를 등록해 놓는다. 이후, start 메서드를 실행하면 Task가 실행되고 10초 이후에 Observer를 통해서 값(300)을 전달하는 것이다.</p><p>이 정도만으로도 비동기 작업 수행 메서드에 Closure를 파라미터로 전달하는 방식의 단점을 어느 정도 극복할 수 있지만, start 함수를 호출해야 하고 완벽한 Promise form은 아니다. 이제 이걸 활용해서 Promise와 더 유사하게 만들어보자.</p><h3>Promise 클래스 정의</h3><p>일단 SignalProducer형 객체를 프로퍼티로 가지고 있으면서 특정 기능만 활용하기 위해서 Promise라는 Wrapper 클래스를 정의했다. <strong>Task를 생성자의 파라미터로 전달받는다.</strong> 이는 SignalProducer가 시작될 때 함께 실행되며 Observer 객체에 Event를 전달할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908940eb23d9e4d942c86dacc225b540/href">https://medium.com/media/908940eb23d9e4d942c86dacc225b540/href</a></iframe><p>SignalProducer가 start 메서드를 가지고 있는 이유는 Signal을 정의한 후 개발자가 원하는 시점에 실행할 수 있게 하기 위해서다. JS의 Deferred 객체가 미리 정의한 Promise를 원하는 시점에 호출하는 것처럼. 그러나 이 글의 주제는 단순히 JS의 Promise만을 흉내 내는 것이기 때문에 start 메서드가 Task를 정의하는 즉시 실행할 수 있도록 해보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/753a8da2195d54998d1c5dc732b7dd55/href">https://medium.com/media/753a8da2195d54998d1c5dc732b7dd55/href</a></iframe><p><strong>여기서는 Swift 클래스의 deinit을 이용한다. 클래스의 인스턴스는 함수나 메서드의 local scope에 생성되면 scope의 실행이 종료될 때 함께 소멸한다.</strong> 예를 들어, Promise가 아래와 같이 local scope 상에서 생성된다면 scope를 벗어날 때 인스턴스가 소멸하고 그때 deinit 내부에서 start 메서드를 호출해 SignalProducer가 시작된다.</p><pre>func myFunc() {<br>    let p = Promise( ... ) <br>}</pre><pre>func myFunc1() -&gt; Promise {<br>    return Promise( ... )<br>}</pre><pre>func myFunc2() {<br>    myFunc1().foo().bar()<br>}</pre><p>myFunc 내부에 생성한 p는 함수 호출이 끝나는 시점에 소멸하며, myFunc1이 생성해서 반환한 Promise 객체는 myFunc2의 실행이 끝나는 시점에 소멸한다. 이러한 접근법을 이용해서 Promise 객체를 생성하고 Handler를 추가한 scope가 끝나는 즉시 Task가 실행되도록 했다.</p><p>물론 defer 구문을 이용해서 비슷한 처리 할 수도 있지만, 그것보다는 필요한 모든 것을 코드 한 줄에 작성하면 더욱 간결한 표현이 될 수 있다고 생각한다. Promise의 인스턴스를 다른 클래스의 프로퍼티에 저장하면 안 된다는 단점도 있다. 하지만 Task와 그 결과를 약속하고 즉시 실행시키고 결과를 전달받는 Promise 구문의 특징을 생각하면 그런 경우는 거의 없을 것이기 때문에 이 또한 무시할 수 있는 정도의 단점이라 할 수 있다.</p><h3>Promise에 Handler 추가하기</h3><p>ReactiveSwift의 SignalProducer는 상태별로 <strong>사이드 이펙트(이벤트 핸들러)</strong>를 주입할 수 있는데, 이는 Producer의 각각의 상태에 맞게 호출되는 Closure 객체이다. 예를 들어 SignalProducer는 Signal을 생성하면서 전달받은 startHandler(Task)를 실행하는데, 그 직전에 <strong>“starting”</strong>, 실행 이후 <strong>“started”</strong> 상태를 위해 주입된 Closure를 호출한다.</p><p>우리의 Promise 클래스는 내부적으로 <strong>SignalProducer를 이용하기 때문에 바로 이 사이드 이펙트를 추가하는 방식으로 (Promise의) Handler를 추가</strong>할 수 있다. 다음은 sp 객체에 자주 사용되는 상태에 대해서 사이드 이펙트를 주입하는 메서드들을 추가한 코드이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e97225313813ac68fcec2358ff0546/href">https://medium.com/media/62e97225313813ac68fcec2358ff0546/href</a></iframe><p>이제 앞서 예로 든 myFunc2 함수를 다음과 같이 개선할 수 있다.</p><pre>func myFunc1() -&gt; Promise {<br>    return Promise( ... )<br>}</pre><pre>func myFunc2() {<br>    <strong>myFunc1().started {</strong><br>        doSomethingOnStarted()<br>    <strong>}.value { v in </strong><br>        doSomethingWithValue(v)<br>    <strong>}</strong><br>}</pre><h3>Promise 구문 사용해 보기</h3><p>다음은 앞서 정의한 Promise를 사용해 Restful API를 호출하는 예이다. Network 처리는 Alarmofire를 사용하고 JSON 처리는 SwiftyJSON을 사용하였다. 어떤가 JS의 Promise 구분과 흡사하지 않은가?!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56070ec527025ce143a95572465ac0ae/href">https://medium.com/media/56070ec527025ce143a95572465ac0ae/href</a></iframe><p>이렇게 해서 앞에서 나열한 메서드에 콜백 처리를 위한 Closure 객체를 전달했을 때의 두 가지 단점이 해결되었다. 위의 예제에 “<strong>started</strong>” 같은 <strong>추가적인 Promise Handler를 추가하는 일도 매우 간단히 할 수 있게 되었으며 코드 자체의 가독성도 훨씬 좋아졌다.</strong></p><p>다시 정리해 보면 <strong>기술적인 핵심은 ReactiveSwift의 SignalProducer를 이용하는 것과 Promise 클래스의 deinit에서 start 메서드를 호출하도록 하고 그것이 local scope가 소멸할 때 실행되도록 한 것</strong>이다.</p><h3>결론</h3><p>Swift에서 Promise 구문을 이용하는 방법은 구현하기에 따라 아주 다양할 수 있으며, 아주 예전부터 오픈 소스 라이브러리들이 존재해 왔다. 최근에는 Reactive 방식과 MVVC 같은 디자인 패턴이 많이 사용됨에 따라서 ReactiveSwift를 필연적으로 사용하게 되었다.</p><p>이런 환경에서 Promise 구문을 위해 별도의 라이브러리를 사용하는 것은 비효율적이다. 내부를 들여다보면 그것이 비슷한 개념과 철학을 구현하고 있다는 것을 발견할 것이고 구현이 중복된다는것을 알게 될 것이기 때문이다. 그래서 어차피 ReactiveSwift를 사용해야 한다면 그것을 기반으로 자체 Promise 클래스를 제작하는 것도 괜찮은 대안이라고 생각하고 그 방법을 제시해 보았다. 이것을 가지고 좀 더 유연하고 표현력 있는 코드를 작성할 수 있기를 바란다.</p><p>많은 사람에게 조금이나마 도움이 되었기를 바라며. 감사드리며 이만 줄입니다. 모두 행복한 코딩 하시길 바라며 …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a20bcb441f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Enums in Swift]]></title>
            <link>https://codeburst.io/using-enums-in-swift-7d9cd7729758?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d9cd7729758</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 15:09:10 GMT</pubDate>
            <atom:updated>2018-03-19T13:58:20.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOLMrawd5b-wjCnCeBms2g.jpeg" /></figure><h3>Enumerations are used anywhere.</h3><p>Consider a system that uses user information. Many apps, Internet services, and information processing systems in the world use user information. And it is essential to use an enumeration to represent attributes such as gender, marital status, and the type of authentication service (such as Facebook or Google).</p><p>It is used not only for representing and storing attributes of the domain model, but also for rendering the UI. Or it may be defined as an attribute of a specific entity somewhere in the remote database, or it may be passed through the remote API.</p><h3>How enumerations are used.</h3><p>Let’s look at how enumerations are used. To represent the Item in code, declare Constant and define the raw value. And displays each item in the UI using the associated expression. If you have a multilingual version, you should use the translated expression.</p><p>For example, for a marital status, we define an Enum called <strong>Married</strong>, declare a Constant named <strong>.Single</strong>, and define a raw value of <strong>0</strong>. In UI, <strong>.Single</strong> is expressed as <strong>미혼(Korean)</strong> or <strong>未婚(Chinese)</strong>.</p><p>Using an enumeration is logically equivalent to dealing with three elements. As you can see in the example above, you can code with <strong>Constant</strong>, <strong>Raw values</strong>, and <strong>expression values</strong>.</p><h3>Enumerations on iOS</h3><p>It’s true that Objective-C’s enumeration was lacking to smooth the work discussed above. It only had the advantage of increasing the readability of the Switch statement or If clause.</p><p>In Swift, you can set data types and values ​​in Enums and define methods or properties on them. Also, using Codable, it is possible to convert from value to Constant very easily. So, Code that uses Enums can be more elegantly organized.</p><p>Let’s take a look at how Swift can handle <strong>the Constant, Raw value, and Expression values</strong> ​​of Enumerations.</p><h3>Defining raw values for enumerations</h3><p>Let’s think about marital status in the previous example. The name of the Enum type is Married and has two items, Single and Married. This seems to be enough to write code that is readable. So how do I set the raw values?</p><p>How to define a value when declaring an Enum type is in fact a matter of developer preference. However, if you need to communicate with a remote system, it may not be delivered as a preferred value. For example, if you define a primitive value corresponding to <strong>Single</strong> as <strong>s</strong>, and you receive <strong>0</strong> as the value for the same item from the server, you might need code to convert that value to <strong>s</strong>.</p><p>So I recommend that remote systems using the Restful API use the values ​​defined in the communication protocol as the raw value of the Enum type. Thus, the Enum type for expressing marital status is defined as follows. <strong>.Single</strong> has a raw value of <strong>0</strong>, and <strong>.Married</strong> has <strong>1</strong>. Logically, there is an advantage to think of <strong>0</strong> as <strong>false</strong> and <strong>1</strong> as <strong>true</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f3234860e92d52eb79b0c0c3c09cd0/href">https://medium.com/media/78f3234860e92d52eb79b0c0c3c09cd0/href</a></iframe><h3>Converting Raw Values ​​to Constants with Codable</h3><p>Converting a specific value to an Enum type is not required in many places. In my experience, I can think of a time when I need to assign the value in the local storage or the value passed through the Restful API to the Enum type property of the domain model object. In addition to this, it is a normal process, so it may be necessary at any time. However, in this article, I will deal with JSON data received from a remote system.</p><pre>{<br>  user: {<br>      married: 0<br>  }  <br>}</pre><p>Let’s assume that we receive the above JSON data from the server. The following is a domain model named User defined on the local system. The User model implements Decodable to automatically convert JSON data. Items that are not essential are defined as Optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ab1992907ed2ab3eb4157367d0e004/href">https://medium.com/media/f9ab1992907ed2ab3eb4157367d0e004/href</a></iframe><p>Swift’s Codable can handle enumerations by default. Just declare the Enum type to conform to the Decodable, and the Decoder handles it. The following is the Married Enum type declared to conform to Decodable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef534d850fb6d2d147a72c4c27c7214/href">https://medium.com/media/7ef534d850fb6d2d147a72c4c27c7214/href</a></iframe><p>Since both the User model and the Married Enum are Codable compliant, you can simply obtain a user object by simply calling the decode method after creating the JSONDecoder. The married property of the converted User object will be stored as <strong>.Single</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/decd58654b2d06b10c6b303cd9fdebd3/href">https://medium.com/media/decd58654b2d06b10c6b303cd9fdebd3/href</a></iframe><p>Of course, Swift’s Enum basically provides a constructor that accepts rawValue as its argument, so it can be initialized to something like <strong>user.married = Married (rawValue: 0)</strong>.</p><p>We have discussed how to change the received data to Enum type.<strong> In fact, developers do not have much to do except to declare that they are Codable (or Decodable) compliant. Even if you add any Enum type, you can clear your mind to convert the raw value to Constant with a very simple few letter coding.</strong></p><h3>Smoothly convert Enum type variables to their represent values</h3><p>You can define the Enum type’s raw value to be displayed in the UI as follows. This makes it difficult to decode data received from the server using Codable unless the protocol is changed. And if your application supports multiple languages, you need to change it to a translated representation in the UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e4392b4c6e0eedc646764c9f6f50a8/href">https://medium.com/media/03e4392b4c6e0eedc646764c9f6f50a8/href</a></iframe><p>Back to the origin. Swift’s Enum can have methods. It can have instance methods and you can use it to return expression value for the UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42a7e85e6f1fa5d522a73ddfe38c861/href">https://medium.com/media/a42a7e85e6f1fa5d522a73ddfe38c861/href</a></iframe><p>Let’s look at the code above. I defined a string array named marriedStrings using the fireprivate access limiter. Define an instance method named toString inside the Married Enum to find and return the expression value corresponding to raw value in the marriedStrings array. You can use this to write the following UI code.</p><pre>marriedLabel.text = <strong>user.married.toString()</strong></pre><p>It is no longer necessary to set the expression value using the conditional expression as shown below.</p><pre>marriedLabel.text = <strong>user.married == .Single ? &quot;미혼&quot; : &quot;기혼&quot;</strong></pre><p>Of course, you can also create a global function that takes a Married Enum as an argument and returns an expression value. In an environment where Enum was a simple set of constants, like Objective-C, I did so to prevent it from repeating the same code. However, In Swift, I recommend adding the instance method as above, because <strong>I believe it is good code to encapsulate and increase the cohesion by adding methods related to specific data structures. User.married.toString()</strong> is better to read than <strong>StringFrom (user.married)</strong>.</p><h3>Show UI to select enumeration items</h3><p>In the case of an enumerated type item, the input UI is seldom received as a simple text form. It is essential to provide a UI that selects one from a list of possible items on any platform. Most developers use Picker UI on iOS as shown below. And you need code that passes a list of expression values ​​to display in the Picker component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*S-bqruec9Th-E-5Z_6C1Pg.png" /></figure><p>The following code displays the ActionSheetPicker that selects an enumeration item. Put a selectable item in a string array and pass it to the picker. Then, when a specific item is selected, the index of the selected item in the array is obtained and converted to Married Enum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e488940e592d6bd2de70e5517a1de9/href">https://medium.com/media/71e488940e592d6bd2de70e5517a1de9/href</a></iframe><p><strong>Assuming that the .Divorced (rawValue: 2) should be added to the Married Enum after doing this, all code that directly passes the string array as above should be changed.</strong> In this case, the compiler will not be able to check it, so there is a high probability that a bug will occur if the developer does not remember it.</p><p>In order to solve this inconvenience, I am trying to encapsulate and try to increase cohesiveness. Swift’s Enum can add a Static Method. You can use this to create methods that return the UI expression values ​​of all enumeration items as an array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cff4a087158a3719390fb96a0d9c616/href">https://medium.com/media/2cff4a087158a3719390fb96a0d9c616/href</a></iframe><p>It is the final version of the Married Enum type. Static method called <strong>strings</strong> is added to return all possible expression values as an array. We also added a Static Method called <strong>fromString</strong>, which can generate an Enum type variable through the expression value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37d53fcb65cf7e49786888fb6280eb17/href">https://medium.com/media/37d53fcb65cf7e49786888fb6280eb17/href</a></iframe><p>When displaying the ActionSheetPicker, I simply called the Married.Strings method without defining a separate array. And the selected value is simply converted to Married type variable through Married.fromString method. <strong>Now, even if .Divorced is added, you only need to modify the part that defines the married enum, and you do not have to worry about others.</strong></p><h3>Conclusion</h3><p>We have discussed how to handle the <strong>constants</strong>, <strong>raw values</strong>, and <strong>expressions</strong> of an Enum type through Swift. We have discussed how to convert raw values ​​received from outside using Codable into Enum type variables, and show how to easily connect Enum type and expression values ​​on UI.</p><p>An enumerated type is a type that can be used in a very wide variety of places. This is analogous to the use of integer types in all parts of our lives. <strong>Therefore, rather than merely improving the readability of the code, it is necessary to make the code simpler and easier to modify wherever the enumeration can be used through maximum encapsulation.</strong></p><p>I do not think that this article presented difficult logic or a particularly creative method. This is a small article about the problem that everyone is encountering in development and I think that there are many who use Swift Enum in a better way.</p><p>Hopefully people will be able to inspire even a little bit to figure out how to use Swift in a better way. Thank you very much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d9cd7729758" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/using-enums-in-swift-7d9cd7729758">Using Enums in Swift</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift에서 열거형 활용하기]]></title>
            <link>https://medium.com/@JinwooChoi/swift%EC%97%90%EC%84%9C-%EC%97%B4%EA%B1%B0%ED%98%95-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0-aaf69148e08d?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaf69148e08d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[codable]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Fri, 09 Feb 2018 09:24:53 GMT</pubDate>
            <atom:updated>2018-02-09T09:24:53.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOLMrawd5b-wjCnCeBms2g.jpeg" /></figure><h3>열거형은 어디서든 사용된다.</h3><p>사용자 정보를 활용하는 시스템에 대해서 생각해 보자. 세상에 존재하는 무수히 많은 앱, 인터넷 서비스, 정보처리를 시스템은 사용자 정보가 필요하다. 그중 사용자의 성별이나 결혼 여부, 인증 서비스 종류(Facebook이나 Google 같은) 등의 속성을 표현하기 위해 열거형을 사용하는 것은 필수적인 일이다.</p><p>로컬 애플리케이션의 도메인 모델의 속성을 표현하고 저장하기 위한 것뿐만 아니라, UI를 표현하기 위한 코드에서도 사용된다. 원격 데이터베이스의 어딘가에 특정 엔티티의 속성으로 정의되어 저장되어 있을 수도 있고, 원격 API를 통해서 값을 전달받을 수도 있다.</p><h3>열거형은 어떻게 활용되는가.</h3><p>열거형이 어떻게 활용되는지 살펴보자. 각각의 항목을 코드상에서 표현하기 위해 Constant를 선언하고 원시 값을 정의한다. 그리고 각각의 항목을 연관된 표현을 이용해 UI에 표시한다. 다국어를 지원한다면 상황에 맞게 번역된 표현을 사용해야 한다.</p><p>예를 들어 결혼 여부라는 상태를 표현하기 위해서는 <strong>Married</strong>라는 Enum을 정의하고 <strong>Single</strong>이라는 Constant를 선언하고 <strong>0</strong>이라는 원시 값을 정의하는 식이다. UI에는 <strong>Single</strong>을 <strong>미혼</strong> 혹은 <strong>未婚</strong>으로 표현한다.</p><p>열거형 데이터를 활용하는 것은 논리적으로 세 가지 요소를 다루는 것으로 볼 수 있다. 위에서 예를 든 것처럼 <strong>Constant, 원시 값, 표현 값</strong>을 가지고 상황에 따라서 코딩해 나가는 것이다.</p><h3>iOS에서의 열거형</h3><p>오랫동안 iOS의 애플리케이션 개발 언어였던 Objective-C의 열거형은 위에서 논의한 작업을 매끄럽게 처리하기에는 다소 부족했던 것이 사실이다. Switch 문이나 If 절의 가독성을 높여주는 정도의 장점만을 가지고 있었을 뿐.</p><p>Swift가 발표되고 열거형의 항목에 자료형과 원시 값을 설정할 수 있고 메서드나 프로퍼티를 정의할 수 있게 되었다. 또한, Codable이 도입되면서 원시 값에서 Constant로 편하게 변환할 수 있게 되면서 열거형을 활용하는 코드가 좀 더 세련되게 정리될 수 있는 환경이 되었다고 할 수 있다.</p><p>그럼 Swift를 통해 열거형 자료의 <strong>Constant, 값, 표현 값</strong>이라는 요소를 어떻게 다룰 수 있는지 살펴보자.</p><h3>열거형의 값 정의하기</h3><p>앞에서 예로든 결혼 여부에 대해서 생각해 보자. Enum형의 이름은 Married 정도로 정하고 Single, Married 정도로 Constant를 정의할 수 있다. 이 정도면 가독성 있는 코드를 작성하기 충분할 것 같다. 그럼 원시 값은 어떻게 설정해 주어야 하는가?</p><p>특정한 열거형을 선언할 때 원시 값을 어떻게 정의하는지는 사실 개발자의 선호도에 따르면 되는 일이긴 하다. 하지만 원격 시스템과 통신을 해야 할 필요가 있는 경우, 같은 정보가 개발자가 선호하는 값으로 전달되지 않을 수도 있다. 다시 말해 <strong>Single</strong>에 대응하는 원시 값을 <strong>s</strong>로 정의하였는데 서버에서 사용자의 결혼 여부에 대한 값이 <strong>0</strong>으로 전달된다면 그 값을 <strong>s</strong>로 변환하는 코드가 필요할 수 있다.</p><p>그래서 Restful API를 사용하는 원격 시스템 같은 경우에는 통신 프로토콜에서 정의하고 있는 값을 열거형의 원시 값으로 사용하는 것을 추천한다. 그 결과 결혼 여부를 표현하기 위한 열거형을 다음과 같이 정의하였다. .Single은 원시 값으로 0을 가지고, .Married는 1을 가진다. 이는 0을 거짓, 1을 참으로 생각할 수도 있기 때문에 논리적 표현 관점에서 봐도 어색하지 않다는 장점이 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f3234860e92d52eb79b0c0c3c09cd0/href">https://medium.com/media/78f3234860e92d52eb79b0c0c3c09cd0/href</a></iframe><h3>Codable을 통한 원시 값에서 Constant로 변환</h3><p>특정 값을 열거형으로 변환해야 하는 작업은 다양한 곳에서 필요한 작업은 아니다. 필자의 경험으로는 로컬 데이터에 저장된 값이나 Restful API를 통해 전달된 값을 도메인 모델 객체의 열거형 속성에 대입해 주어야 할 때 정도를 생각해 볼 수 있다. 그 외에도 워낙 일반적인 처리이기 때문에 때에 따라서 얼마든지 필요할 수는 있다. 여기서는 앞서 얘기했던 원격 시스템의 데이터 처리로 한정해 전달받은 JSON 데이터를 다루는 것을 살펴보도록 하겠다.</p><pre>{<br>  user: {<br>      married: 0<br>  }  <br>}</pre><p>위와 같은 JSON 데이터를 서버로부터 전달받았다고 해보자. 다음은 로컬 시스템에 정의된 User라는 도메인 모델이다. JSON 데이터를 자동으로 변환하기 위해 Decodable을 구현하고 있다. 또 필수항목이 아닌 항목은 Optional로 정의되어 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ab1992907ed2ab3eb4157367d0e004/href">https://medium.com/media/f9ab1992907ed2ab3eb4157367d0e004/href</a></iframe><p>Swift Codable은 기본적으로 열거형도 처리하게 되어있다. Codable을 사용해 본 개발자라면 누구나 아는 내용이겠지만 <strong>Enum 형을 Decodable을 준수하도록 선언하기만 하면 Decoder가 알아서 처리해 준다.</strong> 다음은 Decodable을 준수하도록 선언한 Married 열거형이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef534d850fb6d2d147a72c4c27c7214/href">https://medium.com/media/7ef534d850fb6d2d147a72c4c27c7214/href</a></iframe><p>User 모델과 Married 열거형 모두 Codable을 준수하고 있기 때문에 그저 JSONDecoder를 생성한 후 decode(…) 메서드를 호출하는 것만으로 간편하게 user 객체를 얻을 수 있다. 여기에 married 속성은 .Single로 저장되어 있을 것이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/decd58654b2d06b10c6b303cd9fdebd3/href">https://medium.com/media/decd58654b2d06b10c6b303cd9fdebd3/href</a></iframe><p>물론 Swift의 열거형은 기본적으로 rawValue를 인자로 받는 생성자를 제공하기 때문에 user.married = Married(rawValue: 0) 과 같은 형태로 초기화 할 수도 있다.</p><p>이렇게 전달받은 데이터를 열거형으로 변경하는 방법을 알아보았다. 사실 <strong>개발자는 Codable(Decodable)을 준수한다고 선언하는 것 말고는 해줄 것이 별로 없다. 어떤 열거형이 추가된다고 하더라도 아주 간단한 몇 글자 코딩만으로 원시 값(rawValue)을 Constant로 변환하는 작업을 머릿속에서 지울 수 있다.</strong></p><h3>열거형 변수를 표현 값으로 매끄럽게 변환</h3><p>다음과 같이 열거형의 원시 값(rawValue) 자체를 UI에서 표시할 내용으로 정의할 수도 있다. 이렇게 하면 프로토콜을 바꾸지 않는 한 서버에서 전달받은 데이터를 Codable을 이용해 Decoding 하기 힘들다. 하지만 그렇게 하더라도 다국어를 지원하는 애플리케이션이라면 UI에 번역된 표현으로 변경해주는 처리가 추가되어야 할 것이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e4392b4c6e0eedc646764c9f6f50a8/href">https://medium.com/media/03e4392b4c6e0eedc646764c9f6f50a8/href</a></iframe><p>다시 원점으로 돌아가서. Swift의 Enum은 메서드를 가질 수 있다. 인스턴스 메서드를 가질 수 있는데, 이것을 이용해 UI의 표현 값을 반환하도록 할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42a7e85e6f1fa5d522a73ddfe38c861/href">https://medium.com/media/a42a7e85e6f1fa5d522a73ddfe38c861/href</a></iframe><p>위의 코드를 살펴보자. fireprivate 접근제한자를 사용해서 marriedStrings라는 문자열 배열을 정의하였다. <strong>Married Enum 내부에 toString이라는 인스턴스 메서드를 정의해 marriedStrings 배열에서 rawValue에 해당하는 표현 값을 찾아서 반환한다.</strong> 이를 이용해 UI 관련 코드에서 다음과 같은 코딩을 할 수 있다.</p><pre>marriedLabel.text = <strong>user.married.toString()</strong></pre><p>아래와 같이 번거롭게 조건절을 이용해 값을 설정해 줄 필요가 없어졌다.</p><pre>marriedLabel.text = <strong>user.married == .Single ? &quot;미혼&quot; : &quot;기혼&quot;</strong></pre><p>물론 Married Enum을 인자로 받아서 문자열을 반환하는 전역 함수를 만들어서 처리할 수도 있다. Objective-C와 같이 Enum이 단순한 상수의 집합이었던 환경에서는 그렇게 처리해 같은 코드가 반복되는 것을 막기도 했다. 하지만 그 보다는 특정 자료구조에 연관된 메서드를 추가해 캡슐화를 하고 코드의 응집도를 높여주는 것이 좋은 코드라고 믿기 때문에 위와 같이 인스턴스 메서드를 추가하는 것을 추천한다. StringFrom(user.married) 보다는 user.married.toString()이 보기도 더 좋지 않은가!</p><h3>열거형 항목 선택 UI 표시</h3><p>열거형 항목의 경우 입력 UI에서 단순 텍스트 형태로 입력받는 경우는 거의 없다. 어떤 플랫폼이건 가능한 항목의 목록에서 하나를 선택하는 방식의 UI를 제공하는 것이 필수적이다. iOS에서는 대부분 아래 이미지와 같이 Picker UI를 이용해 하나의 항목을 선택할 수 있도록 구현하며 Picker 컴포넌트에 표시할 값의 목록을 전달하는 코드가 필요하다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*S-bqruec9Th-E-5Z_6C1Pg.png" /></figure><p>다음은 결혼 여부를 선택하는 ActionSheetPicker를 표시하는 코드이다. 선택 가능한 항목을 문자열 배열에 넣어서 전달하며, 특정항목이 선택되면 같은 배열에서 선택 값의 index를 구해서 Married Enum으로 변환하는 처리를 하고 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e488940e592d6bd2de70e5517a1de9/href">https://medium.com/media/71e488940e592d6bd2de70e5517a1de9/href</a></iframe><p>이렇게 처리한 후 <strong>Married Enum에 .Divorced(rawValue: 2)가 추가되어야 한다고 가정하면 위와 같이 별도의 문자열 배열을 직접 만들어 전달한 코드는 모두 변경되어야 한다.</strong> 이런 경우는 컴파일러가 점검해 줄 수도 없기 때문에 개발자가 기억하지 못하면 버그가 될 확률이 높다.</p><p>이런 불편함을 해결하기 위해 캡슐화를 하고 응집도를 높이려고 노력하는 것이 아니겠는가. Swift의 Enum은 Static Method를 추가할 수 있다. 이를 이용해 모든 열거형 항목의 UI 표현 값을 배열로 반환하는 메서드를 추가할 수 있다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cff4a087158a3719390fb96a0d9c616/href">https://medium.com/media/2cff4a087158a3719390fb96a0d9c616/href</a></iframe><p>Married 열거형의 최종 버전이다. <strong>strings()라는 Static Method를 추가해 가능한 모든 표현 값을 배열로 반환하도록 하였고, 표현 값을 통해서 열거형 변수를 생성할 수 있는 fromString(_ text:)이라는 Static Method도 추가</strong>하였다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37d53fcb65cf7e49786888fb6280eb17/href">https://medium.com/media/37d53fcb65cf7e49786888fb6280eb17/href</a></iframe><p>ActionSheetPicker를 표시할 때도 별도의 배열을 정의하지 않고 Married.Strings() 메서드 호출로 간단하게 처리하였고, 선택한 값도 Married.fromString(…) 메서드를 통해서 간단히 Married형 변수로 변환하였다. <strong>이제 .Divorced가 추가되어도 Married enum을 정의하는 부분만 수정하면 다른 곳은 신경 쓰지 않을 수 있게 되었다.</strong></p><h3>결론</h3><p>이상으로 Swift를 통해 열거형의 <strong>Constant, 값, 표현 값</strong>을 어떻게 다루는지 알아보았다. Codable을 이용해 외부에서 전달받은 원시 값을 어떻게 열거형 변수로 변환하는지에 대해서 알아보았고 열거형과 UI 상의 표현 값을 편하게 연결할 방법을 제시해 보았다.</p><p>열거형은 아주 광범위한 곳에서 사용될 수 있는 자료형이며 이는 정수형이 우리 삶의 모든 곳에서 사용되는 것과 유사하게 볼 수 있다. 그러므로 <strong>단순히 코드의 가독성만 향상만을 목적으로 하는 것이 아니라 가능한 최대한의 캡슐화를 통해서 열거형이 사용될 수 있는 모든 곳의 코드를 간결하게 만들고 쉽게 수정할 수 있는 것을 목적으로 할 필요가 있다.</strong></p><p>필자는 이 글을 통해 어려운 로직이나 특별히 창의적인 방법을 제시했다고 생각하지 않는다. 이것은 개발을 하다 보면 누구나 부딪히는 소소한 문제에 대한 글이며 더 좋은 방식으로 Swift Enum을 활용하는 개발자도 많을 것으로 생각한다.</p><p>사람들이 더 좋은 방식으로 Swift의 언어적인 특성을 활용하는 방법을 생각해 내는데 조금이라도 영감을 줄 수 있기를 바라며, 감사드리며 이만 줄인다. 여기까지.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaf69148e08d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing parameters to Restful API with Swift Codable]]></title>
            <link>https://medium.com/@JinwooChoi/passing-parameters-to-restful-api-with-swift-codable-d78eb78f7b1?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78eb78f7b1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 07:36:15 GMT</pubDate>
            <atom:updated>2018-03-14T10:59:32.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7hYv0zwPypteWQza7K7oA.jpeg" /></figure><p>Codable made it convinient for many things. This is especially useful when creating a restful app. Because it is necessary to decode the serialized object. Codable makes it super easy to convert a JSON object into a domain model. (Of course there are still some inconveniences…)</p><p>Converting received data to model objects has become very easy. But when sending data, it is not easy to know where Codable makes it easier. <br>This is because it is very rare to directly convert domain model objects into parameters of Restful API. If you change existing design to use Codable instead of applying it to existing design, you can take advantage of it. I want call it the Codable Driven Design :-)</p><h3>Crassical way</h3><p>To pass parameters to the Restful API, you need to add variables to the Dictionary. This is a very classic form of Objective-C method. This is a sign up handling code almost all restful apps should include.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55cb6c5fd3a229084049a8f820d8cfe0/href">https://medium.com/media/55cb6c5fd3a229084049a8f820d8cfe0/href</a></iframe><p><strong>Add the passed method parameters to the params dictionary.</strong> Then passes the params Dictionary to the HTTP Client object for low-level processing that actually calls the API. And it delivers success and failure block to receive result.</p><h3>Crassical Swift style</h3><p>Here is the Swift 2 source code for the same function. It was written before Codable was released.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc831fe2fa92971ec10628caf45df6fa/href">https://medium.com/media/bc831fe2fa92971ec10628caf45df6fa/href</a></iframe><p>Here is also the code to add the method parameters to the dictionary p. Since it do not use Promise (or Observable / Disposable), it still passing success closure to the callAPI. It then returns a Failure object so that the caller can add failure handling.</p><h3>The shortcomings of traditional ways</h3><p>The two examples above have two drawbacks.</p><p><strong>First, when a method parameter is added or deleted, all relevant code must be modified.</strong> Of course, Swift supports default parameter values, so you can flexibly deal with these situations. But if you need to pass values ​​only to a specific item in that method that has multiple parameters with default values, you must set default value for all other items manually. Therefore, the default parameter value is not a complete solution.</p><p><strong>Second, you must manually add method parameters to Dictionary.</strong> Both examples have code like <strong>p [“name”] = name, p [“birthday”] = b</strong>. And it is very annoying in itself.</p><p>Codable can help to reduce this kind of boilerplate code. Let’s take a third example.</p><h3>Modern Swift Style</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d8baf6fb2bb9aed050f7f8c005fd811/href">https://medium.com/media/2d8baf6fb2bb9aed050f7f8c005fd811/href</a></iframe><p>As in the previous examples, this is a method that calls the API to add a new user. Here we have replaced the parameters with an instance of Structure that follows an Encodable named NewUserParams. We then call the dictionary method to convert it to a Dictionary. And pass it to the multipartCall method.</p><p>There is no boilerplate code. It is now possible to call the method once. How can Structure become a Dictionary? How does the dictionary method do this? The answer is Codable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5614042d680e5a01ceb628c08cac79b/href">https://medium.com/media/a5614042d680e5a01ceb628c08cac79b/href</a></iframe><p>This is the source code for the DictionaryEncodable protocol.<strong> It conforms to the Encodable protocol. And it includes a dictionary method that serializes itself to a JSON object using the JSONEncoder.</strong> Thus, a structure that conforms to the DictionaryEncodable can be converted to a Dictionary simply by calling the dictionary method.</p><p><strong>We can create a structure containing the parameters of the Restful API, simply change it to a Dictionary and pass it to the next step.</strong> We no longer need to add method parameters to the Dictionary. And no longer need to modify the relevant parts when the parameters of Restful API changed.</p><p>In addition, Restful API parameter list can be easily grasped in a structured form. You can also easily distinguish members of structs from required and non-required items by using Swift Optional.</p><p>In this way, I noticed how not only the data received from the Restful API, but also the data to be transmitted, can be handled easily through Codable. <br>We also looked at the disadvantages of the existing approach to send parameters and how the new approach to using Swift Codable can overcome it. In short, through structured parameters.</p><p>Determining whether or not to structure multiple parameters always occurs in the programming process. I chose the structured parameters. And I think it is a good idea to intentionally structure it in certain parts in order to use Swift Codable. I hope that more developers will be able to implement the desired functionality quickly and easily through the new features of Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78eb78f7b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift codable을 이용한 restful api 호출]]></title>
            <link>https://medium.com/@JinwooChoi/swift-codable%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-restful-api-%ED%98%B8%EC%B6%9C-21de0fffa84a?source=rss-575d0599ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/21de0fffa84a</guid>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Jinwoo Choi]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 07:10:22 GMT</pubDate>
            <atom:updated>2018-02-02T07:39:53.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7hYv0zwPypteWQza7K7oA.jpeg" /></figure><p>Swift에 Codable이 추가됨으로 인해 많은 부분이 편해졌다. 현장에서 가장 보편적으로 사용하는 Restful 방식의 통신을 하는 애플리케이션을 작업할 때 특히 그러하다. 객체를 직렬화된 상태로 code/decode 하는 작업이 필수적으로 이루어져야 하기 때문이다. Codable을 이용해서 서버에서 전달받은 JSON 객체를 도메인 모델 객체로 변경하는 작업이 예전과는 비교도 안 될 정도로 편리해졌다. (물론 여전히 일부 불편한 점도 있지만 …)</p><p>수신된 데이터를 모델 객체로 전환하는 처리하기가 쉬워졌지만, 전달할 데이터는 도메인 모델 객체를 Restful API의 파라미터로 직접 변환해서 전달하는 경우는 별로 없기 때문에 직관적으로 편해질 수 있는 부분이 드러나지는 않는다. 하지만 기존 설계에 Codable을 반영하는 것이 아니라, Codable을 사용하기 위해 기존 설계를 조금만 변경해 주면 같은 이점을 누리면서 몇 가지 장점을 가지는 코드를 만들어 낼 수 있다. Codable driven architecture 라고 나 할까?</p><p>Restful API에 파라미터를 전달하기 위해서는 메서드 파라미터 목록을 Dictionary 형태로 전환하는 코드가 필요했다. 아래는 아주 고전적인 Restful API를 호출하는 Objective-C 메서드이다. 그것도 Restful 통신 방식의 애플리케이션 중 거의 무조건 들어가야 하는 정도로 많이 만들어지는 신규 사용자 가입 처리 코드이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55cb6c5fd3a229084049a8f820d8cfe0/href">https://medium.com/media/55cb6c5fd3a229084049a8f820d8cfe0/href</a></iframe><p>API를 실제로 호출하는 저수준 처리를 수행하는 Http Client 객체에 대상 API의 path와 Dictionary 형태의 파라미터 모음을 전달해 주고 처리 결과를 전달받을 success, failure block 객체를 전달한다. 메서드 파라미터를 여러 개 선언하고 그 파라미터들을 Dictionary로 묶는 처리가 코드 초반에 구현되어 있다. 다음은 codable이 발표되기 훨씬 전 Swift 2.x 기반으로 작업했던 프로젝트의 사용자 추가 API에 대한 구현이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc831fe2fa92971ec10628caf45df6fa/href">https://medium.com/media/bc831fe2fa92971ec10628caf45df6fa/href</a></iframe><p>여기도 물론 위의 코드와 같이 API 파라미터들을 메서드 파라미터로 받아서 Dictionary로 묶어주는 처리가 되어있다. 요즘 유행하는 Promise 구문 (혹은 Observable/Disposable) 스타일로 구현되어 있지 않기 때문에 여전히 success closure를 파라미터로 넘기고 실패 처리를 호출한 쪽에서 추가할 수 있도록 구현된 failure 객체를 반환하고 있다.</p><p>위의 두 가지 예제는 몇 가지 단점이 있는데 두 가지 정도만 예를 들어볼 수 있다. 첫째, 메서드 파라미터가 추가되거나 삭제되었을 때 모든 호출하는 코드가 수정되어야 한다는 점이다. 물론 Swift는 default 파라미터를 지원하기 때문에 어느 정도는 유연하게 사용할 수 있기는 하지만 default 파라미터를 여러 개 가지는 메서드의 특정 파라미터에만 값을 전달하기 위해서는 나머지 파라미터에 모두 nil 값을 넘겨줘야 하는 경우가 생길 수 있는 불편함은 여전히 남는다.</p><p>둘째, 전달받은 메서드 파라미터들을 일일이 Dictionary에 저장하는 코드를 작성해 주어야 한다는 것이다. 두 번째 예제의 3, 4번째 라인에 작성된 p[“name”] = name, p[“birthday”] = b 등이 그 예이다.</p><p>사실 이런 종류의 Boilerplate 코드 작성을 Codable을 통해서 최소화 할 수 있다. 세 번째 예제를 살펴보자.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d8baf6fb2bb9aed050f7f8c005fd811/href">https://medium.com/media/2d8baf6fb2bb9aed050f7f8c005fd811/href</a></iframe><p>위의 두 예제와 마찬가지로 새로운 사용자를 추가하는 API를 호출하는 메서드이다. 여기서는 파라미터 목록을 NewUserParams라는 Encodable을 따르는 Struct 의 인스턴스로 대체하였다. 또한, 다른 예제와 마찬가지로 Restful API를 호출하는 multipartCall 메서드의 파라미터에 Dictionary를 넘겨주고 있다.</p><p>Struct를 전달받아서 Dictionary를 넘겨줘야 하기 때문에 해당 변환 작업을 수행하는 dictionary() 메서드를 호출하고 있다. 이는 직접 구현한 DictionaryEncodable 프로토콜에 포함되어 있는데, 여기서 Codable을 이용해 변환하는 처리를 수행한다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5614042d680e5a01ceb628c08cac79b/href">https://medium.com/media/a5614042d680e5a01ceb628c08cac79b/href</a></iframe><p>DictionaryEncodable의 소스 코드이다. 앞서 언급한 dictionary() 메서드를 포함하는 프로토콜이며, 다른 Codable 관련 문서에서 많이 접했던 JSONEncoder를 이용해서 데이터를 Encoding 하는 코드가 포함되어 있다.</p><p>이렇게 함으로써 API를 호출할 때마다 반복적으로 코딩해야 했던 메서드 파라미터들을 Dictionary에 일일이 추가해주는 처리를 할 필요가 없어졌다. 필요한 것은 파라미터 목록을 정의하는 Struct를 만들고 DictionaryEncodable 프로토콜을 따르도록 하고 dictionary() 메서드를 호출하는 것뿐이다.</p><p>또한 API의 파라미터가 추가되거나 삭제될 경우에 해당 메서드(postUsers)를 호출하는 모든 부분을 수정해 줄 필요가 없어졌다. Restful API의 파라미터 목록을 조금 더 구조화된 형태로 한눈에 파악할 수 있는 장점도 생겼으며 Swift의 Optional을 이용해 필수 항목과 아닌 항목을 구분할 수도 있다.</p><p>이로써 Restful API에서 수신한 데이터뿐만 아니라 전달할 데이터까지도 어떻게 Codable을 통해 편하게 다루는지를 알아보았다. 파라미터를 구조화시켜서 전달할 것인지 그냥 나열해서 전달할 것인지를 결정하는 것은 프로그래밍 과정에서 발생하는 필연적인 부분이다. 필자는 Codable을 이용하기 위해 특정 부분에서 의도적 구조화를 추구해 Boilerplate 코드를 줄이는 방안을 구현해 보았다.</p><p>많은 부분에서 Codable을 이용해 코딩 효율을 높일 수 있다고 필자는 생각한다. 더 많은 개발자가 최소한의 코딩으로 빠르게 원하는 기능을 구현할 수 있기를 바라며 이 글은 여기서 줄인다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21de0fffa84a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>