<?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 Chynmn on Medium]]></title>
        <description><![CDATA[Stories by Chynmn on Medium]]></description>
        <link>https://medium.com/@chynmn0523?source=rss-5dd33e6287d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vn_iffN1emKuU32M</url>
            <title>Stories by Chynmn on Medium</title>
            <link>https://medium.com/@chynmn0523?source=rss-5dd33e6287d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:53:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chynmn0523/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[iOS 스터디 5주차 Ch24]]></title>
            <link>https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-5%EC%A3%BC%EC%B0%A8-ch24-4ce4b157ce85?source=rss-5dd33e6287d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce4b157ce85</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chynmn]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 09:07:36 GMT</pubDate>
            <atom:updated>2022-11-21T09:07:36.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgHS6QkGMXrrQlo2jUReNw.png" /></figure><blockquote>Chapter 24. SwiftUI 스택 정렬과 정렬 가이드</blockquote><blockquote><em>스택 정렬의 고급 기술인 컨테이너 정렬, 정렬 가이드, 커스텀 정렬, 서로 다른 스택들 간의 정렬 구현을 실습해본다.</em></blockquote><h4>1. 컨테이너 정렬</h4><pre>VStack (alignment: .leading) {<br>            // 특정 컨테이너 값을 지정하지 않으면 .center가 디폴트. .leading(왼쪽 정렬) .trailing(오른쪽 정렬)<br>            Text(&quot;This is some text&quot;)<br>            Text(&quot;This is some longer text&quot;)<br>            Text(&quot;This is short&quot;)<br>        }<br>        .font(.body)<br>        .border(.blue)<br>        .padding()<br>        <br>        HStack (alignment: .lastTextBaseline, spacing: 20) {<br>            // 역시 중앙 정렬이 디폴트. .firstTextBaseLine(상단 정렬) .lasrTextBaseLine(하단 정렬)<br>            Text(&quot;This is some text&quot;)<br>                .font(.largeTitle)<br>            Text(&quot;This is. ome much longer text&quot;)<br>                .font(.body)<br>            Text(&quot;This is short&quot;)<br>                .font(.headline)<br>        }<br>        .border(.blue)<br>        .padding()</pre><p>• 수행 결과</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*eQtTdhwN-3MestQSG8OL_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*8wIMljooiEcrbRFtP2enDQ.png" /></figure><h4>2. 정렬 가이드</h4><pre>        VStack(alignment: .leading) {<br>            Rectangle()<br>                .foregroundColor(Color .green)<br>                .frame(width: 120, height: 50)<br>            Rectangle()<br>                .foregroundColor(Color .red)<br>                .alignmentGuide(.leading, computeValue: { d in 120.0 })<br>            // 120포인트 왼쪽 정렬. 부모 스택에 적용된 정렬 타입과 일치해야 한다.<br>                .frame(width: 200, height: 50)<br>            Rectangle()<br>                .foregroundColor(Color .blue)<br>                .alignmentGuide(.leading, computeValue: { d in d[HorizontalAlignment.trailing] + 20})<br>            // ViewDimensions 객체는 뷰의 HorizontalAlignment와 VerticalAlignment 프로퍼티에 대한 접근을 제공한다.<br>                .frame(width: 180, height: 50)<br>            Rectangle()<br>                .foregroundColor(Color .purple)<br>                .alignmentGuide(.leading, computeValue: {d in d.width / 3})<br>            // offset 하드코딩 대신 클로저에 전달된 ViewDimensions 객체의 프로퍼티를 정렬 가이드 위치를 계산하는데 이용할 수 있다.<br>                .frame(width: 160, height: 50)<br>        }</pre><p>• 수행 결과</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*6mxz1xnxhhX8BJeu-FnbeA.png" /></figure><h4>3. 정렬 가이드 도구 사용하기</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHbykQqj_wHhZELTbyFnlA.jpeg" /></figure><p>정렬 가이드에 익숙해지기 위해 다양한 설정으로 테스트해 보는 오픈소스를 복사해 아이패드에 앱을 설치 후 실습 해보았다. 아래는 위의 앱을 설치하기 위한 alignment-guides-tool.swift 라는 소스코드이다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f174a42e4d05d30256df076f1aed09/href">https://medium.com/media/87f174a42e4d05d30256df076f1aed09/href</a></iframe><h4>4. 커스텀 정렬 타입</h4><pre>        // 4. 커스텀 정렬 타입 -&gt; 표준 정렬 타입을 확장<br>        // 방법 1 : 정렬에 적용될 값을 계산하기 위한 계산식이 포함된 정렬 가이드를 적용하는 방법<br>        // 방법 2 : 여러 뷰에 적용될 수 있는 커스텀 정렬을 생성<br>        HStack(alignment: .oneThird) {<br>            Rectangle()<br>                .foregroundColor(Color .green)<br>                .frame(width: 50, height: 200)<br>            Rectangle()<br>                .foregroundColor(Color .red)<br>                .alignmentGuide(.oneThird, computeValue: { d in d[VerticalAlignment.bottom]})<br>                .frame(width: 50, height: 200)<br>            Rectangle()<br>                .foregroundColor(Color .blue)<br>                .frame(width: 50, height: 200)<br>            Rectangle()<br>                .foregroundColor(Color .orange)<br>                .alignmentGuide(.oneThird, computeValue: { d in d[VerticalAlignment.top]})<br>                .frame(width: 50, height: 200)<br>        }</pre><pre>// 4.커스텀정렬 - 계산된 값을 반환하는 새로운 정렬 타입을 추가하기 위하여 VerticalAlignment나 HorizontalAlignment를 확장하여 사용.<br>// extension에 AlignmentID 프로토콜을 따르는 enum을 포함하고, defaultValue()라는 이름의 함수가 수현되도록 지시.<br>// 이 함수는 뷰에 대한 ViewDimensions 객체를 받아야 하며, 정렬 가이드 위치를 가리키는 계산된 GCFloat 값을 반환해야 한다.<br>extension VerticalAlignment {<br>    private enum OneThird : AlignmentID {<br>        static func defaultValue(in d: ViewDimensions) -&gt; CGFloat {<br>            return d.height / 3 // view 높이의 3분의 1 반환<br>        }<br>    }<br>    static let oneThird = VerticalAlignment(OneThird.self)<br>}</pre><ul><li>수행 결과</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*hVNUuPII7cXLQvfsdrB6Kg.png" /></figure><h4>5. 스택 정렬 교차</h4><pre>        // 5. 스택 정렬 교차<br>        // 표준 정렬 타입의 단점 -&gt; 스택 내의 뷰가 다른 스택에 있는 뷰와 정렬되도록 하는 방법을 제공하지 않는다.<br>        HStack(alignment: .crossAlignment, spacing: 20) {   // 중요! 서로 다른 스택에 포함된 뷰를 정렬하기 위해 사용<br>            // HStack 안에 VStack이 포함된 스택의 구성도. 원을 구성하는 뷰도 포함.<br>            Circle()<br>                .foregroundColor(Color .purple)<br>                .alignmentGuide(.crossAlignment, computeValue: { d in d[VerticalAlignment.center]})<br>                .frame(width: 100, height: 100)<br>            <br>            VStack(alignment: .center) {<br>                Rectangle()<br>                    .foregroundColor(Color .green)<br>                    .frame(width: 100, height: 100)<br>                Rectangle()<br>                    .foregroundColor(Color .red)<br>                    .frame(width: 100, height: 100)<br>                Rectangle()<br>                    .foregroundColor(Color .blue)<br>                    .alignmentGuide(.crossAlignment, computeValue: { d in d[VerticalAlignment.center]})<br>                    .frame(width: 100, height: 100)<br>                Rectangle()<br>                    .foregroundColor(Color .orange)<br>                    .frame(width: 100, height: 100)<br>            }<br>        }</pre><pre>// 5. 원을 사각형에 맞춰 정렬하기 위해 커스텀 정렬 수행<br>extension VerticalAlignment {<br>    private enum CrossAlignment : AlignmentID {<br>        static func defaultValue(in d: ViewDimensions) -&gt; CGFloat {<br>            return d[.bottom]<br>        }<br>    }<br>    static let crossAlignment = VerticalAlignment(CrossAlignment.self)<br>}</pre><ul><li>수행 결과</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*YDFyRHXBCePijHEX6MSZuw.png" /></figure><h4>6. ZStack 커스텀 정렬</h4><pre>        // 6. ZStack : 뷰가 겹치도록 각각 위로 쌓이는 구조<br>        // 표준 정렬 타입으로는 스택에 속한 모든 뷰의 정렬이 바뀐다. -&gt; 따라서 각 뷰가 자신만의 정렬을 갖도록하는 커스텀 뷰로 정렬.<br>        ZStack(alignment: .myAlignment) {<br>            Rectangle()<br>                .foregroundColor(Color .green)<br>//                .alignmentGuide(HorizontalAlignment.myAlignment) { d in d[.trailing] }<br>                .alignmentGuide(HorizontalAlignment.myAlignment) { d in d[.leading] }<br>                .alignmentGuide(VerticalAlignment.myAlignment) { d in d[VerticalAlignment.bottom] }<br>                .frame(width: 100, height: 100)<br>            Rectangle()<br>                .foregroundColor(Color .red)<br>//                .alignmentGuide(VerticalAlignment.myAlignment) { d in d[VerticalAlignment.top] }<br>//                .alignmentGuide(HorizontalAlignment.myAlignment) { d in d[HorizontalAlignment.center] }<br>                .alignmentGuide(VerticalAlignment.myAlignment) { d in d[VerticalAlignment.center] }<br>                .alignmentGuide(HorizontalAlignment.myAlignment) { d in d[HorizontalAlignment.trailing] }<br>                .frame(width: 100, height: 100)<br>            Circle()<br>                .foregroundColor(Color .orange)<br>                .alignmentGuide(HorizontalAlignment.myAlignment) { d in d[.leading] }<br>//                .alignmentGuide(VerticalAlignment.myAlignment) { d in d[.bottom] }<br>                .alignmentGuide(VerticalAlignment.myAlignment) { d in d[.top] }<br>                .frame(width: 100, height: 100)<br>        }</pre><pre>// 6. ZStack 커스텀 정렬 -&gt; ZStack의 하위 뷰를 수직/수평으로 정렬하는데 사용.<br>// 수평 커스텀 정렬과 수직 커스텀 정렬 모두가 하나의 커스텀 정렬로 결합되어야 함.<br>extension HorizontalAlignment {<br>    enum MyHorizontal: AlignmentID {<br>        static func defaultValue(in d: ViewDimensions) -&gt; CGFloat {<br>            d[HorizontalAlignment.center]<br>        }<br>    }<br>    static let myAlignment = HorizontalAlignment(MyHorizontal.self)<br>}<br><br>extension VerticalAlignment {<br>    enum MyVertical: AlignmentID {<br>        static func defaultValue(in d: ViewDimensions) -&gt; CGFloat {<br>            d[VerticalAlignment.center]<br>        }<br>    }<br>    static let myAlignment = VerticalAlignment(MyVertical.self)<br>}<br><br>extension Alignment {<br>    static let myAlignment = Alignment(horizontal: .myAlignment, vertical: .myAlignment)<br>}</pre><ul><li>수행 결과</li></ul><blockquote><em>주석 처리한 부분</em></blockquote><figure><img alt="주석 처리한 부분" src="https://cdn-images-1.medium.com/max/344/1*q1q468C2NLtGHxFKkb7YLg.png" /></figure><blockquote><em>뷰의 정렬 설정을 바꿔 응용해보기</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*cW5HCQekakIrEcmEtwSWew.png" /></figure><h4>정리</h4><p>• SwiftUI Stack Container View는 컨테이너를 기준으로 모든 하위 뷰의 위치를 조절하는 기본 정렬 설정을 이용하여 구성될 수 있다.</p><p>• 스택에 속한 개별 뷰의 정렬은 alignmentGuide를 사용하여 할 수 있다. AlignmentGuide는 ViewDimenstions 객체가 전달되는 클로저를 포함하며, ViewDimensions 객체는 뷰의 높이와 폭을 기준으로 뷰의 위치를 계산하는데 사용된다.</p><p>• 이러한 alignmentGuide는 스택 뷰 레이아웃을 선언할 때 표준 정렬과 동일한 방법으로 재사용될 수 있는 커스텀 정렬로 구현할 수도 있다.</p><p>• 커스텀 정렬은 서로 다른 스택에 포함된 뷰들이 서로 정렬되어야 하는 경우에 매우 유용하다.</p><p>• ZStack의 하위 뷰에 대한 커스텀 정렬은 HorizontalAlignmentGuide와 VerticalAlignmentGuide 모두가 필요하다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce4b157ce85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-5%EC%A3%BC%EC%B0%A8-ch24-4ce4b157ce85">iOS 스터디 5주차 Ch24</a> was originally published in <a href="https://medium.com/gdsc-tuk">GDSC TUK</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS 스터디 4주차 Ch22]]></title>
            <link>https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-4%EC%A3%BC%EC%B0%A8-ch22-b3c6bc716929?source=rss-5dd33e6287d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c6bc716929</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[iphone-app-development]]></category>
            <dc:creator><![CDATA[Chynmn]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 17:27:21 GMT</pubDate>
            <atom:updated>2022-11-13T17:27:21.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Xhr-X1kWwbrOwrBju-MqA.png" /></figure><blockquote>chapter 22. SwiftUI 예제 튜토리얼</blockquote><ol><li>프로젝트 생성 과정</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFc7TUI5S4GE0MFxv3VZXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynEoQ39PaAa--4085Islfg.png" /></figure><p>2. 프로젝트 생성 후 첫 화면</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toVMFM_aUzImbKeRaAIQ0w.png" /></figure><p>3. 컨테이너 뷰 사용하기</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*n9MwZU2Bs9vT1BUTtpiKqg.png" /></figure><p>Cmd 버튼을 누른상태에서 뷰 항목을 클릭하여 메뉴를 선택한다.</p><p>4. 슬라이더 뷰에 @State property 바인딩</p><pre>@State private var rotation: Double = 0 // 슬라이더와 바인딩을 하기 위함.<br><br>Slider(value: $rotation, in: 0...360, step: 0.1) // 뷰를 회전시킬 용도<br>    .padding()</pre><p>5. 회전과 애니메이션 추가</p><pre>Text(&quot;Hello, world!&quot;)<br>  .font(.largeTitle)<br>  .fontWeight(.heavy)<br>  .rotationEffect(.degrees(self.rotation))<br>  // 회전에 대한 상태 프로퍼티에 할당된 값을 읽는 것이므로 rotation프로퍼티 앞에 $를 붙이지 않음.<br>  .animation(.easeInOut(duration: 2))</pre><p>6. TextField 추가</p><pre>// Stack에 TextField 뷰 추가.<br>@State private var text: String = &quot;Welcome to SwiftUI&quot;<br><br><br>Text(text)<br>  .font(.largeTitle)<br>  .fontWeight(.heavy)<br>  .rotationEffect(.degrees(self.rotation))<br>  .animation(.easeInOut(duration: 2))<br><br><br>TextField(&quot;Enter text here&quot;, text: $text)<br>  // 사용자가 입력하는 텍스트가 저장될 상태 프로퍼티와 이 프로퍼티를 이용하여 Text 뷰를 변경함.<br>  .textFieldStyle(RoundedBorderTextFieldStyle())<br>  // 사용자가 TextField 뷰에 텍스트를 입려하면  text 상태 프로퍼티에 저장되고 바인딩에 의해 Text뷰에 자동으로 나타남.<br>  .padding()</pre><p>7. Picker 추가</p><pre>// Picker를 통해 Text뷰의 글자 색상을 사용자가 선택할 수 있게 하는 것.<br>var colors: [Color] = [.black, .red, .green, .blue] // 색상이름 배열 및 객체 배열<br>var colornames = [&quot;Black&quot;, &quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;]<br><br><br>@State private var colorIndex1 = 0   // 배열 인덱스 값을 저장하기 위한 상태 프로퍼티<br>@State private var colorIndex2 = 0<br><br>Text(text)<br>  .font(.largeTitle)<br>  .fontWeight(.heavy)<br>  .rotationEffect(.degrees(self.rotation))<br>  .animation(.easeInOut(duration: 2))<br>  // picker뷰에 선택된 값으로 포그라운드 색상을 설정<br>  .foregroundColor(self.colors[self.colorIndex2])  <br><br>Picker(selection: $colorIndex2, label: Text(&quot;Color&quot;)) {  // 사용자가 선택하는 기능.<br>  ForEach (0 ..&lt; colornames.count) {<br>    Text(self.colornames[$0])<br>      .foregroundColor(self.colors[$0])<br>    }<br>}</pre><p>8. padding과 Spacer로 레이아웃 정리 후 최종 결과물</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    // Picker를 통해 Text뷰의 글자 색상을 사용자가 선택할 수 있게 하는 것.<br>    var colors: [Color] = [.black, .red, .green, .blue] // 색상이름 배열 및 객체 배열<br>    var colornames = [&quot;Black&quot;, &quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;]<br>    <br>    @State private var colorIndex1 = 0   // 배열 인덱스 값을 저장하기 위한 상태 프로퍼티<br>    @State private var colorIndex2 = 0<br>    @State private var rotation: Double = 0 // 슬라이더와 바인딩을 하기 위함.<br>    @State private var text: String = &quot;Welcome to SwiftUI&quot;  // Stack에 TextField 뷰 추가.<br>    <br>    var body: some View {<br>        VStack {<br>            Spacer()<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundColor(.accentColor)<br>            <br>            VStack {<br>                Spacer()<br>                Text(&quot;Hello, world!&quot;)<br>                    .font(.largeTitle)<br>                    .fontWeight(.heavy)<br>                    .rotationEffect(.degrees(self.rotation))<br>                // 회전에 대한 상태 프로퍼티에 할당된 값을 읽는 것이므로 프로퍼티 앞에 $를 붙이지 않음.<br>                    .animation(.easeInOut(duration: 2))<br>                    .foregroundColor(self.colors[self.colorIndex1])<br>                Spacer()<br>                <br>                Picker(selection: $colorIndex1, label: Text(&quot;Color&quot;)) {  // 사용자가 선택하는 기능.<br>                    ForEach (0 ..&lt; colornames.count) {<br>                        Text(self.colornames[$0])<br>                            .foregroundColor(self.colors[$0])<br>                    }<br>                }<br>                Spacer()    // 뷰간 간격 맞춤 기능<br>                Divider()   // 뷰를 구분하기 위한 라인<br>                <br>                Slider(value: $rotation, in: 0...360, step: 0.1) // 뷰를 회전시킬 용도<br>                    .padding()<br>                <br>                Text(text)<br>                    .font(.largeTitle)<br>                    .fontWeight(.heavy)<br>                    .rotationEffect(.degrees(self.rotation))<br>                    .animation(.easeInOut(duration: 2))<br>                    .foregroundColor(self.colors[self.colorIndex2])<br>                    .padding()<br>                <br>                TextField(&quot;Enter text here&quot;, text: $text)<br>                // 사용자가 입력하는 텍스트가 저장될 상태 프로퍼티와 이 프로퍼티를 이용하여 Text 뷰를 변경함.<br>                    .textFieldStyle(RoundedBorderTextFieldStyle())<br>                // 사용자가 TextField 뷰에 텍스트를 입려하면  text 상태 프로퍼티에 저장되고 바인딩에 의해 Text뷰에 자동으로 나타남.<br>                    .padding()<br>                <br>                Picker(selection: $colorIndex2, label: Text(&quot;Color&quot;)) {  // 사용자가 선택하는 기능.<br>                    ForEach (0 ..&lt; colornames.count) {<br>                        Text(self.colornames[$0])<br>                            .foregroundColor(self.colors[$0])<br>                    }<br>                }<br>                .padding()<br>            }<br>        }<br>        .padding()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*bDPriXPlUouCjk3QfzWn8w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c6bc716929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-4%EC%A3%BC%EC%B0%A8-ch22-b3c6bc716929">iOS 스터디 4주차 Ch22</a> was originally published in <a href="https://medium.com/gdsc-tuk">GDSC TUK</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS 스터디 3주차 Ch11 ~13]]></title>
            <link>https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-3%EC%A3%BC%EC%B0%A8-ch11-13-9994ecd86a0c?source=rss-5dd33e6287d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9994ecd86a0c</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chynmn]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 18:15:55 GMT</pubDate>
            <atom:updated>2022-11-03T12:20:50.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNd1ppioW3gVv-VsFtegyQ.png" /></figure><h4>chapter 11. Swift 서브클래싱과 익스텐션의 개요</h4><blockquote>상속, 클래스, 하위 클래스</blockquote><p>상속을 통해서 class에 특성을 정의할 수 있게 하고, class를 상속받은 다른 class를 생성할 수 있게 한다. 상속된 클래스는 부모 클래스의 모든 기능을 상속받으며 자신만의 기능을 추가한다.</p><p>class 상속을 통해 class hierarchy를 만든다. 최상위 클래스를 base class 또는 root class라고 부르고, 상속받은 클래스를 subclass 또는 child class라고 부르며, 상속해준 클래스를 super class 또는 parent class라고 부른다. swift의 subclass는 반드시 단 한 개의 부모 클래스만 둘 수 있는데 이것을 single inheritance(단일 상속)이라 한다.</p><p>상속을 통해 새로운 클래스가 기존의 클래스로 부터 파생되어 새로운 기능이 추가되도록 하는 방법으로 객체지향 프로그래밍의 객체 재사용성 개념을 확장시킨다.</p><pre>// 상속해준 상위 클래스<br>BankAccount 클래스 뿐만 아니라 저축 계좌 클래스를 선언할 것. -&gt; 계좌, 잔고 및 데이터 접근 메서드 필요. 따라서 BankAccount 클래스의 하위 클래스로 저축 계좌 클래스를 선언.</pre><pre><strong>class</strong> BankAccount {<br>   <strong>var</strong> accountBalance: Float<br>   <strong>var</strong> accountNumber: Int</pre><pre><strong>   init</strong>(number: Int, balance: Float) {<br>       accountNumber = number<br>       accountBalance = balance<br>   }   // SavingsAccount 클래스에 상속</pre><pre><strong>   func</strong> displayBalance() {<br>       print(&quot;Number \(accountNumber)&quot;)<br>       print(&quot;Current balance is \(accountBalance)&quot;)<br>   }<br>}<br></pre><pre>// 상속받은 하위 클래스<br><strong>class</strong> SavingsAccount: BankAccount { <br>// BankAccount 클래스의 모든 메서드와 프로퍼티를 상속받았음<br>   <strong>var</strong> interestRate: Float = 0.0</pre><pre>// 하위 클래스 초기화하기 -&gt; 이자율을 초기화하는 작업을 통해 부모 클래스의 init 메서드를 호출하여 모든 변수가 초기화되도록 한다. -&gt; 하위 클래스의 인스턴스가 생성될 때 프로퍼티가 초기화되도록 해야 한다.</pre><pre><strong>   init</strong>(number: Int, balance: Float, rate: Float) { <br>   // 이자율에 대한 이자율 변수.<br>       interestRate = rate<br>       <strong>super</strong>.<strong>init</strong>(number: number, balance: balance)//상위 클래스에서 호출<br>   } <br>// 초기화 과정에서 발생 할 수 있는 잠재적 문제를 피하기 위해 상위 클래스의 init 메서드는 항상 하위 클래스의 초기화 작업이 완료된 후에 호출되도록 해야 한다.<br>  <br>   <strong>func</strong> calculateInterest() -&gt; Float {<br>      <strong>return</strong> interestRate * accountBalance    <br>      // 상위 클래스에서 상속받은 프로퍼티 사용함.<br>   }</pre><pre>/* <br>상속받은 메서드 오버라이딩 : 상속받은 기능을 수정을 통해 필요로 하는 기능으로써 사용하기 위함. method override를 통해 하위 클래스 내에 새로운 버전의 메서드를 만든다.</pre><pre>메서드 오버라이딩의 두 가지 규칙 :<br>1. 하위 클래스의 오버라이딩 메서드는 오버라이딩되는 상위 클래스 메서드의 매개변수 개수와 타입이 정확하게 일치해야 한다.<br>2. 새롭게 오버라이딩하는 메서드는 반드시 부모클래스 메서드가 반환하는 타입과 일치해야한다.<br>하위 클래스에서 오버라이드된 상위 클래스의 메서드를 호출 할 수 있다.<br>*/</pre><pre>// 계좌번호와 잔고를 표시하는 메서드 + 계좌에 할당된 이자율<br>    <strong>override</strong> <strong>func</strong> displayBalance() {    <br>//        print(&quot;Number \(accountNumber)&quot;)<br>//        print(&quot;Current balance is \(accountBalance)&quot;)</pre><pre><strong>    super</strong>.displayBalance()          <br>// 상위 클래스의 메서드를 호출함으로써 코드의 중복을 없앨 수 있다.<br>        print(&quot;Prevailing interest rate is \(interestRate)&quot;)<br>   }<br>}</pre><pre>// 하위 클래스 사용<br><strong>let</strong> savings1 = SavingsAccount(number: 12311, <br>balance: 600.00, rate: 0.07)<br>print(savings1.calculateInterest())<br>savings1.displayBalance()</pre><blockquote>Extension을 이용해 swift class에 하위 클래스를 생성하거나 참조하지 않고 기존 클래스에 메서드, 초기화, 연산 프로퍼티, 서브스크립트 등의 새로운 기능을 추가할 수 있다.</blockquote><p>특히, swift언어와 iOS SDK 프레임워크에 내장된 클래스에 기능을 추가할 때 익스텐션을 이용하면 매우 효과적이다.</p><pre>/*<br>extension ClassName {<br>   // Extension을 이용해 클래스에 새로운 기능을 추가한다.<br>}<br>*/</pre><pre><strong>extension</strong> Double {  // 연산 프로퍼티 확장<br>   <strong>var</strong> squared: Double {   // 제곱<br>      <strong>return</strong> <strong>self</strong> * <strong>self<br>   </strong>}<br>   <br>   <strong>var</strong> cubed: Double {     // 세제곱<br>      <strong>return</strong> <strong>self</strong> * <strong>self</strong> * <strong>self<br>   </strong>}<br>}</pre><pre><strong>let</strong> myValue: Double = 3.0   <br>// 상수를 선언할 때 Double형으로 선언하여 익스텐션 프로퍼티를 사용했다.<br>print(myValue.squared)</pre><pre>print(3.0.squared)      <br>// 하위 클래스를 사용하는 것이 아니라 익스텐션으로 추가된 것이므로, Double값에서 프로퍼티에 직접 접근 가능<br>print(6.0.cubed)<br></pre><p>분명 익스텐션은 하위 클래스를 사용하지 않고 클래스의 기능을 확장할 수 있는 빠르고 편리한 방식을 제공하지만,</p><p>익스텐션을 이용해서는 클래스에 있는 기존의 기능을 오버라이드 할 수 없으며, 익스텐션에는 저장 프로퍼티를 포함할 수도 없다는 점에서 하위 클래스가 익스텐션보다 좋은 장점도 있다.</p><h4>chapter 12. Swift 구조체</h4><blockquote>구조체 사용법과 클래스와 구조체의 차이점, 값 타입과 참조 타입 개념 이해</blockquote><h4>공통점</h4><p>1. property 정의, value 저장, method 정의할 수 있는 객체 생성 메커니즘을 제공.</p><p>2. 데이터와 기능을 재사용할 수 있는 객체로 캡슐화하는 방법을 제공한다.</p><p>3. 구조체도 클래스처럼 확장이 가능하며, 프로토콜을 채택하거나 초기화를 가질 수 있다.</p><h4><strong>차이점</strong></h4><ol><li>struct 키워드를 사용한다.</li></ol><p>2. 구조체 인스턴스의 타입은 value type, 클래스 인스턴스의 타입은 reference type.</p><p>3. 구조체는 클래스의 상속이나 하위클래스를 지원하지 않는다.</p><p>4. 구조체는 소멸자 메서드(deinit)를 포함할 수 없다.</p><p>5. 런타임에서 클래스 인스턴스의 유형을 식별할 수 있지만 구조체는 그렇지 않다.</p><h4>결론</h4><p>일반적으로 구조체가 클래스보다 효율적이고 멀티 스레드 코드를 사용하는데 더 안정적이기 때문에 가능하다면 구조체를 사용하는 것을 권장.</p><p>그러나, 상속이 필요하거나 데이터가 캡슐화된 하나의 인스턴스가 필요한 때, 인스턴스가 소멸될 때 리소스를 확보하기 위한 작업이 필요할 때 클래스를 사용해야 함.</p><pre><strong>struct</strong> SampleStruct {   <br>// String변수, 초기화, 메서드로 구성. class 키워드를 사용하는 것을 제외하면 선언부는 동일함.<br>   <strong>var</strong> name: String</pre><pre><strong>   init</strong>(name: String) {<br>      <strong>self</strong>.name = name<br>   }<br>}</pre><pre>// 인스턴스를 생성할 때도 동일한 구문을 사용<br><strong>let</strong> myStruct = SampleStruct(name: &quot;Mark1&quot;)<br><strong>let</strong> myClass = SampleClass(name: &quot;Mark2&quot;)</pre><pre>print(myStruct.name)<br>print(myClass.name)</pre><pre><strong>let</strong> myStruct1 = SampleStruct(name: &quot;Mark45&quot;)<br><strong>var</strong> myStruct2 = myStruct1</pre><pre>myStruct2.name = &quot;David&quot;<br>print(myStruct1.name)<br>print(myStruct2.name)   <br>// myStruct2는 myStruct1의 복사본이므로 자신만의 데이터를 갖게 된다.</pre><p>-&gt; 구조체 인스턴스가 복사되거나 메서드에 전달될 때 인스턴스의 복사본은 원본 객체가 가지고 있던 모든 데이터를 복사하기 때문에 원본 구조체 인스턴스와 별개인 자신만의 데이터를 가진다. 따라서 하나의 인스턴스를 변경해도 다른 복사본들에 영향을 미치지 않는다.</p><p>-&gt; 클래스 인스턴스가 복사되거나 인자로 전달되면 해당 클래스 인스턴스가 있는 메모리의 위치에 대한 참조체가 생성되거나 전달되고 참조체를 변경하면 원본 인스턴스에도 동일한 작업이 수행된다. 따라서 단 하나의 클래스 인스턴스가 있고 그 인스턴스를 가리키는 여러 개의 참조체가 존재하므로 참조체들 중 하나를 이용하여 인스턴스 데이터를 변경하면 모든 참조체 데이터가 변경된다.</p><pre>// 클래스와 비교<br><strong>class</strong> SampleClass {<br>   <strong>var</strong> name: String</pre><pre><strong>   init</strong>(name: String) {<br>      <strong>self</strong>.name = name<br>   }<br>}</pre><pre><strong>let</strong> myClass1 = SampleClass(name: &quot;Mark98&quot;)<br><strong>var</strong> myClass2 = myClass1</pre><pre>myClass2.name = &quot;David2&quot;<br>print(myClass1.name)<br>print(myClass2.name)    <br>// 동일한 클래스 인스턴스에 대한 참조체들이므로 name property를 변경함으로써 myClass1와 myClass2 모두에 영향을 미치게 된다.</pre><h4>chapter 13. Swift Property Wrapper</h4><blockquote>property wrapper는 클래스와 구조체 구현부에 getter, setter, computed property 코드의 중복을 줄이는 방법을 제공.</blockquote><blockquote>property wrapper는 연산 프로퍼티의 기능을 개별 클래스와 구조체와 분리할 수 있게하며, 앱 코드에서 재사용할 수 있게 한다.</blockquote><blockquote>iOS SDK로 작업을 할 때 미리 정의된 프로퍼티 래퍼를 SwiftUI에서 주로 사용한다.</blockquote><pre>// 도시 이름을 저장하는 String property를 가진 구조체 예제<br><strong>struct</strong> Address {<br>   <strong>private</strong> <strong>var</strong> cityname: String = &quot;&quot;</pre><pre><strong>   var</strong> city: String {  <br>// 도시 이름을 입력에 상관없이 대문자로 저장하기 위한 연산 프로퍼티<br>      <strong>get</strong> { cityname }<br>      <strong>set</strong> { cityname = newValue.uppercased() }<br>   }<br>}</pre><pre><strong>var</strong> address = Address()<br>address.city = &quot;London&quot;</pre><pre>print(address.city)     <br>// setter가 private cityname 변수에 값을 저장하기 전에 대문자로 변환.</pre><pre>// 연산 프로퍼티를 사용하는 대신에 로직을 래퍼로 구현할 수 있다.<br>// 문자열을 대문자로 변환하도록 설계된 FixCase 프로퍼티 래퍼 선언.<br><strong>@propertyWrapper<br>struct</strong> FixCase {<br>   <strong>private</strong>(<strong>set</strong>) <strong>var</strong> value: String = &quot;&quot;</pre><pre><strong>   var</strong> wrappedValue: String {  <br>// 모든 property wrapper는 값을 변경하거나 유효성을 검사하는 게터와 세터 코드가 포함된 wrappedValue property를 가져야 한다.</pre><pre><strong>      get</strong> { value }</pre><pre><strong>      set</strong> { value = newValue.uppercased() }   <br>// 초깃값을 문자열을 대문자로 변환하고 private 변수에 저장하는 wrappedValue 프로퍼티에 할당.<br>   }</pre><pre><strong>   init</strong>(wrappedValue initialValue: String) {   <br>// 초깃값이 전달되는 초기화 메서드는 선택사항으로 포함.<br>       <strong>self</strong>.wrappedValue = initialValue<br>   }<br>}</pre><pre><strong>struct</strong> Contact {    <br>// 동일한 동작이 필요한 다른 프로퍼티 변수에 적용하여 재사용한다. propertyWrapper를 사용하기 위해 클래스나 구조체의 선언부에 있는 프로퍼티 선언 앞에 @FixCase 지시자를 붙인다.<br>    @FixCase <strong>var</strong> name: String   <br>    @FixCase <strong>var</strong> city: String<br>    @FixCase <strong>var</strong> country: String<br>}</pre><pre><strong>var</strong> contact = Contact(name: &quot;John Smith&quot;, city: &quot;London&quot;, country: &quot;United Kingdom&quot;)<br>print(&quot;\(contact.name), \(contact.city), \(contact.country)&quot;)</pre><blockquote>property wrapper를 사용해 여러 값을 받도록 구현.</blockquote><pre><strong>@propertyWrapper<br>struct</strong> MinMaxVal_INT {     // Int값만 가지는 프로퍼티 래퍼<br>   <strong>var</strong> value: Int<br>   <strong>let</strong> max: Int<br>   <strong>let</strong> min: Int<br> <br>   <strong>init</strong>(wrappedValue: Int, min: Int, max: Int) {   <br>// wrapper 값에 추가된 min과 max 값을 받아서 구현된다.<br>      value = wrappedValue<br>      <strong>self</strong>.min = min<br>      <strong>self</strong>.max = max<br>   }</pre><pre><strong>   var</strong> wrappedValue: Int {<br>      <strong>get</strong> { <strong>return</strong> value }<br>      <strong>set</strong> {// 값이 특정 범위 안에 있는지를 검사하여 그 값을 min or max에 할당한다.<br>         <strong>if</strong> newValue &gt; max {<br>             value = max<br>         } <strong>else</strong> <strong>if</strong> newValue &lt; min {<br>             value = min<br>         } <strong>else</strong> {<br>             value = newValue<br>         }<br>      }<br>   }<br>}</pre><pre>// 지정된 값으로 사용하도록 설계된 프로퍼티 래퍼의 형태. 추가되는 값들을 괄호 안에 둔다.<br><strong>struct</strong> Demo {<br>   @MinMaxVal_INT(min: 100, max: 200) <strong>var</strong> value: Int = 100<br>}</pre><pre><strong>var</strong> demo = Demo()<br>demo.value = 150    // 최댓값의 허용범위 안에 있으므로 150을 정상적으로 출력print(demo.value)</pre><pre>demo.value = 250    // 최댓값의 허용범위인 200을 초과하여 200을 출력print(demo.value)</pre><p>동일한 타입의 다른 값과 비교할 수 있는 모든 변수 타입과 함께 사용할 수 있도록 property wrapper는 특정 protocol을 따르는 모든 타입과 작업하도록 구현할 수 있다.</p><p>프로퍼티 래퍼의 목적은 비교 작업을 하는것이므로, Foundation 프레임워크에 포함된 Comparable 프로토콜을 따르는 모든 데이터 타입을 지원하도록 수정해야 한다.</p><p>Comparable 프로토콜을 따르는 타입은 값의 크기를 비교하는데 사용될 수 있다.</p><pre>// Comparable 프로토콜을 따르는 모든 타입에 사용될 수 있도록 property wrapper 구현하기 위해 위의 예제의 선언부를 수정.</pre><pre><strong>@propertyWrapper<br>struct</strong> MinMaxVal_ALL&lt;V: Comparable&gt; {   // String, Int, Date, DateInterval, Character등이 Comparable protocol을 따른다.<br>   <strong>var</strong> value: V<br>   <strong>let</strong> max: V<br>   <strong>let</strong> min: V</pre><pre><strong>   init</strong>(wrappedValue: V, min: V, max: V) {   <br>       // wrapper 값에 추가된 min과 max 값을 받아서 구현된다.<br>       value = wrappedValue<br>       <strong>self</strong>.min = min<br>       <strong>self</strong>.max = max<br>   }<br>   <br>   <strong>var</strong> wrappedValue: V {<br>      <strong>get</strong> { <strong>return</strong> value }<br>      <strong>set</strong> {// 값이 특정 범위 안에 있는지를 검사하여 그 값을 min or max에 할당한다.<br>         <strong>if</strong> newValue &gt; max {<br>            value = max<br>         } <strong>else</strong> <strong>if</strong> newValue &lt; min {<br>            value = min<br>         } <strong>else</strong> {<br>            value = newValue<br>         }<br>      }<br>   }<br>}</pre><pre>// String 문자열 값이 알파벳 사전 관점에서 최솟값과 최댓값 범위 안에 들어오는지를 판단.<br><strong>struct</strong> StringDemo {<br>  @MinMaxVal_ALL(min: &quot;Apple&quot;, max: &quot;Orange&quot;) <strong>var</strong> value: String = &quot;&quot;<br>}</pre><pre><strong>var</strong> Stringdemo = StringDemo()<br>Stringdemo.value = &quot;Banana&quot; //주어진 알파벳 범위 내에 있어서 정상적으로 저장.<br>print(Stringdemo.value)</pre><pre>Stringdemo.value = &quot;Watermelon&quot;  <br>// 주어진 알파벳 범위 밖이므로 지정한 최댓값인 Orange가 저장print(Stringdemo.value)</pre><pre>// Date 객체로 동작하는 래퍼. 현재 날짜와 한 달 후 날짜 사이의 데이터로 제한.<br><strong>struct</strong> DateDemo {<br>    @MinMaxVal_ALL(min: Date(), max: Calendar.current.date(byAdding: .month, value: 1, to: Date())! ) <strong>var</strong> value: Date = Date()<br>}</pre><pre><strong>var</strong> dateDemo = DateDemo()</pre><pre>print(dateDemo.value)   // Default로 현재 날짜가 프로퍼티에 설정</pre><pre>dateDemo.value = Calendar.current.date(byAdding: .day, value: 10, to: Date())!  // 10일 후의 날짜를 프로퍼티에 설정<br>print(dateDemo.value)</pre><pre>dateDemo.value = Calendar.current.date(byAdding: .month, value: 2, to: Date())! // 2달 후의 날짜를 프로퍼티에 설정<br>print(dateDemo.value)   <br>// 유효 범위가 현재 날짜에서 1달 후 까지이므로 프로퍼티에는 최댓값인 1달 후가 저장된다.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9994ecd86a0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gdsc-tuk/ios-%EC%8A%A4%ED%84%B0%EB%94%94-3%EC%A3%BC%EC%B0%A8-ch11-13-9994ecd86a0c">iOS 스터디 3주차 Ch11 ~13</a> was originally published in <a href="https://medium.com/gdsc-tuk">GDSC TUK</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>