<?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 gaeng2y on Medium]]></title>
        <description><![CDATA[Stories by gaeng2y on Medium]]></description>
        <link>https://medium.com/@gaeng2y?source=rss-6c83e1283199------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zjK-QDEeTUlL6ZLYy0OLxg.jpeg</url>
            <title>Stories by gaeng2y on Medium</title>
            <link>https://medium.com/@gaeng2y?source=rss-6c83e1283199------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:16:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaeng2y/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[[SwiftUI] @ScaledMetric]]></title>
            <link>https://gaeng2y.medium.com/swiftui-scaledmetric-1c129f4d305c?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c129f4d305c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 03:35:17 GMT</pubDate>
            <atom:updated>2026-08-19T03:35:17.536Z</atom:updated>
            <content:encoded><![CDATA[<p>안녕하세요.. 매 주 돌아온다면 3개월만에 기어나온 저입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*AJfbzf7eXaKr_zkX" /></figure><p>빠르게 본론으로 들어가겠습니다.</p><p>다이내믹 타입을 적용한 화면에서 글자만 커지고 아이콘은 그대로인 경우가 있습니다.</p><p>SwiftUI의 Text는 사용자가 설정한 글자 크기에 맞춰 자동으로 변합니다. 반면 이미지 크기나 여백, 프레임을 고정된 숫자로 지정하면 그<br> 값은 바뀌지 않습니다. 큰 글자 설정에서 텍스트와 아이콘의 비율이 어색해지는 이유입니다.</p><p>이럴 때 쓸 수 있는 것이 <a href="http://twitter.com/ScaledMetric">@ScaledMetric</a>입니다.</p><h3>@ScaledMetric은 무엇을 바꿀까?</h3><p><a href="http://twitter.com/ScaledMetric">@ScaledMetric</a>은 CGFloat, Double 같은 수치를 사용자의 글자 크기 설정에 맞춰 조절하는 프로퍼티 래퍼입니다.</p><p>아이콘 크기나 레이아웃 값에 적용하면 텍스트가 커질 때 해당 값도 함께 커집니다. 텍스트가 아닌 요소도 다이내믹 타입에 맞춰 조절하고 싶을 때 유용합니다.</p><h4>간단한 사용 예제</h4><p>프로필 아이콘과 이름을 나란히 보여주는 화면을 만들어 보겠습니다.</p><pre>import SwiftUI<br><br>struct ProfileCardView: View {<br>  @ScaledMetric var iconSize: CGFloat = 50<br>  <br>  var body: some View {<br>    HStack(spacing: 16) {<br>      Image(systemName: &quot;person.circle.fill&quot;)<br>        .resizable()<br>        .foregroundColor(.blue)<br>        .frame(width: iconSize, height: iconSize)<br><br>      Text(&quot;iOS 개발자&quot;)<br>        .font(.headline)<br>      <br>      Spacer()<br>    }<br>    .padding()<br>    .background(Color.gray.opacity(0.1))<br>    .cornerRadius(12)<br>  }<br>}<br><br>#Preview {<br>  VStack(spacing: 20) {<br>    ProfileCardView()<br>      .dynamicTypeSize(.medium)<br>    ProfileCardView()<br>      .dynamicTypeSize(.accessibility3)<br>  }<br>  .padding()<br>}</pre><p>핵심은 아래 한 줄입니다.</p><p><a href="http://twitter.com/ScaledMetric">@ScaledMetric</a> var iconSize: CGFloat = 50</p><p>기본 크기는 50이지만, 사용자가 글자 크기를 키우면 iconSize도 함께 커집니다.</p><p>이 값을 이미지의 frame에 사용했기 때문에 프로필 아이콘 역시 글자 크기 설정을 따라갑니다.</p><p>Preview에서는 .dynamicTypeSize()를 이용해 결과를 비교할 수 있습니다.</p><p>.medium과 .accessibility3을 각각 적용하면 텍스트와 아이콘의 크기가 함께 달라지는 모습을 바로 확인할 수 있습니다.</p><h3>특정 텍스트 스타일을 기준으로 맞추기</h3><p>본문과 큰 제목은 크기가 변하는 비율이 다릅니다. 특정 텍스트 스타일을 기준으로 값을 조절하고 싶다면 relativeTo를 지정하면 됩니다.</p><p><a href="http://twitter.com/ScaledMetric">@ScaledMetric</a>(relativeTo: .largeTitle)<br> var headerHeight: CGFloat = 100</p><p>위의 headerHeight는 .largeTitle의 크기 변화에 맞춰 조절됩니다.</p><p>접근성을 챙기면 더 많은 사용자가 앱을 편하게 사용할 수 있습니다. 큰 글자 설정에서 화면 비율이 어색하다면 아이콘이나 레이아웃에 사용한 고정값부터 확인해 보세요.</p><p>그 값이 텍스트와 함께 변해야 한다면 <a href="http://twitter.com/ScaledMetric">@ScaledMetric</a>이 간단한 해결책이 될 수 있습니다.</p><h3>참고</h3><p><a href="https://developer.apple.com/documentation/swiftui/scaledmetric">https://developer.apple.com/documentation/swiftui/scaledmetric</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c129f4d305c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LinkNavigator에서 이전 화면으로 이벤트 전달하기]]></title>
            <link>https://gaeng2y.medium.com/linknavigator%EC%97%90%EC%84%9C-%EC%9D%B4%EC%A0%84-%ED%99%94%EB%A9%B4%EC%9C%BC%EB%A1%9C-%EC%9D%B4%EB%B2%A4%ED%8A%B8-%EC%A0%84%EB%8B%AC%ED%95%98%EA%B8%B0-35c6f7a3c784?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c6f7a3c784</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Tue, 19 May 2026 04:50:43 GMT</pubDate>
            <atom:updated>2026-05-19T04:50:43.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGnpeyrqRf7wBU0a" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>안녕하세요! 매 주 돌아온다고 말하던 그는 5월이 되어서야 기어왔습니다…</p><p>오늘은 업무 중에 알게된 내용에 대해 포스팅하도록 하려고 합니다!</p><p>현재 회사 프로젝트에서 내비게이션을 <a href="https://github.com/forXifLess/LinkNavigator">LinkNavigator</a>를 사용하고 있습니다.</p><p>iOS 앱에서 화면 전환을 구현하다 보면 단순히 “다음 화면으로 이동”하는 것만으로 끝나지 않는 경우가 많죠…</p><p>예를 들어 다음과 같은 상황이 있습니다.</p><pre>A 화면 -&gt; B 화면으로 이동<br>B 화면에서 특정 액션 발생<br>A 화면이 그 이벤트를 받아서 상태 갱신</pre><p>대표적인 예시는 다음과 같습니다.</p><ul><li>B 화면에서 항목을 선택하면 A 화면의 리스트를 갱신한다.</li><li>B 화면에서 저장을 완료하면 A 화면에 Toast를 띄운다.</li><li>B 화면에서 설정을 변경하면 A 화면의 ViewModel에 반영한다.</li><li>B 화면에서 완료 이벤트를 발생시키고 A 화면이 후속 액션을 수행한다.</li></ul><p>UIKit 기반이라면 delegate, closure, NotificationCenter, Combine Subject 등 여러 방식이 있겠지만 LinkNavigator를 사용하고 있다면, 이미 제공되는 eventSubscriber를 활용해서 화면 간 이벤트 전달을 처리할 수 있습니다.</p><h3>eventSubscriber는 무엇인가?</h3><p>LinkNavigator의 WrappingController는 SwiftUI View를 감싸는 UIHostingController 역할을 합니다.</p><p>이 컨트롤러는 matchPath와 eventSubscriber를 가지고요.</p><p>실제 구조는 다음과 같습니다.</p><pre>public final class WrappingController&lt;Content: View&gt;: UIHostingController&lt;Content&gt;, MatchPathUsable {<br><br>  public init(<br>    matchPath: String,<br>    title: String? = .none,<br>    eventSubscriber: LinkNavigatorItemSubscriberProtocol? = .none,<br>    @ViewBuilder content: () -&gt; Content<br>  ) {<br>    self.matchPath = matchPath<br>    self.eventSubscriber = eventSubscriber<br>    super.init(rootView: content())<br>    super.title = title ?? matchPath<br>  }<br><br>  public let matchPath: String<br>  public let eventSubscriber: LinkNavigatorItemSubscriberProtocol?<br>}</pre><p>즉, 각 화면은 matchPath로 식별되고, 선택적으로 eventSubscriber를 가질 수 있습니다. eventSubscriber가 따라야 하는 프로토콜은 매우 단순하죠.</p><pre>public protocol LinkNavigatorItemSubscriberProtocol {<br>  func receive(encodedItemString: String)<br>}</pre><p>화면 간 전달되는 데이터는 encodedItemString 형태로 넘어옵니다.</p><h3>문제 상황: B에서 A로 이벤트를 보내고 싶다</h3><p>상황을 이렇게 가정해보자.</p><pre>A 화면에서 B 화면으로 next<br>B 화면에서 저장 완료<br>A 화면은 저장 완료 이벤트를 받아 리스트를 reload</pre><p>흐름은 다음과 같습니다.</p><pre>A -&gt; B<br>B에서 이벤트 발생<br>B -&gt; navigator.send(...)<br>A의 eventSubscriber.receive(...)<br>AViewModel reload</pre><p>핵심은 <strong>B가 직접 A를 참조하지 않는다는 점</strong>입니다.<br>B는 단지 LinkNavigator를 통해 특정 path로 이벤트를 보내고 A는 자신의 eventSubscriber를 통해 그 이벤트를 수신하죠.</p><h3>A 화면에 Subscriber 붙이기</h3><p>먼저 A 화면에서 사용할 subscriber를 선언합니다.</p><pre>final class AEventSubscriber: LinkNavigatorItemSubscriberProtocol {<br>  private let viewModel: AViewModel<br><br>  init(viewModel: AViewModel) {<br>    self.viewModel = viewModel<br>  }<br><br>  func receive(encodedItemString: String) {<br>    viewModel.handleEventFromB(encodedItemString)<br>  }<br>}</pre><p>여기서 중요한 점은 subscriber가 View 자체를 직접 변경하지 않는다는 것입니다.<br>SwiftUI View를 직접 조작하기보다는 ViewModel에 이벤트를 전달하고, View는 상태 변화를 관찰해서 갱신되는 구조가 더 자연스럽다.</p><pre>B -&gt; navigator.send(...)<br>  -&gt; AEventSubscriber.receive(...)<br>  -&gt; AViewModel.handleEventFromB(...)<br>  -&gt; AView 갱신</pre><h3>A RouteBuilder에서 eventSubscriber 주입하기</h3><p>A 화면을 만드는 RouteBuilder에서 WrappingController에 subscriber를 넘긴다.</p><pre>struct ARouteBuilder: RouteBuilder {<br>  var matchPath: String { &quot;a&quot; }<br><br>  func build(<br>    navigator: LinkNavigatorType,<br>    item: String,<br>    dependency: DependencyType<br>  ) -&gt; MatchingViewController? {<br>    let viewModel = AViewModel()<br>    let subscriber = AEventSubscriber(viewModel: viewModel)<br><br>    return WrappingController(<br>      matchPath: matchPath,<br>      eventSubscriber: subscriber<br>    ) {<br>      AView(<br>        navigator: navigator,<br>        viewModel: viewModel<br>      )<br>    }<br>  }<br>}</pre><p>이제 A 화면은 &quot;a&quot;라는 matchPath를 가진다. 그리고 &quot;a&quot; path로 이벤트가 전달되면 AEventSubscriber가 받을 수 있다.</p><h3>B 화면에서 A로 이벤트 보내기</h3><p>이제 B 화면에서 특정 이벤트가 발생했을 때 navigator.send(...)를 호출한다.</p><pre>navigator.send(<br>  item: .init(<br>    pathList: [&quot;a&quot;],<br>    items: [<br>      &quot;event&quot;: &quot;didCompleteSave&quot;,<br>      &quot;id&quot;: &quot;123&quot;<br>    ]<br>  )<br>)</pre><p>여기서 pathList에 &quot;a&quot;를 넣는 것이 핵심이다. LinkNavigator는 현재 navigation stack에 있는 view controller 중 matchPath가 &quot;a&quot;인 화면을 찾고, 그 화면의 eventSubscriber를 호출한다.</p><p>실제 send(item:) 구현도 이 흐름과 일치한다.</p><pre>public func send(item: LinkItem) {<br>  activeController?.viewControllers<br>    .compactMap { $0 as? MatchPathUsable }<br>    .filter { matchPathUsable in item.pathList.contains(matchPathUsable.matchPath) }<br>    .compactMap { $0 }<br>    .forEach {<br>      $0.eventSubscriber?.receive(encodedItemString: item.encodedItemString)<br>    }<br>}</pre><p>즉, 현재 active navigation stack 안에서 MatchPathUsable을 찾고, pathList에 포함된 matchPath를 가진 화면의 subscriber로 이벤트를 전달합니다.</p><h3>전체 흐름 정리</h3><p>전체 흐름은 다음과 같다.</p><pre>A 화면 생성<br>- matchPath: &quot;a&quot;<br>- eventSubscriber: AEventSubscriber<br><br>A -&gt; B로 next<br><br>B에서 이벤트 발생<br><br>B에서 호출:<br>navigator.send(<br>  item: .init(<br>    pathList: [&quot;a&quot;],<br>    items: [<br>      &quot;event&quot;: &quot;didCompleteSave&quot;<br>    ]<br>  )<br>)<br><br>LinkNavigator가 현재 stack에서 matchPath == &quot;a&quot;인 controller 탐색<br><br>AEventSubscriber.receive(encodedItemString:)<br><br>AViewModel 액션 수행</pre><p>이 구조의 장점은 B가 A를 직접 참조하지 않는다는 것이다. B는 “A에게 이벤트를 보낸다”기보다는 “특정 path를 가진 화면에게 item을 보낸다”에 가깝다.</p><h3>send와 rootSend의 차이</h3><p>주의할 점은 send가 항상 root stack을 대상으로 동작하는 것은 아니라는 점이다.</p><p>LinkNavigator에는 여러 send 계열 메서드가 있다.</p><pre>navigator.send(...)<br>navigator.rootSend(...)<br>navigator.allSend(...)<br>navigator.allRootSend(...)<br>navigator.mainSend(...)</pre><p>프로토콜상으로도 각 메서드는 화면 간 item 전달을 위한 용도로 정의되어 있다. send는 현재 navigation stack의 특정 subscriber로 item을 보내는 용도이고, rootSend는 root controller 쪽으로 item을 보내는 용도다.</p><p>일반적인 A -&gt; B push 구조라면 send로 충분하다.</p><pre>A -&gt; B<br>현재 active stack: [A, B]<br>B에서 navigator.send(pathList: [&quot;a&quot;])<br>A가 수신</pre><p>하지만 B가 sheet 내부에 있는 경우라면 다르게 봐야 한다.</p><pre>Root stack: [A]<br>Sheet stack: [B]</pre><p>이 경우 send는 현재 active stack, 즉 sheet 내부 stack을 바라볼 수 있다.<br>A가 root stack에 있다면 rootSend를 사용해야 할 수 있다.</p><pre>navigator.rootSend(<br>  item: .init(<br>    pathList: [&quot;a&quot;],<br>    items: [<br>      &quot;event&quot;: &quot;didCompleteSave&quot;<br>    ]<br>  )<br>)</pre><p>따라서 기준은 다음처럼 잡으면 된다.</p><pre>A와 B가 같은 navigation stack에 있다면 send<br>A가 root stack에 있고 B가 sheet/sub stack에 있다면 rootSend</pre><h3>ViewModel과 연결할 때의 형태</h3><p>실제 앱에서는 encodedItemString을 그대로 ViewModel에 넘기기보다, 이벤트 타입으로 변환해서 처리하는 편이 낫다.</p><p>예를 들어 다음과 같이 구성할 수 있다.</p><pre>enum AExternalEvent {<br>  case didCompleteSave(id: String)<br>  case didUpdateProfile<br>  case unknown<br>}</pre><p>subscriber에서는 문자열을 파싱해서 ViewModel에 전달한다.</p><pre>final class AEventSubscriber: LinkNavigatorItemSubscriberProtocol {<br>  private let viewModel: AViewModel<br><br>  init(viewModel: AViewModel) {<br>    self.viewModel = viewModel<br>  }<br><br>  func receive(encodedItemString: String) {<br>    let event = AExternalEventMapper.map(encodedItemString)<br>    viewModel.handleExternalEvent(event)<br>  }<br>}</pre><p>ViewModel은 이벤트에 따라 필요한 액션을 수행한다.</p><pre>final class AViewModel: ObservableObject {<br>  func handleExternalEvent(_ event: AExternalEvent) {<br>    switch event {<br>    case let .didCompleteSave(id):<br>      reload(id: id)<br><br>    case .didUpdateProfile:<br>      refreshProfile()<br><br>    case .unknown:<br>      break<br>    }<br>  }<br><br>  private func reload(id: String) {<br>    // reload logic<br>  }<br><br>  private func refreshProfile() {<br>    // refresh logic<br>  }<br>}</pre><p>이렇게 하면 navigation event와 화면 상태 갱신 로직이 분리된다.</p><h3>이 방식이 적절한 경우</h3><p>eventSubscriber 방식은 다음 상황에 잘 맞는다.</p><ul><li>이전 화면에 reload 이벤트를 보내야 한다.</li><li>push된 다음 화면에서 이전 화면에 결과를 알려야 한다.</li><li>sheet 내부 화면에서 root 화면에 완료 이벤트를 보내야 한다.</li><li>화면 간 직접 참조를 만들고 싶지 않다.</li><li>delegate/closure를 RouteBuilder 구조에 억지로 끼워 넣고 싶지 않다.</li></ul><p>반대로 다음 목적이라면 다른 방식이 더 적절할 수 있다.</p><ul><li>화면이 표시되는 순간 자동 실행해야 한다.</li><li>viewDidAppear, viewWillDisappear 같은 lifecycle을 잡아야 한다.</li><li>단순히 SwiftUI View의 appear/disappear 이벤트만 필요하다.</li></ul><p>이 경우에는 SwiftUI의 .onAppear, .onDisappear 또는 custom WrappingController에서 lifecycle을 처리하는 편이 더 명확하다.</p><pre>.onAppear {<br>  viewModel.onAppear()<br>}<br>.onDisappear {<br>  viewModel.onDisappear()<br>}</pre><h3>결론</h3><p>LinkNavigator의 eventSubscriber는 화면 간 이벤트 전달에 사용할 수 있다.</p><p>특히 다음과 같은 흐름을 만들 수 있다.</p><pre>A -&gt; B로 이동<br>B에서 특정 이벤트 발생<br>B가 navigator.send(...) 호출<br>A의 eventSubscriber가 receive<br>AViewModel이 필요한 액션 수행</pre><p>핵심은 pathList에 이벤트를 받을 화면의 matchPath를 지정하는 것이다.</p><pre>navigator.send(<br>  item: .init(<br>    pathList: [&quot;a&quot;],<br>    items: [<br>      &quot;event&quot;: &quot;didCompleteSave&quot;<br>    ]<br>  )<br>)</pre><p>이 구조를 사용하면 B가 A를 직접 참조하지 않아도 된다.<br>A는 자신의 subscriber를 통해 외부 이벤트를 받고, ViewModel을 통해 상태를 갱신한다.</p><p>즉, LinkNavigator에서 eventSubscriber는 단순한 부가 기능이라기보다, <strong>navigation stack 안의 화면 간 느슨한 이벤트 전달 채널</strong>로 활용할 수 있다.</p><h3>참고</h3><p><a href="https://github.com/forXifLess/LinkNavigator">GitHub - forXifLess/LinkNavigator: 🌊 Easy &amp; Powerful navigation library in SwiftUI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c6f7a3c784" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Swift] Task { @MainActor in } vs Task { await MainActor.run {} }]]></title>
            <link>https://gaeng2y.medium.com/swift-task-mainactor-in-vs-task-await-mainactor-run-eef59ddb29c2?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef59ddb29c2</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[actors]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 04:29:37 GMT</pubDate>
            <atom:updated>2026-04-20T04:29:37.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AXEcP7PoFMH_j91Y" /><figcaption>Photo by <a href="https://unsplash.com/@sergidolcet?utm_source=medium&amp;utm_medium=referral">Sergi Dolcet Escrig</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Swift Concurrency에서 메인 스레드로 작업을 보내는 흔한 두 가지 방법. 같은 결과처럼 보이지만, 액터 홉(actor hop) 횟수도, 의미도, 성능도 다릅니다.</p><p>Swift Concurrency를 쓰다 보면 거의 매일 마주하는 코드입니다.</p><pre>Task { @MainActor in<br>    self.title = &quot;안녕&quot;<br>}<br><br>Task {<br>    await MainActor.run {<br>        self.title = &quot;안녕&quot;<br>    }<br>}</pre><p>둘 다 “메인 스레드에서 title을 갱신&quot;한다는 결과는 같습니다. 그래서 많은 분들이 둘을 같은 것처럼 섞어 쓰곤 하는데, 사실 이 둘은 <strong>언제 어디서 액터 홉이 일어나는가</strong>, <strong>어떤 코드를 안에 담을 수 있는가</strong>, <strong>컴파일러가 격리를 어떻게 검증하는가</strong> 모두 다릅니다.</p><p>액터 홉의 개념부터 시작해서, 두 패턴이 실제로 어떻게 다른지, 어떤 상황에 무엇을 골라야 하는지 살펴보겠습니다.</p><h3>Actor와 Actor Hop</h3><p>Swift Concurrency에서 <strong>액터</strong>는 내부 상태를 한 번에 한 작업만 접근하도록 보장하는 동시성 격리 단위입니다. MainActor는 그중 가장 자주 만나는 전역 액터로, 위에서 실행되는 코드를 <strong>메인 스레드</strong>에서 직렬화해 줍니다.</p><pre>@MainActor<br>final class MyViewModel {<br>    var title = &quot;&quot;<br>}</pre><p>이렇게 선언하면 title 접근은 항상 메인 스레드에서, 다른 코드와 겹치지 않게 실행됩니다.</p><p>문제는 <strong>현재 위치한 액터와 호출하려는 함수의 액터가 다를 때</strong>입니다. 백그라운드 작업 중에 메인 액터의 프로퍼티에 값을 쓰려면 실행 컨텍스트를 메인 액터로 옮겨야 하는데, 이 컨텍스트 전환을 <strong>액터 홉(actor hop)</strong> 이라고 합니다.</p><pre>func loadAndShow() async {<br>    let data = await fetch()          // 백그라운드(Cooperative pool)에서 실행<br>    await MainActor.run {             // ← 여기서 액터 홉: pool → MainActor<br>        viewModel.title = data.title<br>    }                                 // ← 블록 끝나면 다시 홉: MainActor → pool<br>}</pre><p>액터 홉은 공짜가 아닙니다. 내부적으로 작업(Job)을 해당 액터의 실행자(executor)에게 큐잉(enqueue)하고, 스케줄링과 재개를 거칩니다. 한 번에 수십 µs 수준이고, UI 프레임(16.67ms) 안에서 수십 번 일어나면 체감되는 버벅임으로 이어질 수 있습니다.</p><blockquote><strong><em>핵심 포인트</em></strong><em>: “메인 스레드에서 실행한다” 자체가 비싼 게 아닙니다. </em><strong><em>“다른 액터에서 메인 액터로 옮겨 가는 행위”</em></strong><em> 가 비용입니다. 얼마나 자주 옮겨다니냐가 성능을 좌우합니다.</em></blockquote><h3>1 — Task { @MainActor in ... }</h3><p>Task를 만들 때 클로저에 @MainActor를 붙이면, <strong>그 Task 자체가 메인 액터에 격리된 상태로 실행</strong>됩니다.</p><pre>final class FeedViewModel: ObservableObject {<br>    @Published var items: [Item] = []<br><br>    func reload() {<br>        Task { @MainActor [weak self] in<br>            guard let self else { return }<br>            let fetched = await loadFromNetwork()        // ① 네트워크 await<br>            self.items = fetched                         // ② @Published 갱신<br>        }<br>    }<br>    <br>    private nonisolated func loadFromNetwork() async -&gt; [Item] { ... }<br>}</pre><p>액터 홉이 일어나는 시점은 다음과 같습니다.</p><ul><li><strong>Task 시작 시점</strong>: 호출자에서 MainActor로 <strong>1회 홉</strong></li><li>await loadFromNetwork() 동안: nonisolated이므로 잠시 메인을 떠남</li><li><strong>재개될 때</strong>: 다시 MainActor로 <strong>1회 홉</strong></li><li>self.items = fetched: 이미 MainActor 위 → <strong>홉 없음</strong></li></ul><p>핵심은 <strong>“중간에 비동기 작업을 해도, 결과를 받은 뒤의 코드는 자동으로 다시 MainActor에서 재개된다”</strong> 는 점입니다. UI 갱신 코드를 따로 감쌀 필요가 없습니다.</p><h3>2 — Task { await MainActor.run { ... } }</h3><p>MainActor.run은 함수입니다. 시그니처를 보면:</p><pre>@MainActor<br>static func run&lt;T&gt;(<br>    resultType: T.Type = T.self,<br>    body: @MainActor () throws -&gt; T<br>) async rethrows -&gt; T</pre><p>여기서 주목할 점이 두 가지입니다.</p><ol><li>body가 <strong>동기 클로저</strong>입니다 — 안에서 await를 직접 쓸 수 없습니다.</li><li>호출 전후로 <strong>들어갈 때 한 번, 빠져나올 때 한 번</strong> 홉이 발생합니다.</li></ol><pre>func reload() {<br>    Task {                                           // 호출자 액터 상속(nonisolated)<br>        let fetched = await loadFromNetwork()        // pool에서 실행<br>        await MainActor.run {                        // ① 홉: pool → MainActor<br>            viewModel.items = fetched<br>        }                                            // ② 홉: MainActor → pool<br>        // 여기는 다시 pool<br>    }<br>}</pre><p>MainActor.run 블록을 여러 번 쓰면 그 횟수만큼 홉 비용이 곱해집니다.</p><h3>나란히 비교해보기 — 홉 횟수의 차이</h3><p>같은 시나리오를 두 방식으로 작성해 보겠습니다. 네트워크에서 두 번 가져와서 UI를 두 번 갱신하는 경우입니다.</p><h3>Task { @MainActor in } 사용 시</h3><pre>Task { @MainActor [weak self] in<br>    guard let self else { return }<br>    self.isLoading = true                  // 홉 없음<br>    let users = await api.fetchUsers()     // 떠났다가 MainActor로 복귀<br>    self.users = users                     // 홉 없음<br>    let posts = await api.fetchPosts()     // 떠났다가 MainActor로 복귀<br>    self.posts = posts                     // 홉 없음<br>    self.isLoading = false                 // 홉 없음<br>}<br>// 총 홉: 시작 1회 + 복귀 2회 = 약 3회</pre><h3>Task { await MainActor.run {} } 반복 시</h3><pre>Task {<br>    await MainActor.run { viewModel.isLoading = true }  // 홉 2회<br>    let users = await api.fetchUsers()<br>    await MainActor.run { viewModel.users = users }     // 홉 2회<br>    let posts = await api.fetchPosts()<br>    await MainActor.run { viewModel.posts = posts }     // 홉 2회<br>    await MainActor.run { viewModel.isLoading = false } // 홉 2회<br>}<br>// 총 홉: 8회</pre><p>UI 갱신 한 줄을 위해 매번 액터를 들락거리는 비용이 얼마나 쌓이는지 한눈에 보입니다.</p><h3>그럼 MainActor.run은 언제 써야 할까?</h3><p>쓸 자리는 분명히 있습니다.</p><p><strong>비-MainActor 컨텍스트에서 딱 한 지점만 UI를 갱신할 때</strong>가 대표적입니다.</p><pre>actor ImageCache {<br>    func warmUp(for ids: [String]) async {<br>        for id in ids {<br>            let image = await download(id)<br>            await MainActor.run {<br>                NotificationCenter.default.post(name: .imageReady, object: image)<br>            }<br>        }<br>    }<br>}</pre><p>Task 자체를 MainActor로 격리하면 다운로드까지 메인에 묶이는 문제가 생깁니다. 본체는 액터에 두고, <strong>딱 UI 갱신 한 지점만</strong> MainActor.run으로 옮기는 패턴이 적절합니다.</p><p><strong>이미 만들어진 nonisolated 함수에서 동기 콜백만 메인에서 실행하면 될 때</strong>도 마찬가지입니다.</p><pre>nonisolated func processInBackground() async {<br>    let result = heavyComputation()<br>    await MainActor.run {<br>        delegate?.didFinish(result)<br>    }<br>}</pre><h3>어떤 걸 골라야 할까? 빠른 판단표</h3><ul><li>await가 여러 번, 중간/끝에 UI 갱신: Task { @MainActor in ... }</li><li>비-MainActor 컨텍스트에서 짧은 일회성 UI 갱신: await MainActor.run { ... }</li><li>이미 @MainActor 함수 안에서 호출: 어느 쪽도 불필요, 그냥 호출</li><li>withTaskGroup 종료 후 상태 일괄 갱신: Task { @MainActor in ... }</li><li>Actor 메서드 내부에서 가끔 메인 액세스 await MainActor.run { ... }</li></ul><h3>한 가지 더 — 부모가 MainActor면 명시 안 해도 된다</h3><pre>@MainActor<br>final class MyView: UIView {<br>    func tapped() {<br>        Task {                       // 격리 미지정 → MainActor 상속<br>            let v = await api.fetch()<br>            label.text = v           // 자동으로 MainActor에서 재개<br>        }<br>    }<br>}</pre><p>호출자가 @MainActor라면 Task { ... }는 격리를 자동으로 상속합니다. 반대로 ObservableObject처럼 비-MainActor 클래스에서 호출한다면 상속받을 액터가 없으므로, 명시적으로 Task { @MainActor in }를 달아야 합니다.</p><pre>final class FeedViewModel: ObservableObject {<br>    func reload() {<br>        Task { @MainActor in      // ← 여기는 명시 필요<br>            self.items = await load()<br>        }<br>    }<br>}</pre><blockquote><em>공식 가이드라인은 단순합니다: </em><strong><em>“Task 안의 코드가 어느 액터에서 도는지 한눈에 모르겠다면 명시하라.”</em></strong><em> 명시는 컴파일 비용 0, 가독성과 안전성은 올라갑니다.</em></blockquote><h3>마치며</h3><p>Task { @MainActor in }와 Task { await MainActor.run {} }은 모두 메인 스레드에서 코드를 실행하지만, <strong>액터 홉 횟수</strong>, <strong>await 사용 가능 여부</strong>, <strong>컴파일러가 보는 격리 경계</strong>가 다릅니다.</p><p>원칙을 하나로 정리하면 이렇습니다.</p><blockquote><em>연속된 비동기 작업 + UI 갱신은 </em><em>Task { @MainActor in }. 비-MainActor 컨텍스트에서의 일회성 짧은 UI 갱신만 </em><em>MainActor.run.</em></blockquote><p>이 차이를 알고 쓰면 액터 홉으로 새는 µs들을 줄이고, 의도를 더 명확히 드러내는 코드를 작성할 수 있습니다.</p><h3>참고 자료</h3><ul><li><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0316-global-actors.md">Swift Evolution SE-0316: Global Actors</a></li><li><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md">Swift Evolution SE-0306: Actors</a></li><li>WWDC 2021 — <em>Protect mutable state with Swift actors</em></li><li>WWDC 2022 — <em>Eliminate data races using Swift Concurrency</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef59ddb29c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Swift] swift-openapi-generator 간단히 적용해보기]]></title>
            <link>https://gaeng2y.medium.com/swift-swift-openapi-generator-%EA%B0%84%EB%8B%A8%ED%9E%88-%EC%A0%81%EC%9A%A9%ED%95%B4%EB%B3%B4%EA%B8%B0-bace3d00c866?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/bace3d00c866</guid>
            <category><![CDATA[data-transfer-object]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 14:20:10 GMT</pubDate>
            <atom:updated>2026-04-09T14:20:10.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ou6gxgCVemjzBJmd" /><figcaption>Photo by <a href="https://unsplash.com/@douglasamarelo?utm_source=medium&amp;utm_medium=referral">Douglas Lopes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>서버와 통신하는 iOS 앱을 만들다 보면, URLRequest를 직접 만들고 응답 모델을 붙이는 작업이 반복됩니다.</p><p>이 과정을 줄이기 위해 Apple의 <strong>Swift OpenAPI Generator</strong>를 적용해봤습니다.</p><p>swift-openapi-generator는 <strong>OpenAPI 문서(YAML/JSON)</strong> 를 기반으로 Swift의 <strong>API client / server 코드</strong>를 생성해주는 도구입니다. 빌드 시점에 코드를 생성하기 때문에, 스펙과 코드가 계속 동기화되도록 가져갈 수 있는 점이 특징입니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>무엇이 좋은가</h3><p>이 도구를 적용하면 대략 이런 이점이 있습니다.</p><ul><li>OpenAPI 스펙 기반으로 <strong>타입 안전한 API 호출 코드</strong>를 만들 수 있다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li><li>요청/응답 모델을 직접 일일이 작성하는 보일러플레이트를 줄일 수 있다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li><li>빌드 타임에 생성되므로 스펙과 구현의 불일치를 줄이기 좋다. 생성 코드를 별도로 저장소에 커밋하지 않는 흐름도 가능하다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li></ul><p>iOS 클라이언트 기준으로는 보통 다음 조합을 사용합니다.</p><ul><li>swift-openapi-generator : 코드 생성기</li><li>swift-openapi-runtime : 생성 코드가 사용하는 런타임</li><li>swift-openapi-urlsession : URLSession 기반 transport (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li></ul><h3>기본 적용 흐름</h3><p>전체 흐름은 단순합니다.</p><ol><li>OpenAPI 문서를 준비한다.</li><li>Swift Package에 generator plugin과 runtime/transport를 추가한다.</li><li>빌드하면 Client 타입과 요청/응답 타입이 생성된다.</li><li>앱 코드에서는 생성된 Client를 사용해 API를 호출한다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li></ol><h3>1. OpenAPI 문서 준비</h3><p>예를 들어 openapi.yaml 파일이 있다고 가정합니다.</p><pre>openapi: 3.1.0<br>info:<br>  title: GreetingService<br>  version: 1.0.0</pre><pre>servers:<br>  - url: <a href="https://example.com/api">https://example.com/api</a></pre><pre>paths:<br>  /greet:<br>    get:<br>      operationId: getGreeting<br>      responses:<br>        &#39;200&#39;:<br>          description: Success<br>          content:<br>            application/json:<br>              schema:<br>                type: object<br>                properties:<br>                  message:<br>                    type: string<br>                required:<br>                  - message</pre><p>공식 README의 예시도 비슷한 형태로 operationId를 기준으로 Swift 메서드가 생성되는 구조를 보여줍니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>2. 패키지 의존성 추가</h3><p>Package.swift에 generator와 runtime, URLSession transport를 추가합니다.</p><pre>// swift-tools-version: 6.0<br>import PackageDescription</pre><pre>let package = Package(<br>    name: &quot;MyApp&quot;,<br>    platforms: [<br>        .iOS(.v16)<br>    ],<br>    dependencies: [<br>        .package(url: &quot;https://github.com/apple/swift-openapi-generator&quot;, from: &quot;1.0.0&quot;),<br>        .package(url: &quot;https://github.com/apple/swift-openapi-runtime&quot;, from: &quot;1.0.0&quot;),<br>        .package(url: &quot;https://github.com/apple/swift-openapi-urlsession&quot;, from: &quot;1.0.0&quot;)<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;Networking&quot;,<br>            dependencies: [<br>                .product(name: &quot;OpenAPIRuntime&quot;, package: &quot;swift-openapi-runtime&quot;),<br>                .product(name: &quot;OpenAPIURLSession&quot;, package: &quot;swift-openapi-urlsession&quot;)<br>            ],<br>            plugins: [<br>                .plugin(name: &quot;OpenAPIGenerator&quot;, package: &quot;swift-openapi-generator&quot;)<br>            ]<br>        )<br>    ]<br>)</pre><p>핵심은 <strong>target에 plugin을 붙이는 것</strong>과, 생성 코드가 사용할 OpenAPIRuntime, 실제 HTTP 전송을 위한 OpenAPIURLSession을 함께 추가하는 것입니다. 공식 문서에서도 generator는 plugin/CLI 역할을 하고, URLSession transport는 별도 패키지로 분리되어 있습니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>3. 설정 파일 추가</h3><p>타깃 디렉터리 안에 보통 다음 파일들을 둡니다.</p><ul><li>openapi.yaml</li><li>openapi-generator-config.yaml</li></ul><p>예시:</p><pre>generate:<br>  - types<br>  - client<br>accessModifier: public</pre><p>이렇게 해두면 빌드 시 client와 관련 타입이 생성됩니다. 공식 README와 예제들은 build plugin 방식이 기본 사용 패턴이라고 안내합니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>4. 생성된 Client 사용</h3><p>이제 앱 코드에서는 직접 endpoint를 조립하기보다 생성된 Client를 사용합니다.</p><pre>import Foundation<br>import OpenAPIURLSession</pre><pre>final class GreetingAPI {<br>    private let client: Client</pre><pre>    init() {<br>        self.client = Client(<br>            serverURL: URL(string: &quot;https://example.com/api&quot;)!,<br>            transport: URLSessionTransport()<br>        )<br>    }</pre><pre>    func fetchGreeting() async throws -&gt; String {<br>        let response = try await client.getGreeting()</pre><pre>        switch response {<br>        case .ok(let okResponse):<br>            return try okResponse.body.json.message<br>        default:<br>            throw URLError(.badServerResponse)<br>        }<br>    }<br>}</pre><p>이 패턴은 공식 README에 있는 generated client 사용 예시와 같은 방향입니다. Client를 만들고, operation별 메서드를 async/await로 호출하는 형태입니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>실제로 써보면서 느낀 점</h3><h3>1) API 스펙이 기준이 된다는 점이 좋다</h3><p>보통 앱 코드에서 API 호출부가 먼저 생기고 문서는 뒤늦게 맞추는 경우가 많은데, 이 방식은 반대로 <strong>OpenAPI 문서가 기준</strong>이 됩니다.<br>결과적으로 서버와 클라이언트가 같은 계약을 보고 작업하기 쉬워집니다. 이건 생성기가 OpenAPI 문서로부터 코드를 만드는 구조 자체에서 오는 장점입니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>2) 네트워킹 레이어의 반복 코드가 줄어든다</h3><p>path, method, request body, response model을 각각 손으로 관리하던 부담이 줄어듭니다.<br>특히 규모가 커질수록 직접 작성하는 DTO/endpoint 코드보다 생성 기반 접근이 유지보수에 유리해 보였습니다. 이 점은 공식 예제들이 client/server, middleware, 다양한 content type까지 확장해 보여주는 이유이기도 합니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>3) 완전히 “아무 설정 없이” 되는 도구는 아니다</h3><p>OpenAPI 문서 품질이 낮으면 생성 결과도 애매해질 수 있습니다.<br>또 공식 이슈 기준으로 <strong>외부 파일로 분리된 JSON references</strong> 지원은 아직 제한적이라, 큰 스펙을 여러 파일로 나누어 관리하는 경우에는 제약을 확인하는 편이 좋습니다. (<a href="https://github.com/apple/swift-openapi-generator/issues/25?timeline_page=1&amp;utm_source=chatgpt.com">GitHub</a>)</p><h3>Swift 프로젝트에서는 어디에 두면 좋을까</h3><p>개인적으로는 Networking 또는 API 모듈을 따로 두고, 그 안에 아래처럼 두는 구성이 깔끔해 보입니다.</p><pre>Networking/<br> ┣ Sources/<br> ┃ ┣ Generated/<br> ┃ ┣ OpenAPI/<br> ┃ ┃ ┣ openapi.yaml<br> ┃ ┃ ┗ openapi-generator-config.yaml<br> ┃ ┗ APIClient.swift</pre><p>실제로 앱 전반에서 생성 타입을 직접 퍼뜨리기보다는,<br><strong>생성된 client를 내부 구현으로 감추고</strong>, 바깥에는 프로젝트에서 쓰는 Repository / Service 인터페이스를 노출하는 방식이 더 안정적입니다. 공식 예제에도 generated API를 감싸는 curated client library 예제가 따로 있습니다. (<a href="https://github.com/apple/swift-openapi-generator/blob/main/Examples/README.md?utm_source=chatgpt.com">GitHub</a>)</p><h3>마무리</h3><p>swift-openapi-generator는 Swift 프로젝트에서 OpenAPI 스펙을 기준으로 네트워킹 코드를 관리하고 싶을 때 꽤 매력적인 선택지였습니다.</p><p>특히 이런 경우에 잘 맞습니다.</p><ul><li>서버가 이미 OpenAPI 문서를 제공하는 경우</li><li>앱에서 타입 안전한 API 호출 구조를 원할 때</li><li>스펙과 클라이언트 코드의 동기화를 자동화하고 싶을 때 (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</li></ul><p>반대로, 작은 프로젝트이거나 OpenAPI 문서 관리가 전혀 안 되는 팀이라면 초기 세팅 비용이 더 크게 느껴질 수도 있습니다.</p><p>그래도 <strong>“문서를 기준으로 Swift API 코드를 생성한다”</strong> 는 흐름 자체는 꽤 깔끔했고,<br>규모가 있는 프로젝트일수록 도입 가치가 있어 보였습니다. (<a href="https://github.com/apple/swift-openapi-generator?utm_source=chatgpt.com">GitHub</a>)</p><h3>참고</h3><ul><li><a href="https://github.com/apple/swift-openapi-generator">GitHub - apple/swift-openapi-generator: Generate Swift client and server code from an OpenAPI document.</a></li><li><a href="https://www.openapis.org/">OpenAPI Initiative - The OpenAPI Initiative provides an open source, technical community, within which industry participants may easily contribute to building a vendor-neutral, portable and an open specification for providing technical metadata for REST APIs - the &quot;OpenAPI Specification&quot; (OAS).</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bace3d00c866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Swift] @inlinable]]></title>
            <link>https://gaeng2y.medium.com/swift-inlinable-0c3d40ccbc3a?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c3d40ccbc3a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[inline-functions]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 07:02:01 GMT</pubDate>
            <atom:updated>2026-04-02T07:02:01.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BAzdCDkX8nHta98Q" /><figcaption>Photo by <a href="https://unsplash.com/@joaovgs?utm_source=medium&amp;utm_medium=referral">Joao Viegas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>안녕하세요 죽지도 않고 또 돌아왔습니다. 밀린 포스팅은 맞추지 않고 다시 주에 1개씩 작성할 수 있도록 노력해보겠습니다…</p><p>Foundation 프레임워크 정의를 살펴보면 @inlinable 이라는 어트리뷰트를 만나볼 수 있다.</p><p>그러면 inlinable에 대해 알아보기 전에 inline이라는 개념을 먼저 알아봐야할 것 같은데요</p><h3>inline function</h3><ul><li>Swift 뿐 아니라 일반적인 프로그래밍 언어에 있는 기능</li><li>컴파일러 최적화에서 사용</li><li>인라인이란, 메서드 호출을 해당 메서드의 본문으로 대체하는 컴파일러 최적화 방법<br>- 일반적인 메소드를 호출하는 작업: 스레드에 있는 스택 테스크(추적, 앱 상태 전송, 저장, 변경)하는 과정이 존재<br>(장점 — 디버깅 용이, 단점 — 오버헤드)<br>- 인라인을 사용한 경우, 메소드 호출: 스택을 따로 추적하지 않고 메소드의 본문을 바로 가져다가 사용 <br>(장점 — 오버헤드 감소, 단점 — 함수 body가 재귀 호출과 같은 반복이 있는 경우에는 더 비효율적)</li></ul><blockquote>함수 호출 시 별도로 분리된 위치의 레이블로 점프하여 실행되는 일반 함수와는 달리 호출 부분을 함수 전체 코드로 치환하여 컴파일한다. 전처리기의 매크로와 달리 언어 차원에서 지원하기에 일반 함수와 별 다르지 않게 사용할 수 있다.<br>- <a href="https://namu.wiki/w/%EC%9D%B8%EB%9D%BC%EC%9D%B8%20%ED%95%A8%EC%88%98">나무위키</a></blockquote><h3>@inlinable</h3><p>컴파일러가 함수 본문을 호출 지점에 인라인할 수 있게 허용하는 어트리뷰트입니다</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWdHAgY67qTZyXu502Aw6w.png" /><figcaption><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes/#inlinable">https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes/#inlinable</a></figcaption></figure><p>일반 함수 호출은 call → jump → execute → return 과정을 거치지만, 인라인되면 함수 본문이 호출 지점에 직접 삽입되어 함수 호출 오버헤드가 사라집니다.</p><p>주로 Swift 표준 라이브러리나 프레임워크 모듈에서 성능이 중요한 작은 함수에 사용합니다. 앱 코드에서는 컴파일러가 같은 모듈 내에서 알아서 인라인 최적화를 하기 때문에 직접 붙일 필요가 거의 없습니다.</p><p>모듈 경계를 넘어서 호출되는 작고 성능이 중요한 public 함수에 사용합니다.</p><p><strong>핵심 이유</strong></p><p>모듈이 분리되면 컴파일러가 다른 모듈의 함수 본문을 볼 수 없어서 인라인 최적화가 불가능합니다. <a href="http://twitter.com/inlinable">@inlinable</a>을 붙이면 함수 본문이 모듈의 .swiftinterface에 노출되어 호출 측 모듈에서 인라인할 수 있게 됩니다.</p><h3>예제: +1을 하여 print하는 메소드</h3><pre>// 일반적인 메소드<br>func logPlusOn(number: Int) {<br>  print(&quot;value is \(number + 1)&quot;)<br>}<br><br>// 재귀호출이 없고, body가 단순한 형태이므로 @inlinable 사용하여 컴파일러 최적화<br>@inlinable<br>func logPlusOn(number: Int) {<br>  print(&quot;value is \(number + 1)&quot;)<br>}</pre><h3>참고</h3><p><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes/#inlinable">Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c3d40ccbc3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[SwiftUI] ImageRenderer로 뷰를 이미지로 변경하기]]></title>
            <link>https://gaeng2y.medium.com/swiftui-imagerenderer%EB%A1%9C-%EB%B7%B0%EB%A5%BC-%EC%9D%B4%EB%AF%B8%EC%A7%80%EB%A1%9C-%EB%B3%80%EA%B2%BD%ED%95%98%EA%B8%B0-877b99fa76b1?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/877b99fa76b1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 12:57:12 GMT</pubDate>
            <atom:updated>2026-03-15T12:57:12.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ygss_4Cvmc5F29Z7" /><figcaption>Photo by <a href="https://unsplash.com/@joshuahanson43?utm_source=medium&amp;utm_medium=referral">Joshua Hanson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>TLDR</h3><p>네트워크 이미지가 들어간 SwiftUI 화면을 저장해야 한다면, 이제는 UIHostingController를 억지로 붙이기보다 ImageRenderer를 쓰는 쪽이 훨씬 단순합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wB_81o0oRItz49Nw.png" /></figure><h3>들어가며</h3><p>SwiftUI로 만든 화면을 이미지 파일로 저장해야 할 때가 있습니다. 예를 들면 카드 뉴스, 포토북, 인증서, 공유용 썸네일 같은 기능이 그렇습니다.</p><p>저도 처음에는 예전부터 많이 쓰던 방식으로 구현했습니다.</p><p><strong>UIHostingController</strong>로 SwiftUI 뷰를 감싼 뒤, <strong>drawHierarchy</strong>로 캡쳐하는 방식이었죠.</p><p>처음엔 문제 없어 보였습니다. 그런데 뷰 안에 네트워크 이미지가 들어가자 상황이 달라졌습니다.</p><ul><li>어떤 날은 잘 저장되고</li><li>어떤 날은 이미지가 비어 있고</li><li>어떤 날은 레이아웃이 덜 그려진 상태로 저장됐습니다</li></ul><p>결론부터 말하면, 문제의 핵심은 “캡쳐 시점에 화면이 정말 다 준비됐는가?”였습니다.</p><p>이 글에서는 그 문제를 어떻게 정리했고, 왜 최종적으로 <strong>이미지 프리로드 + ImageRenderer</strong> 조합으로 바꾸게 됐는지 가볍게 정리해보겠습니다.</p><p>이 글은 <strong>iOS 16 이상</strong> 기준입니다.</p><h3>기존 방식은 왜 불안했을까?</h3><p>예전 방식은 대체로 이런 흐름입니다.</p><ol><li>SwiftUI 뷰를 `UIHostingController`로 감싼다</li><li>그 뷰를 어딘가의 윈도우에 잠깐 올린다</li><li>레이아웃을 강제로 잡는다</li><li><strong>drawHierarchy</strong>로 화면을 이미지처럼 그린다</li></ol><p>코드로 보면 이런 느낌입니다.</p><pre>extension CardView {<br>    func capture(size: CGSize, scale: CGFloat = 1.0) async -&gt; UIImage {<br>        let controller = UIHostingController(rootView: self.ignoresSafeArea(.all))<br>        controller.view.frame = CGRect(x: 0, y: 0, width: 1, height: 1)<br>        guard let window = UIApplication.shared.connectedScenes<br>            .compactMap({ $0 as? UIWindowScene })<br>            .first?.windows.first else { return UIImage() }<br>        window.addSubview(controller.view)<br>        controller.view.setNeedsLayout()<br>        controller.view.layoutIfNeeded()<br>        try? await Task.sleep(nanoseconds: 3_000_000_000)<br>        controller.view.bounds = CGRect(origin: .zero, size: size)<br>        let renderer = UIGraphicsImageRenderer(size: size)<br>        let image = renderer.image { _ in<br>            controller.view.drawHierarchy(<br>                in: controller.view.bounds,<br>                afterScreenUpdates: true<br>            )<br>        }<br>        controller.view.removeFromSuperview()<br>        return image<br>    }<br>}</pre><p>동작 자체는 가능합니다. 다만 초보자 입장에서도 딱 봐도 “조금 억지스럽다”는 느낌이 듭니다.</p><p>특히 아쉬운 지점은 세 가지였습니다.</p><h4>1. 보이지 않는 뷰를 몰래 올려야 한다</h4><p>실제 사용자 화면에는 안 보이지만, 내부적으로는 뷰 계층에 끼워 넣는 과정이 필요합니다.</p><p>이런 방식은 당장은 돌아가도 나중에 유지보수할 때 부담이 큽니다.</p><p>“왜 여기서 갑자기 윈도우에 뷰를 추가하지?” 같은 코드가 되기 쉽기 때문입니다.</p><h4>2. 네트워크 이미지는 준비 타이밍이 다르다</h4><p>문제는 SDWebImageSwiftUI 라이브러리의 WebImage 같은 비동기 이미지 뷰입니다.</p><p>화면에 보여줄 때는 괜찮습니다. 어차피 다운로드가 끝나면 다시 그려주니까요.</p><p>하지만 캡쳐는 다릅니다. <strong>그 순간 준비된 상태만 저장</strong>합니다.</p><p>즉,</p><ul><li>이미지 다운로드가 아직 안 끝났다면</li><li>캡쳐 결과에도 이미지가 비어 있게 됩니다</li></ul><p>그래서 흔히 이런 코드를 붙이게 됩니다.</p><pre>try? await Task.sleep(nanoseconds: 3_000_000_000)</pre><p>3초 기다리면 될까요? 어떤 환경에서는 충분할 수 있습니다.</p><p>하지만 네트워크가 느리면 3초도 부족하고, 빠르면 괜히 기다리는 시간이 됩니다.</p><p>즉, <strong>운에 기대는 코드</strong>가 됩니다.</p><h4>3. SwiftUI와 UIKit의 타이밍이 완전히 같지는 않다</h4><p>drawHierarchy(afterScreenUpdates: true)는 UIKit 기준으로는 <strong>업데이트 후 캡쳐</strong>입니다.</p><p>그런데 SwiftUI는 자체 렌더링 흐름이 있습니다.</p><p>그래서 UIKit 쪽에서 “이제 됐다”고 생각한 순간에도, SwiftUI는 아직 다시 그리는 중일 수 있습니다.</p><p>이 차이 때문에 간헐적으로</p><ul><li>빈 이미지가 나오거나</li><li>일부 레이아웃이 덜 그려진 채 저장되는 문제</li></ul><p>가 생길 수 있습니다.</p><p>가장 까다로운 버그가 바로 이런 종류입니다.</p><p>항상 재현되지 않아서 더 어렵습니다.</p><h3>해결 아이디어는 의외로 단순했다</h3><p>정리해보면 문제는 하나였습니다.</p><blockquote>캡쳐할 때 필요한 데이터가 아직 준비되지 않은 상태였다.</blockquote><p>그래서 접근을 바꿨습니다.</p><ol><li>이미지는 먼저 다운로드해 둔다</li><li>캡쳐할 때는 비동기 뷰 대신 Image(uiImage:)를 쓴다</li><li>마지막에 <strong>ImageRenderer</strong>로 SwiftUI 뷰를 바로 이미지로 만든다</li></ol><p>핵심은 <strong>캡쳐 시점</strong>에는 모든 재료가 이미 준비되어 있어야 한다입니다.</p><h4>1. 필요한 이미지를 먼저 프리로드한다</h4><p>저는 SDWebImage를 쓰고 있어서, 같은 라이브러리의 로더를 그대로 활용했습니다.</p><pre>import SDWebImage<br><br>func preloadImages(urls: [String]) async -&gt; [String: UIImage] {<br>    guard !urls.isEmpty else { return [:] }<br>    <br>    return await withTaskGroup(of: (String, UIImage?).self) { group in<br>        for url in Set(urls) {<br>            group.addTask {<br>                await withCheckedContinuation { continuation in<br>                    SDWebImageManager.shared.loadImage(with: URL(string: url), options: .continueInBackground, progress: nil) { image, _, _, _, _, _ in<br>                        continuation.resume(returning: (url, image))<br>                    }<br>                }<br>            }<br>        }<br>        var result = [String: UIImage]()<br>        for await (url, image) in group {<br>            if let image {<br>                result[url] = image<br>            }<br>        }<br>        return result<br>    }<br>}</pre><p>여기서 중요한 건 두 가지입니다.</p><ul><li>여러 이미지를 TaskGroup으로 동시에 받는다</li><li>이미 캐시에 있는 이미지는 빠르게 재사용할 수 있다</li></ul><p>즉, <strong>화면에서 한 번 본 이미지</strong>라면 실제로는 거의 바로 준비되는 경우도 많습니다.</p><h4>2. 뷰는 상황에 따라 이미지를 다르게 그린다</h4><p>기존에는 항상 WebImage를 썼다면, 이제는 프리로드된 이미지가 있을 때는 Image(uiImage:)를 우선 사용합니다.</p><pre>import SwiftUI<br>import SDWebImageSwiftUI<br><br>struct CardView: View {<br>    let title: String<br>    let imageURL: String<br>    let backgroundColor: String<br>    var preloadedImages: [String: UIImage] = [:]<br>    var body: some View {<br>        VStack(spacing: 0) {<br>            resolvedImage(url: imageURL)<br>                .scaledToFill()<br>                .frame(width: 300, height: 200)<br>                .clipped()<br>            Text(title)<br>                .font(.title2)<br>                .padding()<br>        }<br>        .background(Color(hex: backgroundColor))<br>    }<br>    @ViewBuilder<br>    private func resolvedImage(url: String) -&gt; some View {<br>        if let image = preloadedImages[url] {<br>            Image(uiImage: image).resizable()<br>        } else {<br>            WebImage(url: URL(string: url)).resizable()<br>        }<br>    }<br>}</pre><p>이 구조가 좋은 이유는 하나의 뷰를 두 상황에서 모두 재사용할 수 있기 때문입니다.</p><ul><li>일반 화면 표시: WebImage로 비동기 로딩</li><li>캡쳐용 렌더링: 프리로드된 UIImage로 즉시 표시</li></ul><p>즉, 뷰를 따로 두 벌 만들 필요가 없습니다.</p><h4>3. 마지막은 ImageRenderer로 끝낸다</h4><p>이제 렌더링할 뷰 안의 데이터가 모두 준비됐으니, 캡쳐도 훨씬 단순해집니다.</p><pre>extension CardView {<br>    @MainActor<br>    func capture(size: CGSize, scale: CGFloat = 1.0) -&gt; Data {<br>        let content = self<br>            .frame(width: size.width, height: size.height)<br>            .ignoresSafeArea(.all)<br>        let renderer = ImageRenderer(content: content)<br>        renderer.scale = scale<br>        renderer.isOpaque = false<br>        guard let cgImage = renderer.cgImage else { return Data() }<br>        let uiImage = UIImage(cgImage: cgImage)<br>        return uiImage.jpegData(compressionQuality: 1.0) ?? Data()<br>    }<br>}</pre><p>이전 방식과 비교하면 확실히 단순합니다.</p><ul><li>UIHostingController가 필요 없습니다</li><li>윈도우에 뷰를 올릴 필요가 없습니다</li><li>sleep으로 기다릴 필요가 없습니다</li><li>drawHierarchy를 직접 호출할 필요도 없습니다</li></ul><p>SwiftUI 뷰를 SwiftUI 방식으로 이미지화한다는 점에서 훨씬 자연스럽습니다.</p><h3>실제 호출 흐름은 이렇게 정리된다</h3><p>최종 흐름은 아래처럼 이해하면 됩니다.</p><pre>final class CardMaker {<br>    func exportCard() async -&gt; Data {<br>        let card = CardData(<br>            title: &quot;제주도 여행&quot;,<br>            imageURL: &quot;https://example.com/jeju.jpg&quot;,<br>            backgroundColor: &quot;#FFF8E7&quot;<br>        )<br>        let preloaded = await preloadImages(urls: [card.imageURL])<br>        let cardView = CardView(<br>            title: card.title,<br>            imageURL: card.imageURL,<br>            backgroundColor: card.backgroundColor,<br>            preloadedImages: preloaded<br>        )<br>        return await MainActor.run {<br>            cardView.capture(<br>                size: CGSize(width: 300, height: 280),<br>                scale: 2.0<br>            )<br>        }<br>    }<br>}</pre><p>읽는 순서도 자연스럽습니다.</p><ol><li>이미지 준비</li><li>뷰 생성</li><li>렌더링</li></ol><p>캡쳐 타이밍 때문에 머리를 싸맬 일이 크게 줄어듭니다.</p><h3>그래서 무엇이 좋아졌을까?</h3><p>짧게 요약하면 이렇습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjwLlRznRfpUeOPTQGh_2w.png" /></figure><p>물론 drawHierarchy 방식이 완전히 틀린 건 아닙니다.</p><p>iOS 16 미만을 지원해야 한다면 여전히 고려할 수 있습니다.</p><p>다만 <strong>iOS 16 이상이고, 네트워크 이미지가 들어간 SwiftUI 화면을 저장해야 한다면</strong>ImageRenderer 쪽이 훨씬 설득력 있는 선택이라고 느꼈습니다.</p><h3>마무리</h3><p>이번 작업에서 얻은 결론은 단순했습니다.</p><blockquote>캡쳐를 안정적으로 만들고 싶다면, 캡쳐 시점에는 이미 모든 데이터가 준비되어 있어야 한다.</blockquote><p>예전 방식은 <strong>화면이 다 그려졌겠지</strong>를 기대하는 코드에 가까웠습니다.</p><p>반면 새 방식은 <strong>그려질 재료를 먼저 다 준비하고, 마지막에 렌더링한다</strong>는 흐름이라 훨씬 예측 가능했습니다.</p><p>SwiftUI에서 이미지 저장 기능을 만들고 있는데,</p><ul><li>sleep으로 타이밍을 맞추고 있거나</li><li>UIHostingController를 임시로 붙여서 캡쳐하고 있거나</li><li>네트워크 이미지 때문에 결과가 가끔 비어 있다면</li></ul><p><strong>ImageRenderer</strong>로 한 번 정리해볼 만합니다. 생각보다 코드도 더 짧고, 디버깅 포인트도 훨씬 줄어듭니다.</p><h3>참고</h3><ul><li><a href="https://developer.apple.com/documentation/swiftui/uihostingcontroller">UIHostingController | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/uigraphicsrenderercontext">UIGraphicsRendererContext | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/uiview/drawhierarchy(in:afterscreenupdates:)">drawHierarchy(in:afterScreenUpdates:) | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/swiftui/imagerenderer">ImageRenderer | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=877b99fa76b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[CoreML] 간단한 정리와 ONNX에 대해]]></title>
            <link>https://gaeng2y.medium.com/coreml-%EA%B0%84%EB%8B%A8%ED%95%9C-%EC%A0%95%EB%A6%AC%EC%99%80-onnx%EC%97%90-%EB%8C%80%ED%95%B4-73bd654cf667?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bd654cf667</guid>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coreml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 03:26:48 GMT</pubDate>
            <atom:updated>2026-03-03T03:26:48.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>[CoreML] 모델 선택 여정기</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jGQuojY_WyMIygmr" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. 왜 ONNX → CoreML 변환을 고민하게 되었는가</h3><p>iOS 앱에서 온디바이스 추론을 수행하려면 선택지는 사실상 두 가지다.</p><ul><li>PyTorch / TensorFlow 모델을 직접 모바일용으로 변환</li><li>ONNX를 중간 포맷으로 사용</li><li>Apple 생태계에 최적화된 CoreML로 변환</li></ul><p>서버 추론이 아니라 <strong>iPhone에서 실시간 추론을 수행해야 한다면</strong>, 결국 CoreML은 피할 수 없는 선택지다.</p><p>이 글은 다음을 정리한다:</p><ul><li>CoreML이 무엇인지</li><li>ONNX는 어떤 역할을 하는지</li><li>ONNX → CoreML 변환 방법</li><li>실제로 겪게 되는 문제들</li></ul><h3>2. CoreML이란 무엇인가</h3><p>Apple이 만든 온디바이스 ML 프레임워크다. 핵심 목적은 단 하나다.</p><blockquote><em>iOS / macOS / watchOS / visionOS에서 빠르고 전력 효율적으로 추론하기</em></blockquote><h3>CoreML의 특징</h3><ul><li>.mlmodel / .mlpackage 포맷 사용</li><li>Neural Engine 자동 활용</li><li>Metal 최적화 자동 처리</li><li>Vision 프레임워크와 자연스러운 연동</li><li>Xcode에서 모델 메타데이터 확인 가능</li></ul><h3>내부 동작 구조</h3><pre>Model (.mlmodel)<br>   ↓<br>CoreML Runtime<br>   ↓<br>Neural Engine / GPU / CPU 자동 선택</pre><p>CoreML의 가장 큰 장점은 <strong>하드웨어 최적화를 개발자가 직접 고민하지 않아도 된다는 점</strong>이다.</p><h3>3. ONNX란 무엇인가</h3><p>Open Neural Network Exchange는 모델 교환을 위한 중간 포맷이다.</p><p>PyTorch → ONNX<br>TensorFlow → ONNX</p><p>처럼, 프레임워크 간 모델을 이동시키는 데 사용된다.</p><h3>ONNX의 역할</h3><ul><li>프레임워크 독립성 확보</li><li>다양한 런타임에서 실행 가능</li><li>추론 서버 환경에서 매우 유용</li></ul><p>하지만 iOS에서 직접 ONNX Runtime을 사용하는 것은 현실적으로:</p><ul><li>바이너리 크기 증가</li><li>Neural Engine 미활용</li><li>배포 복잡성 증가</li></ul><p>라는 단점이 있다. 따라서 iOS 네이티브 앱에서는 ONNX → CoreML 변환이 일반적이다.</p><h3>4. ONNX → CoreML 변환 개요</h3><p>변환은 coremltools를 사용한다. coremltools는 Apple이 제공하는 Python 라이브러리다.</p><h4>기본 흐름</h4><pre>PyTorch → ONNX → CoreML (.mlmodel)</pre><h3>5. 실제 변환 코드</h3><h4>1️⃣ ONNX 모델 로드</h4><pre>import coremltools as ct</pre><pre>model = ct.converters.onnx.convert(<br>    model=&quot;model.onnx&quot;,<br>    minimum_deployment_target=ct.target.iOS15<br>)</pre><pre>model.save(&quot;Model.mlmodel&quot;)</pre><p>최근 버전에서는 ct.convert() API를 더 많이 사용한다.</p><pre>mlmodel = ct.convert(<br>    &quot;model.onnx&quot;,<br>    source=&quot;onnx&quot;,<br>    minimum_deployment_target=ct.target.iOS15<br>)</pre><pre>mlmodel.save(&quot;Model.mlmodel&quot;)</pre><h3>6. 변환 시 반드시 확인해야 할 것들</h3><h4>1. Opset 버전 문제</h4><p>ONNX 모델의 opset이 너무 최신이면 CoreML 변환이 실패할 수 있다.</p><p>권장:</p><ul><li>opset 11 ~ 13</li></ul><h4>2. 지원되지 않는 연산자</h4><p>일부 ONNX 연산자는 CoreML에서 지원되지 않는다.</p><p>대표적으로:</p><ul><li>NonMaxSuppression</li><li>Dynamic reshape</li><li>일부 custom op</li></ul><p>이 경우:</p><ul><li>모델 수정</li><li>TorchScript 단계에서 처리</li><li>후처리 로직을 Swift로 이동</li></ul><h4>3. 입력 텐서 타입</h4><p>CoreML은:</p><ul><li>Float32</li><li>Image 타입 (RGB)</li></ul><p>을 명확히 지정해야 한다.</p><p>예:</p><pre>mlmodel = ct.convert(<br>    &quot;model.onnx&quot;,<br>    source=&quot;onnx&quot;,<br>    inputs=[<br>        ct.ImageType(<br>            name=&quot;input&quot;,<br>            shape=(1, 3, 224, 224),<br>            scale=1/255.0<br>        )<br>    ]<br>)</pre><p>이미지 전처리를 Swift가 아니라 CoreML 레벨에서 처리하게 만들면 성능이 안정적이다.</p><h3>7. Precision / Quantization 고려</h3><p>CoreML은 다음을 지원한다:</p><ul><li>Float32</li><li>Float16</li><li>INT8 (양자화)</li></ul><p>양자화 예시:</p><pre>mlmodel = ct.models.neural_network.quantization_utils.quantize_weights(<br>    mlmodel,<br>    nbits=16<br>)</pre><p>iPhone의 Neural Engine을 활용하려면 Float16이 일반적으로 유리하다.</p><h3>8. 변환 후 iOS에서 사용</h3><p>Xcode에 .mlmodel을 추가하면 자동으로 Swift 클래스가 생성된다.</p><pre>let model = try Model(configuration: MLModelConfiguration())<br>let output = try model.prediction(input: input)</pre><p>Vision과 함께 쓰는 경우:</p><pre>VNCoreMLModel(for: model.model)</pre><h3>9. ONNX Runtime 대신 CoreML을 선택한 이유</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHdEM77lkI-JZ0wA1ChZxQ.png" /></figure><p>결론은 단순하다.</p><blockquote><em>iOS 네이티브 앱이라면 CoreML이 기본 선택지다.</em></blockquote><h3>10. 정리</h3><ul><li>ONNX는 교환 포맷이다.</li><li>iOS에서 실제 실행은 CoreML이 담당한다.</li><li>변환 과정에서 opset, 연산자, 입력 타입을 반드시 점검해야 한다.</li><li>Neural Engine을 활용하려면 CoreML로 가는 것이 정석이다.</li></ul><h3>참고</h3><ul><li><a href="https://developer.apple.com/kr/machine-learning/core-ml/">Core ML - 머신 러닝 - Apple Developer</a></li><li><a href="https://developer.apple.com/documentation/coreml/">Core ML | Apple Developer Documentation</a></li><li><a href="https://onnx.ai/">ONNX | Home</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bd654cf667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI 뷰 디버깅이 어려운 이유]]></title>
            <link>https://gaeng2y.medium.com/swiftui-%EB%B7%B0-%EB%94%94%EB%B2%84%EA%B9%85%EC%9D%B4-%EC%96%B4%EB%A0%A4%EC%9A%B4-%EC%9D%B4%EC%9C%A0-9a6dc26a8f68?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a6dc26a8f68</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 14:03:09 GMT</pubDate>
            <atom:updated>2026-02-23T14:03:09.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>[SwiftUI] 뷰 디버깅이 어려운 이유</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A5eii13EPVjTrVXh" /><figcaption>Photo by <a href="https://unsplash.com/@dkomow?utm_source=medium&amp;utm_medium=referral">Daniil Komov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>UIKit에서 넘어온 개발자들이 가장 많이 하는 실수는 이것이다.</p><blockquote><em>왜 View Hierarchy가 내가 쓴 코드랑 다르지?</em></blockquote><p>이 질문 자체가 UIKit 사고방식이다.</p><p>SwiftUI는 애초에 <strong>UIView 트리 복제품이 아니다.</strong> SwiftUI는 <strong>상태 기반 렌더링 엔진</strong>이다.</p><p>이번 글에서는 SwiftUI 내부 구조를 더 깊게 파고든다. 단순히 “struct라서 그래요” 수준이 아니다. 실제 렌더링 파이프라인과 타입 시스템 레벨까지 들어간다.</p><h3>TL;DR</h3><ul><li><strong>UIKit의 뷰</strong>는 <strong>실체(Object)</strong> → 계층이 정직하게 보임</li><li><strong>SwiftUI의 뷰</strong>는 <strong>설계도(Struct)</strong> → 시스템이 압축하고 최적화함</li><li>그래서 뷰 디버거에는 코드 구조가 아닌 <strong>최적화된 내부 구현체</strong>가 보임</li></ul><h3>1. SwiftUI View는 View가 아니다</h3><h4>SwiftUI에서 View는 이런 정의다:</h4><pre>public protocol View {<br>    associatedtype Body : View<br>    @ViewBuilder var body: Self.Body { get }<br>}</pre><p>중요한 점:</p><ul><li>View는 프로토콜</li><li>Body는 또 다른 View</li><li>끝없이 재귀적으로 구성됨</li></ul><p>SwiftUI View는 객체가 아니다. 실체가 아니라 <strong>타입 기반 트리 정의</strong>다.</p><p>UIKit:</p><pre>UIView (실제 객체)<br> └─ UILabel (실제 객체)</pre><p>SwiftUI:</p><pre>ModifiedContent&lt;<br>  VStack&lt;<br>    TupleView&lt;...&gt;<br>  &gt;<br>&gt;</pre><p>런타임 객체 트리가 아니라 <strong>컴파일 타임 타입 트리</strong>다. 이 차이를 이해 못하면 SwiftUI는 영원히 낯설다.</p><h3>2. Modifier는 Syntax sugar가 아니다</h3><p>이 코드:</p><pre>Text(&quot;Hello&quot;)<br>    .font(.title)<br>    .padding()<br>    .background(Color.yellow)</pre><p>실제로는 이런 타입이다:</p><pre>ModifiedContent&lt;<br>  ModifiedContent&lt;<br>    ModifiedContent&lt;<br>      Text,<br>      _EnvironmentKeyWritingModifier&lt;Font?&gt;<br>    &gt;,<br>    _PaddingLayout<br>  &gt;,<br>  _BackgroundStyleModifier&lt;Color&gt;<br>&gt;</pre><p>SwiftUI는 modifier를 체이닝할 때마다 <strong>새로운 타입을 생성한다.</strong></p><p>중요한 포인트:</p><ul><li>modifier는 side effect가 아니다</li><li>immutable value를 감싼다</li><li>매번 새로운 struct가 만들어진다</li></ul><p>UIKit처럼 “기존 객체 속성 변경”이 아니다.</p><p>SwiftUI는 항상:</p><pre>기존 View → 감싼 새로운 View 반환</pre><h3>3. ViewBuilder는 어떻게 동작하는가</h3><p>조건문:</p><pre>if isLoggedIn {<br>    HomeView()<br>} else {<br>    LoginView()<br>}</pre><p>이건 문법적 sugar다.</p><p>실제 타입:</p><pre>_ConditionalContent&lt;HomeView, LoginView&gt;<br>ForEach:<br>_VariadicView.Tree&lt;_ForEachContent&lt;...&gt;&gt;<br>VStack:<br>_VariadicView.Tree&lt;_VStackLayout&gt;</pre><p>SwiftUI는 모든 child view를:</p><ul><li>TupleView</li><li>ConditionalContent</li><li>VariadicView</li></ul><p>같은 내부 타입으로 감싼다.</p><p><strong>이게 바로 View Debugger에 보이는 정체불명의 구조다.</strong></p><h3>4. SwiftUI는 언제 실제 뷰를 만들까?</h3><p>이 질문이 핵심이다.</p><p>SwiftUI View는 “그려지는 것”이 아니다.</p><p>SwiftUI 내부 단계:</p><pre>1. State 변화 감지<br>2. Body 재계산<br>3. 이전 트리와 diff<br>4. Render Tree 업데이트<br>5. Display List 생성<br>6. Core Animation / Metal 전달</pre><p>실제 그려지는 것은:</p><ul><li>Render Tree</li><li>Display List</li></ul><p>우리가 작성한 View struct는 그저 <strong>설계도 입력값</strong>일 뿐이다.</p><h3>5. AttributeGraph: SwiftUI의 숨겨진 심장</h3><p>SwiftUI는 AttributeGraph라는 내부 시스템을 사용한다.</p><p>이 시스템이 하는 일:</p><ul><li>상태 의존성 추적</li><li>변경 전파</li><li>최소 업데이트 계산</li></ul><p>UIKit은:</p><pre>setNeedsLayout()<br>layoutSubviews()</pre><p>SwiftUI는:</p><pre>@State 변경 → AttributeGraph diff → 최소 재렌더</pre><p>이 차이가 성능의 핵심이다.</p><p>SwiftUI는 “뷰 계층 유지”가 아니라 <strong>상태 변화에 따른 계산 그래프 갱신</strong>을 한다.</p><h3>6️⃣ 왜 View Hierarchy Debugger가 무의미해지는가</h3><p>View Debugger는 UIKit 전용 철학이다.</p><p>전제 조건:</p><ul><li>객체가 존재해야 한다</li><li>부모-자식 관계가 유지되어야 한다</li></ul><p>SwiftUI는:</p><ul><li>값 타입</li><li>매번 재생성</li><li>내부 최적화 flatten</li><li>Layout 엔진 별도 처리</li></ul><p>View Debugger에 보이는 것은:</p><pre>_UIHostingView<br> └─ Render Tree</pre><p>코드 트리가 아니다. 그래서 집착하면 안 된다.</p><h3>7️⃣ SwiftUI Flattening이 일어나는 이유</h3><p>SwiftUI는 가능한 한 View를 병합한다.</p><p>예:</p><pre>Text(&quot;A&quot;)<br>Text(&quot;B&quot;)</pre><p>이것은 실제로는:</p><ul><li>두 개의 텍스트 draw command</li></ul><p>중간에 VStack이 있더라도 Layout 계산 후 display list에서는 flatten될 수 있다.</p><p>SwiftUI의 목표는:</p><blockquote><strong><em>뷰 트리를 유지하는 것</em></strong><em>이 아니라 </em><strong><em>최소한의 GPU 명령을 만드는 것</em></strong></blockquote><p>UIKit은 View 중심 SwiftUI는 Render 중심</p><h3>8️⃣ 진짜 디버깅은 어디서 해야 하는가</h3><ol><li>_printChanges()</li><li>onChange</li><li>Instruments → SwiftUI template</li><li>View Body 호출 횟수 추적</li><li>State 설계 검토</li></ol><p>SwiftUI에서의 디버깅 질문은 바뀌어야 한다.</p><p>UIKit식 질문:</p><blockquote><em>왜 이 View가 여기 있지?</em></blockquote><p>SwiftUI식 질문:</p><blockquote><em>왜 body가 다시 계산됐지?<br> 왜 이 state가 dependency graph에 묶였지?</em></blockquote><h3>9️⃣ 고급 팁: Body 호출은 공짜가 아니다</h3><p>많은 개발자가 오해한다. <strong>SwiftUI는 struct니까 가볍다 </strong>이다 이건<strong> </strong>틀렸다.</p><p>Body 재계산은:</p><ul><li>dependency graph 평가</li><li>layout 계산</li><li>diff 비교</li></ul><p>를 동반한다. 불필요한 상태 의존을 줄여야 한다.</p><p>예:</p><pre>@StateObject var viewModel</pre><p>vs</p><pre>@ObservedObject var viewModel</pre><p>의 차이는 단순 생명주기 문제가 아니라<br> <strong>graph 연결 범위 문제</strong>다.</p><h3>결론</h3><p>SwiftUI는 UIView 대체제가 아니다.</p><ul><li>객체 트리가 아니다</li><li>상태 기반 계산 시스템이다</li><li>타입 시스템 위에 세워진 렌더 엔진이다</li></ul><p>View Debugger에 집착하는 순간 이미 UIKit 사고방식에 묶여 있다.</p><p>SwiftUI를 제대로 이해하려면:</p><ul><li>타입 트리를 이해하고</li><li>AttributeGraph를 이해하고</li><li>Render 단계와 Display List를 이해해야 한다</li></ul><p>그때부터 SwiftUI는 <strong>마법</strong>이 아니라 <strong>예측 가능한 시스템</strong>이 된다.</p><h3>참고 자료</h3><p>- [SwiftUI Under the Hood — WWDC](https://developer.apple.com/videos/play/wwdc2023/10160/)</p><p>- [Demystify SwiftUI — WWDC 2021](https://developer.apple.com/videos/play/wwdc2021/10022/)</p><p>- [SwiftUI View Lifecycle](https://www.donnywals.com/understanding-swiftui-view-lifecycle/)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a6dc26a8f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Swift] AsyncStream의 비밀?]]></title>
            <link>https://gaeng2y.medium.com/swift-asyncstream%EC%9D%98-%EB%B9%84%EB%B0%80-2ebb014f1ccb?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ebb014f1ccb</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 13:23:28 GMT</pubDate>
            <atom:updated>2026-03-24T02:58:44.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Swift] Screet of AsyncStream</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZtKIs3fPawx8gIhq" /><figcaption>Photo by <a href="https://unsplash.com/@rzunikoff?utm_source=medium&amp;utm_medium=referral">Robert Zunikoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Swift Concurrency가 도입되면서 많은 iOS 개발자들이 Combine 파이프라인을 async/await 기반 코드로 마이그레이션하고 있습니다. 이때 AnyPublisher의 가장 직관적인 대안으로 선택되는 것이 바로 AsyncStream입니다. 겉으로 보면 둘은 매우 비슷해 보입니다.</p><blockquote><em>“Publisher가 값을 방출(emit)하듯, AsyncStream도 값을 yield하니까 같은 거 아닌가?”</em></blockquote><p>하지만 실제 프로젝트에서 그대로 치환했다가 다음과 같은 현상을 겪는 경우가 많습니다.</p><ul><li>같은 ViewModel을 구독하는데 어떤 View는 데이터를 받고</li><li>어떤 View는 데이터를 받지 못한다</li><li>재현은 되는데 원인이 불명확하다</li></ul><p>이 문제의 핵심은 바로 소비 모델(Consume Pattern)의 차이입니다.</p><p>오늘은 AsyncStream과 Combine의 본질적인 차이인 <strong>Unicast(Single Consume)</strong> vs <strong>Multicast(Multi Consume)</strong>를 정확히 정리해 보겠습니다.</p><h3>1. 멘탈 모델: 줄 서기 vs 방송</h3><p>이 차이를 이해하려면 먼저 머릿속 그림을 바꿔야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hTXv03BfgRDuQ431" /><figcaption>Photo by <a href="https://unsplash.com/@heyquilia?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>AsyncStream: 은행 창구</h3><p>AsyncStream은 <strong>Pull 기반 AsyncSequence</strong>입니다. 은행 창구를 떠올려 보세요.</p><ol><li>손님(데이터)이 번호표를 뽑고 기다립니다.</li></ol><p>2. 창구 직원이 두 명(A, B) 있습니다.</p><p>3. 하지만 <strong>1번 손님은 오직 한 명의 직원에게만 갑니다.</strong></p><p>1번 손님을 A가 처리했다면 B는 1번 손님을 절대 볼 수 없습니다.</p><p>👉 이미 소비된 데이터는 사라집니다.</p><p>이것이 <strong>Single Consume (Unicast)</strong> 입니다.</p><h3>Combine: 라디오 방송</h3><p>Combine(특히 share() 또는 multicast)은 <strong>Push 기반 Observer 패턴</strong>입니다. 라디오 방송국을 생각해 보세요.</p><ol><li>방송국에서 노래(데이터)를 틉니다.</li></ol><p>2. 주파수를 맞춘 모든 라디오가 동시에 같은 노래를 듣습니다.</p><p>👉 하나의 데이터가 모든 구독자에게 전달됩니다.</p><p>이것이 <strong>Multi Consume (Multicast)</strong> 입니다.</p><h3>[Diagram] 데이터 흐름 비교</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*dAGh9cK6bPlleQnc" /></figure><p><strong>AsyncStream은 데이터를 나눠 갖고, Combine은 복제하여 전달합니다.</strong></p><h3>2. 코드로 보는 경쟁적 소비</h3><p>AsyncStream 하나를 두 개의 Task에서 동시에 for await로 구독하면 어떤 일이 벌어질까요?</p><pre>let numberStream = AsyncStream&lt;Int&gt; { continuation in<br>    for i in 1...5 {<br>        continuation.yield(i)<br>    }<br>    continuation.finish()<br>}<br><br>Task {<br>    for await number in numberStream {<br>        print(&quot;🔴 소비자 A 획득: \(number)&quot;)<br>    }<br>}<br>Task {<br>    for await number in numberStream {<br>        print(&quot;🔵 소비자 B 획득: \(number)&quot;)<br>    }<br>}</pre><h4>실행 결과 (중요)</h4><pre>🔴 소비자 A 획득: 1<br>🔵 소비자 B 획득: 2<br>🔵 소비자 B 획득: 3<br>🔴 소비자 A 획득: 4<br>🔵 소비자 B 획득: 5</pre><p>순서는 매번 달라질 수 있습니다. 하지만 중요한 점은 이것입니다.</p><blockquote><strong><em>두 소비자가 같은 데이터를 받지 않는다.</em></strong></blockquote><h3>왜 이런 일이 발생할까?</h3><p>AsyncSequence는 내부적으로 AsyncIterator를 사용합니다. for await 루프는 매번:</p><pre>await iterator.next()</pre><p>를 호출합니다. 이 next() 호출은 단순 조회가 아니라:</p><blockquote><strong><em>대기열에서 하나를 꺼내는 소비(Consume) 동작 입니다.</em></strong></blockquote><p>이미 꺼낸 데이터는 사라집니다. 따라서 여러 Task가 동시에 접근하면 데이터를 서로 가져가게 됩니다. 이것은 버그가 아니라 <strong>의도된 설계입니다. </strong>(<a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0314-async-stream.md">SE-0314 AsyncStream Proposal</a> 참고)</p><h3>3. 핵심 비교 정리</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a680F4kd6LnjlpblY9hLPQ.png" /></figure><h3>4. Concurrency 환경에서 Multicast는 어떻게 하나요?</h3><p>AsyncStream이 Single Consume이라면 Concurrency 환경에서는 멀티캐스트를 어떻게 구현해야 할까요?</p><h3>방법 1. Swift Async Algorithms의 share() (권장)</h3><p>Apple의 오픈소스 라이브러리 <a href="https://github.com/apple/swift-async-algorithms">Swift Async Algorithms</a>는 멀티캐스트를 위한 share()를 제공합니다. (<a href="https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0016-share.md">SAA-0016</a>)</p><pre>import AsyncAlgorithms<br><br>  // 원본 AsyncStream을 share()로 감싸면 multi-consumer 가능<br>  let source: AsyncStream&lt;Int&gt; = AsyncStream { continuation in<br>      continuation.yield(1)<br>      continuation.yield(2)<br>      continuation.yield(3)<br>  }<br><br>  let shared = source.share()  // 기본: .bounded(1) — back-pressure, 값 유실 없음<br><br>  Task {<br>      for await value in shared {<br>          print(&quot;A:&quot;, value)<br>      }<br>  }<br><br>  Task {<br>      for await value in shared {<br>          print(&quot;B:&quot;, value)<br>      }<br>  }</pre><p>이제 두 Task 모두 동일한 값을 받습니다.</p><blockquote>주의: share()는 replay가 없으므로, 현재 언어 값을 late-join 구독자에게 전달하려면 actor에 current 값을 별도로 보관하고 구독 시 초기값을 직접 전달하는 래퍼가 필요합니다.</blockquote><h3>방법 2. @Published의 values 활용</h3><pre>@Published var state: AppState</pre><p>$state.values는 AsyncSequence를 제공합니다. 중요한 점은:</p><blockquote><em>각 구독자가 별도의 AsyncSequence를 생성한다는 것</em></blockquote><p>즉, 각 구독자가 독립적으로 값을 수신합니다. 다만 내부적으로는 Combine Publisher 기반이므로 완전히 AsyncStream과 동일한 구조는 아닙니다.</p><h3>5. 언제 무엇을 써야 할까?</h3><p>정답은 의외로 단순합니다.</p><h3>AsyncStream은 “일감(Job)”입니다.</h3><ul><li>한 번 처리되면 끝</li><li>중복 처리되면 안 됨</li><li>Queue 성격</li></ul><p>예:</p><ul><li>다운로드 진행</li><li>소켓 패킷 처리</li><li>백그라운드 작업</li></ul><h3>Combine / Broadcast는 “뉴스”입니다.</h3><ul><li>모두가 알아야 함</li><li>상태 공유</li><li>이벤트 전파</li></ul><p>예:</p><ul><li>로그인 상태</li><li>테마 변경</li><li>UI 상태 바인딩</li></ul><h3>결론</h3><p>AnyPublisher를 AsyncStream으로 무작정 치환하는 것은 위험합니다.</p><p>겉모습은 비슷해도 <strong>데이터 소비 모델이 완전히 다릅니다. </strong>리팩터링 전에 반드시 자문해 보세요.</p><blockquote><em>이 데이터는 나눠 가져야 하는가? 아니면 모두가 동시에 알아야 하는가?</em></blockquote><p>이 질문에 대한 답이AsyncStream을 쓸지, share()를 쓸지를 결정해 줍니다.</p><h3>References</h3><h3>1. Swift Evolution SE-0314</h3><p><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0314-async-stream.md">swift-evolution/proposals/0314-async-stream.md at main · swiftlang/swift-evolution</a></p><h3>2. WWDC 2021 — Meet AsyncSequence</h3><p><a href="https://developer.apple.com/videos/play/wwdc2021/10058/">Meet AsyncSequence - WWDC21 - Videos - Apple Developer</a></p><h3>3. Apple Developer Documentation — AsyncStream</h3><p><a href="https://developer.apple.com/documentation/swift/asyncstream">AsyncStream | Apple Developer Documentation</a></p><h3>4. Swift Async Algorithms</h3><p><a href="https://github.com/apple/swift-async-algorithms">GitHub - apple/swift-async-algorithms: Async Algorithms for Swift</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ebb014f1ccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS] Core Data와 Codable]]></title>
            <link>https://gaeng2y.medium.com/ios-core-data%EC%99%80-codable-317f4afbd967?source=rss-6c83e1283199------2</link>
            <guid isPermaLink="false">https://medium.com/p/317f4afbd967</guid>
            <category><![CDATA[dto]]></category>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[gaeng2y]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 15:39:28 GMT</pubDate>
            <atom:updated>2026-02-09T15:39:28.479Z</atom:updated>
            <content:encoded><![CDATA[<p>오늘은 제가 참고했던 외국 포스팅을 참고 및 추가로 조사한 내용에 대해 포스팅 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Lbvq59_c3maDu4Z" /><figcaption>Photo by <a href="https://unsplash.com/@ricvath?utm_source=medium&amp;utm_medium=referral">Richard Horvath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Core Data를 사용하는 프로젝트에서 서버 통신을 구현하다 보면 늘 마주치는 고민이 있습니다.</p><blockquote>“JSON을 받아서 파싱하는 Codable Struct(DTO)를 따로 만들고, 그걸 다시 NSManagedObject로 변환해야 하나? 그냥 Core Data 객체가 바로 JSON을 입으면 안 될까?&quot;</blockquote><p>하지만 막상 NSManagedObject에 Codable을 채택하려고 하면 컴파일러는 온갖 에러를 뱉어냅니다. 오늘은 Donny Wals의 아티클을 참고하여, <strong>Core Data 객체(NSManagedObject)가 Codable을 직접 수용하는 방법</strong>과 그 과정에서 얻을 수 있는 인사이트를 정리해 봅니다.</p><h3>1. 왜 바로 안 될까?</h3><p>Decodable 프로토콜은 init(from: Decoder)라는 이니셜라이저를 요구합니다. 일반적인 Struct라면 컴파일러가 이를 자동으로 만들어주지만, NSManagedObject는 상황이 다릅니다.</p><p><strong>Core Data 객체는 초기화될 때 반드시 </strong><strong>NSManagedObjectContext가 필요하기 때문입니다.</strong></p><p>우리가 흔히 사용하는 Core Data 초기화 구문은 다음과 같습니다.</p><pre>init(context: NSManagedObjectContext)</pre><p>하지만 Decodable의 init(from: Decoder)에는 Context를 넘겨줄 구멍(파라미터)이 없습니다. 바로 이 지점에서 <strong>의존성 주입의 문제</strong>가 발생합니다.</p><h3>2. 해결의 열쇠: Decoder.userInfo</h3><p>이 문제를 해결하기 위한 가장 우아한 방법은 JSONDecoder가 가진 userInfo 딕셔너리를 활용하는 것입니다. 이 딕셔너리는 디코딩 과정 전반에 걸쳐 데이터를 전달하는 일종의 &#39;배낭&#39; 역할을 합니다.</p><p>우리는 이 배낭에 <strong>Context</strong>를 몰래 넣어서 init(from:) 내부로 전달할 것입니다.</p><h3>Step 1. Context를 담을 Key 정의하기</h3><p>userInfo의 키는 CodingUserInfoKey 타입을 사용합니다. 안전한 접근을 위해 확장을 통해 키를 정의해 줍니다.</p><pre>extension CodingUserInfoKey {<br>    static let managedObjectContext = CodingUserInfoKey(rawValue: &quot;managedObjectContext&quot;)!<br>}</pre><h3>Step 2. Entity 설정 변경 (Codegen)</h3><p>Xcode가 자동으로 생성해주는 클래스 파일은 수정할 수 없으므로, 우리가 직접 커스텀 로직(init)을 작성할 수 있도록 설정을 바꿔야 합니다.</p><ul><li>.xcdatamodeld 파일 오픈</li><li>해당 Entity 선택</li><li>Inspector 패널 &gt; <strong>Codegen</strong> 설정을 Category/Extension으로 변경</li></ul><blockquote><strong><em>Tip:</em></strong><em> </em><em>Category/Extension으로 설정하면 프로퍼티들은 Xcode가 Extension으로 자동 생성해주고, 클래스 정의(</em><em>class MyEntity: NSManagedObject) 부분만 우리가 직접 작성할 수 있게 됩니다.</em></blockquote><h3>Step 3. NSManagedObject에 Decodable 구현하기</h3><p>이제 직접 클래스를 정의하고 Decodable을 구현합니다. 핵심은 decoder.userInfo에서 Context를 꺼내는 부분입니다.</p><pre>import CoreData<br><br>class MyEntity: NSManagedObject, Decodable {<br>    <br>    // 1. CodingKeys 정의 (JSON 키와 매핑)<br>    enum CodingKeys: CodingKey {<br>        case id, title, createdAt<br>    }<br>    <br>    // 2. Decodable 이니셜라이저 구현<br>    required convenience init(from decoder: Decoder) throws {<br>        // 배낭(userInfo)에서 Context 꺼내기<br>        guard let context = decoder.userInfo[CodingUserInfoKey.managedObjectContext] as? NSManagedObjectContext else {<br>            throw DecoderConfigurationError.missingManagedObjectContext<br>        }<br>        <br>        // Context를 이용해 NSManagedObject 초기화<br>        self.init(context: context)<br>        <br>        // 데이터 매핑 시작<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        self.id = try container.decode(Int64.self, forKey: .id)<br>        self.title = try container.decode(String.self, forKey: .title)<br>        self.createdAt = try container.decode(Date.self, forKey: .createdAt)<br>    }<br>}<br>// 에러 처리를 위한 간단한 Enum<br>enum DecoderConfigurationError: Error {<br>    case missingManagedObjectContext<br>}</pre><h3>Step 4. 실전 사용 (Decoding)</h3><p>이제 JSON을 디코딩할 때 context를 주입해주기만 하면 됩니다.</p><pre>let decoder = JSONDecoder()<br>// 🔥 핵심: 디코더에게 Context 쥐어주기<br>decoder.userInfo[.managedObjectContext] = viewContext <br>do {<br>    let myEntities = try decoder.decode([MyEntity].self, from: jsonData)<br>    print(&quot;성공적으로 Core Data 객체로 변환되었습니다.&quot;)<br>    // try viewContext.save() // 필요시 저장<br>} catch {<br>    print(error)<br>}</pre><h3>3. Encodable은 어떨까?</h3><p>반대로 Core Data 객체를 JSON으로 만들 때(Encodable)는 Context가 필요 없으므로 비교적 간단합니다. 다만, Core Data의 관계(Relationship)는 보통 NSSet 타입이므로, 이를 Swift의 Array나 Set으로 변환해주는 과정이 필요합니다.</p><pre>extension MyEntity: Encodable {<br>    public func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(id, forKey: .id)<br>        try container.encode(title, forKey: .title)<br>        // NSSet -&gt; Set or Array 변환 필요<br>    }<br>}</pre><h3>4. Insights: DTO vs. 직접 변환</h3><p>이 방식을 적용하면서 얻은 인사이트를 정리해 봅니다.</p><h4>장점</h4><ul><li><strong>중복 코드 감소:</strong> 별도의 DTO를 만들고, 이를 다시 Core Data 객체로 옮겨 담는 매핑 코드가 사라집니다.</li><li><strong>단일 진실 공급원:</strong> 모델 정의가 Core Data Entity 하나로 관리되므로 구조 파악이 쉽습니다.</li></ul><h4>단점 및 주의점</h4><ul><li><strong>보일러플레이트:</strong> Codable을 채택하면 init(from:)과 CodingKeys를 모두 수동으로 작성해야 합니다. 속성이 많아지면 꽤 번거로운 작업이 됩니다.</li><li><strong>API 의존성:</strong> 서버 API의 응답 구조가 변경되면 Core Data 모델 코드도 직접 수정해야 합니다. (DB 스키마와 API 스펙이 강결합됨)</li><li><strong>스레드 안전성:</strong> Core Data는 스레드에 매우 민감합니다. 디코딩이 일어나는 스레드와 주입된 Context가 속한 스레드가 일치하는지 항상 주의해야 합니다.</li></ul><h3>결론</h3><p>서버 API 응답 구조와 로컬 DB 스키마가 거의 일치하고, 데이터 구조가 복잡하지 않다면 이 방식은 생산성을 크게 높여줍니다. 하지만 데이터 가공이 많이 필요하거나, 로컬 저장 구조가 서버와 판이하게 다르다면 여전히 <strong>DTO 패턴</strong>을 사용하는 것이 유지보수 측면에서 안전할 수 있습니다.</p><h3>References</h3><ul><li><a href="https://www.donnywals.com/using-codable-with-core-data-and-nsmanagedobject/">Donny Wals — Using Codable with Core Data and NSManagedObject</a></li><li><a href="https://developer.apple.com/documentation/coredata/nsmanagedobject">Apple Developer Documentation — NSManagedObject</a></li><li><a href="https://www.google.com/search?q=https://developer.apple.com/documentation/foundation/jsondecoder/2892543-userinfo">Apple Developer Documentation — JSONDecoder.userInfo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=317f4afbd967" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>