<?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 Gülenay Gül on Medium]]></title>
        <description><![CDATA[Stories by Gülenay Gül on Medium]]></description>
        <link>https://medium.com/@glnygl94?source=rss-e9d1f580f5cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YGrGRpKGnxuJpVZIXCj1Ig@2x.jpeg</url>
            <title>Stories by Gülenay Gül on Medium</title>
            <link>https://medium.com/@glnygl94?source=rss-e9d1f580f5cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:59:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@glnygl94/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[Migrating “@Observable” + Combine | SwiftUI #4]]></title>
            <link>https://medium.com/@glnygl94/migrating-observable-combine-swiftui-4-6fb5111de41e?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb5111de41e</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[observableobject]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 10:16:53 GMT</pubDate>
            <atom:updated>2024-12-09T12:51:50.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nRXQeGn2Nqqbl0kY7IYrQ.png" /></figure><p>In my previous article, I explained how to use ObservableObject protocol in Combine. If you haven’t read it yet, You should <strong>DEFINITELY</strong> ❗read it first before diving into this article because I’ll use the same examples and <strong>refer a lot</strong>.</p><p><a href="https://medium.com/@glnygl94/using-observableobject-in-combine-swiftui-3-6b33dd51749f">Using ObservableObject in Combine | SwiftUI #3</a></p><p>In the first article, we’ve created a simple login form and validated its values using Combine.</p><p>Now, we’ll do the same example using “@Observable” macro.</p><p>Let’s start defining our NewLoginViewModel and properties like below.</p><pre>@Observable<br>final class NewLoginViewModel {<br>    <br>    var mail: String = &quot;&quot;<br>    var password: String = &quot;&quot;<br>    <br>    var mailWarning: String = &quot;&quot;<br>    var passwordWarning: String = &quot;&quot;<br>    <br>    var isButtonDisabled = true<br>}</pre><p>I’ve already explained steps of subscribing to a publisher in Combine.</p><ol><li><strong>Get Publisher</strong></li><li><strong>Receive UI changes on Main Thread</strong></li><li><strong>Sink publisher to receive value</strong></li><li><strong>Store AnyCancellable</strong></li></ol><p>According to these steps, first we need a publisher.</p><p>When using ObservableObject protocol, we could access a “@Published”property’s publisher by <strong>“$”</strong> symbol. What about @Observable” macro?</p><p><strong>You can not directly access publisher of a property</strong> while using @Observable” macro. Therefore <strong>you need to create custom publishers </strong>for properties.</p><h3>Create Custom Publisher ✅</h3><p>Custom publishers can be created in two ways:</p><ul><li>PassthroughSubject</li><li>CurrentValueSubject</li></ul><h3>Subject</h3><p>Subject protocol is a publisher that you can use to ”inject” values into a stream. PassthroughSubject and CurrentValueSubject classes which conform this protocol allow us to create custom publishers.</p><p>Using send functions in this protocol, you can directly send values, completions, or subscriptions to the subscribers of these objects (publishers). This makes our objects act as both publishers and subscribers depending on situation.</p><pre>protocol Subject&lt;Output, Failure&gt; : AnyObject, Publisher {<br><br>    /// Sends a value to the subscriber.<br>    func send(_ value: Self.Output)<br><br>    /// Sends a completion signal to the subscriber.<br>    func send(completion: Subscribers.Completion&lt;Self.Failure&gt;)<br><br>    /// Sends a subscription to the subscriber.<br>    func send(subscription: any Subscription)<br>}</pre><p>Lets see how that works.</p><h4>PassthroughSubject</h4><p>Here is how we can define PassthroughSubject for mail and password. The first parameter (Output) represents value type while the second one (Failure) represents error type.</p><p><strong>1- Get Publisher</strong></p><pre>//  PassthroughSubject <br>//  Output: Value<br>//  Failure: Error<br><br>final class PassthroughSubject&lt;Output, Failure&gt; where Failure : Error</pre><pre>// Publishers for mail and password. We won&#39;t handle error case so used Never<br><br>private let mailPublisher = PassthroughSubject&lt;String, Never&gt;()<br>private let passwordPublisher = PassthroughSubject&lt;String, Never&gt;()</pre><p>We’ve created publishers, now we need to inject values to them. To do this, we can use send func in protocol.</p><pre>    var mail: String = &quot;&quot; {<br>        didSet {<br>            mailPublisher.send(mail) <br>        }<br>    }<br>    var password: String = &quot;&quot; {<br>        didSet {<br>            passwordPublisher.send(password)<br>        }<br>    }</pre><p>Whenever you type a value for mail or password, didSet blocks will be triggered and values will be sent to publishers via send function.</p><p>In previous article, I also mentioned sink function and receiveCompletion block.</p><pre>          .sink { [weak self] completion in<br>                switch completion {<br>                case .finished:<br>                    print(&quot;finished&quot;)<br>                case .failure(let error):<br>                    print(&quot;failed&quot;)<br>                }<br>            } receiveValue: { [weak self] value in<br>                self?.value = value<br>            }</pre><p>Although I won’t cover completion case for this login example but you can also send a completion status to PassthroughSubject using <strong>.send(completion:) </strong>func.</p><pre>    enum CustomError: Error {<br>        case failed<br>    }<br>    <br>    private let customPublisher = PassthroughSubject&lt;String, Error&gt;()<br>    <br>    private func sendCompletion() {<br>        customPublisher.send(completion: .finished)<br>    }<br>    <br>    private func sendError() {<br>        customPublisher.send(completion: .failure(CustomError.failed))<br>    }</pre><p><strong>2- Receive UI changes on the Main Thread</strong></p><p>Since typing happens on main thread there’s no need to switch threads.</p><p><strong>3- Sink publisher to receive value / 4- Store AnyCancellable</strong></p><pre>    private func subscribeToMail() {<br>        mailPublisher<br>            .map { mail in<br>                return mail.isEmpty || mail.contains(&quot;@gmail.com&quot;) ? &quot;&quot; : &quot;Enter your gmail address&quot;<br>            }<br>            .sink { [weak self] mailWarning in<br>                self?.mailWarning = mailWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    private func subscribeToPassword() {<br>        passwordPublisher<br>            .map { password in<br>                return password.isEmpty || password.count &gt;= 6 ? &quot;&quot; : &quot;Password should be at least 6 characters&quot;<br>            }<br>            .sink { [weak self] passwordWarning in<br>                self?.passwordWarning = passwordWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><p>As you can see subscription functions are<strong> almost same</strong> with funcs from previous article. The only difference is that instead of accessing the publisher by “$” symbol, we’re using PassthroughSubject.</p><p>What about CurrentValueSubject?</p><h4>CurrentValueSubject</h4><p>CurrentValueSubject is essentially like PassthroughSubject with an initial value (current value).</p><p>Let’s say login form includes a userName field so we can define a CurrentValueSubject just like below and use an empty string as default value.</p><pre>var userName: String = &quot;&quot; {<br>        didSet {<br>            guard oldValue != userName else { return }<br>            userNamePublisher.send(userName)<br>        }<br>    }<br>    <br>private let userNamePublisher = CurrentValueSubject&lt;String, Never&gt;(&quot;&quot;) // initial value is &quot;&quot;</pre><p><strong>When using CurrentValueSubject, you can either send values to this publisher using send function or set directly value property.</strong></p><pre>    private func sendValueWithFunction() {<br>        userNamePublisher.send(&quot;Mary&quot;) <br>    }<br>    <br>    private func sendValueDirectly() {<br>        userNamePublisher.value = &quot;Jane&quot;<br>    }</pre><p>Just like with PassthroughSubject, you can subscribe to CurrentValueSubject and listen value changes.</p><pre>    private func subscribeToUserName() {<br>        userNamePublisher<br>            .map { userName in<br>                return userName.isEmpty || userName.count &gt; 6 ? &quot;&quot; : &quot;Enter valid userName&quot;<br>            }<br>            .sink { [weak self] userNameWarning in<br>                self?.userNameWarning = userNameWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><p>To enable the login button we need to subscribe to <strong>both</strong> values <strong>simultaneously.</strong></p><pre>   private func subscribeToAll() {<br>        mailPublisher<br>            .combineLatest(passwordPublisher)<br>            .map { mail, password in<br>                return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .assign(to: \.isButtonEnabled, on: self)<br>            .store(in: &amp;cancellables)<br>    }</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*yQRKQ-JlD_ZT4wmee-1vMg.gif" /></figure><p>So creating custom publishers while using “@Observable” macro with Combine is quite simple.</p><p>Now, let’s discuss another method you might encounter when trying to access directly publishers with “@Observable” macro and evaluate its pros and cons.</p><h3>“@ObservationIgnored” ❌</h3><p>I’ve already mentioned that “@Observable” macro publishes values by <strong>default</strong>. If you don’t want a property to be published, you should use “@ObservationIgnored”.</p><p>Technically, you can use both “@Published” and “@ObservationIgnored” at the same time with “@Observable” macro.</p><pre>    @ObservationIgnored<br>    @Published<br>    var mail: String = &quot;&quot;</pre><p>In this example, <strong>“@ObservationIgnored” prevents mail value from being published by default, but “@Published” republishes manually.</strong></p><p>This method allows you to access publisher by “$” symbol (just like with ObservableObject protocol) and subscribe to it as shown below.</p><pre>   private func subscribeToMail() {<br>        $mail<br>            .map { mail in<br>                return mail.isEmpty || mail.contains(&quot;@gmail.com&quot;) ? &quot;&quot; : &quot;Enter your gmail address&quot;<br>            }<br>            .sink { [weak self] mailWarning in<br>                self?.mailWarning = mailWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><p>We’ve only added “@ObservationIgnored” and it’s done.</p><p>⚠️ This may seem quick and easy solution. But is that really good way to do this? I don’t think so.</p><p>Even though we’ve manually published value using “@Published”, changes won’t effect UI because we defined our viewModel with “@State”.</p><pre>@State var viewModel = NewLoginViewModel()</pre><p>To make the issue a little bit clear I added a loginCount property to NewLoginViewModel so you can see how that really works.</p><pre>    @ObservationIgnored<br>    @Published<br>    var loginCount: Int = 0</pre><pre>            Button(&quot;Login&quot;) {<br>                viewModel.loginCount += 1<br>                print(&quot;\(viewModel.loginCount)&quot;)<br>            }<br>            .buttonStyle(.borderedProminent)<br>            .disabled(!viewModel.isButtonEnabled)<br><br>            Text(&quot;Login count: \(viewModel.loginCount)&quot;)</pre><p>⚠️ In this case, every time when you press the login button, loginCount will increase and new value will be printed to console but text view won’t update so UI will remain the same.</p><p>However, if you test our login example you’ll notice that mail property works seamlessly with this method. Because mail property is bound to Textfield using <strong>Binding</strong>.</p><pre>TextField(&quot;Mail&quot;, text: $viewModel.mail)</pre><p>To avoid this confusion instead of use this method I highly recommend you to create your own custom publishers.</p><p>I hope this article was helpful. Feel free to reach out if you have any questions and don’t forget to follow me. See you next time 🌸</p><p>Source code:</p><p><a href="https://github.com/glnygl/Medium">https://github.com/glnygl/Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb5111de41e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ObservableObject in Combine | SwiftUI #3]]></title>
            <link>https://medium.com/@glnygl94/using-observableobject-in-combine-swiftui-3-6b33dd51749f?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b33dd51749f</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[observableobject]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 10:48:56 GMT</pubDate>
            <atom:updated>2024-12-04T15:24:57.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROifg6HsrUEJxl0WlXM46g.png" /></figure><p>In my previous articles I discussed “@Observable” macro, its differences from ObservableObject protocol and important points to consider when using them. If you haven’t read those yet I highly recommend starting there.</p><ul><li><a href="https://medium.com/@glnygl94/using-observable-macro-instead-of-observableobject-and-passing-multiple-objects-swiftui-1-e6a6d5a1c181">Using “@Observable” macro instead of ObservableObject and passing multiple objects| SwiftUI #1</a></li><li><a href="https://medium.com/@glnygl94/things-to-consider-when-using-observable-macro-in-async-operations-swiftui-2-a509807d5230">Things to consider when using “@Observable” macro in async operations | SwiftUI #2</a></li></ul><p>Today I’ll explain differences between “@Observable” macro and ObservableObject protocol in Combine framework with examples.</p><p>Imagine we’ve a simple login form with mail and password fields. Mail must contain “‘@gmail.com” string and password must have at least 6 characters. While typing we should display required conditions below textfields, when these conditions are met we should enable button and remove warning texts as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*yQRKQ-JlD_ZT4wmee-1vMg.gif" /></figure><p>First do this example with ObservableObject (<strong>without using Combine</strong>) to better understand logic of observation.</p><p>We start by creating a LoginViewModel class that conforms ObservableObject protocol. In this class we define string properties for mail and password, as well as warning texts.</p><pre>import Foundation<br><br>final class LoginViewModel: ObservableObject {<br>    <br>    @Published var mail: String = &quot;&quot;<br>    @Published var password: String = &quot;&quot;<br>    <br>    @Published var mailWarning: String = &quot;&quot;<br>    @Published var passwordWarning: String = &quot;&quot;<br>    <br>}</pre><p>And create a LoginView just like below.</p><pre>struct LoginView: View {<br>    <br>    @StateObject var viewModel = LoginViewModel()<br>    <br>    var body: some View {<br>        VStack(spacing: 30) {<br>            TextField(&quot;Mail&quot;, text: $viewModel.mail)<br>                .textFieldStyle(.roundedBorder)<br>                .keyboardType(.emailAddress)<br>                .showWarning(viewModel.mailWarning)<br><br>            SecureField(&quot;Password&quot;, text: $viewModel.password)<br>                .textFieldStyle(.roundedBorder)<br>                .showWarning(viewModel.passwordWarning)<br>            <br>            Button(&quot;Login&quot;) {<br>                print(&quot;Login Successful!&quot;)<br>            }<br>            .buttonStyle(.borderedProminent)<br>            .disabled(!viewModel.isButtonEnabled)<br>        }<br>        .padding()<br>    }<br>}</pre><blockquote><strong><em>Note:</em></strong><em> To improve code readability and display warning messages, I created a WarningModifier and added showWarning to each textfields.</em></blockquote><pre>struct WarningModifier: ViewModifier {<br>    let warning: String<br><br>    @ViewBuilder<br>    func body(content: Content) -&gt; some View {<br>        content.overlay(alignment: .leadingFirstTextBaseline) {<br>            Text(warning)<br>                .font(.system(size: 12).bold())<br>                .foregroundStyle(.gray)<br>                .offset(y: 24)<br>        }<br>    }<br>}<br><br>extension View {<br>    func showWarning(_ warning: String) -&gt; some View {<br>        ModifiedContent(content: self, modifier: WarningModifier(warning: warning))<br>    }<br>}</pre><p>We want to validate mail and password based on our rules and show warning texts until validation is successful. You can easily do this with <strong>property observers</strong>.</p><pre>    @Published var mail: String = &quot;&quot; {<br>        didSet {<br>            guard oldValue != mail else { return } <br>            mailWarning =  mail.isEmpty || mail.contains(&quot;@gmail.com&quot;) ? &quot;&quot; : &quot;Enter your gmail address&quot;<br>        }<br>    }<br>    <br>    @Published var password: String = &quot;&quot; {<br>        didSet {<br>            guard oldValue != password else { return }<br>            passwordWarning = password.isEmpty || password.count &gt;= 6 ? &quot;&quot; : &quot;Password should be at least 6 characters&quot;<br>        }<br>    }</pre><p>Each time you enter a value for mail or password, didSet functions will be triggered and warning properties ​​will be updated according to our validation rules. Since all values are already marked with <strong>“@Published” </strong>wrapper, UI will automatically update.</p><p>Easy-peasy 👌🏻</p><p>Of course this may be the easiest way for our case but my goal is to explain how Combine works. So if you are ready let’s dive into Combine. 🚀</p><h4>ObservableObject in Combine</h4><p>As I mentioned earlier, ObservableObject protocol is part of Combine framework which relies on <strong>Publisher/Subscriber</strong> mechanism. What is that mean?</p><p>In this mechanism,<strong> publishers emit value changes while subscribers receive these values ​​through subscription.</strong></p><p>ObservableObject protocol allows us to write Combine operations easily since we can <strong>directly access publishers</strong>. By using <strong>“@Published”</strong> property publishers can be accessed with<strong>“$” symbol</strong>.</p><h4><strong>Subscribe to a publisher</strong></h4><p>Steps for subscribing to a publisher can be summarized as follows:</p><ol><li>Get Publisher</li><li>Receive UI changes on Main Thread</li><li>Sink publisher to receive value</li><li>Store AnyCancellable</li></ol><h4>1- Get Publisher</h4><p>You can access publisher of “@Published” property using <strong>“$”</strong> symbol.</p><pre>@Published var mail: String = &quot;&quot; // property<br>$mail // publisher for mail property</pre><h4>2- Receive UI changes on Main Thread</h4><p>When updating a value of UI element, operation must perform on main thread. ⚠️</p><p>If you modify a value affecting UI from background thread, you may encounter a <strong>thread warning</strong>.</p><p>You can find reasons and solutions for this issue in my previous article.</p><p><a href="https://medium.com/@glnygl94/things-to-consider-when-using-observable-macro-in-async-operations-swiftui-2-a509807d5230">Things to consider when using “@Observable” macro in async operations | SwiftUI #2</a></p><pre>.receive(on: DispatchQueue.main)</pre><blockquote><strong><em>Note:</em></strong><em> Since typing already happens on main thread, there is no need to switch threads in this example.</em></blockquote><h4>3- Sink publisher to receive value</h4><p>Sink function allows us to subscribe to a publisher and monitor value changes.</p><p>There are two types of .sink functions as shown below. Both let us access to <strong>receiveValue</strong> through a <strong>completion handler</strong> and <strong>return an AnyCancellable object</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*HsZ-Qh1dBNdOnRDcJ1CpXQ.png" /></figure><p>The second function additionally includes a <strong>receiveCompletion</strong> handler block, which allows us to get and handle completion status.</p><pre>// First func <br><br>            .sink { [weak self] value in<br>                self?.value = value<br>            }<br>        <br>// Second func with receive completion<br><br>            .sink { [weak self] completion in<br>                switch completion {<br>                case .finished:<br>                    print(&quot;finished&quot;)<br>                case .failure(let error):<br>                    print(&quot;failed&quot;)<br>                }<br>            } receiveValue: { [weak self] value in<br>                self?.value = value<br>            }</pre><p>To prevent <strong>memory leaks </strong>define<strong> self as a weak reference</strong> in these completion handlers.</p><h4>4- Store AnyCancellable</h4><p>Sink function returns an AnyCancellable object which is <strong>essential for keeping subscription alive</strong>. If you don’t store or assign this object to a property the subscription will be <strong>deallocated immediately</strong>. ⚠️</p><p>You can create a cancellable in two ways:</p><pre>private var cancellable: AnyCancellable? // single cancellable <br>private var cancellables = Set&lt;AnyCancellable&gt;() // cancellable set</pre><p>If you are using a single cancellable, you should assign the subscription to this value. On the other hand, if you’ve more than one publisher and you want to cancel all at once in certain case you must chose cancellable set and store them as shown below.</p><pre>cancellable =  publisher<br>            .sink { [weak self] value in<br>                self?.value = value<br>            }<br><br>or <br>        publisher<br>            .sink { [weak self] value in<br>                self?.value = value<br>            }<br>            .store(in: &amp;cancellables)</pre><p>Now we can write subscription functions for mail and password values according to these informations.</p><pre>    private func subscribeToMail() {<br>        $mail<br>            .map { mail in<br>                return mail.isEmpty || mail.contains(&quot;@gmail.com&quot;) ? &quot;&quot; : &quot;Enter your gmail address&quot;<br>            }<br>            .sink { [weak self] mailWarning in<br>                self?.mailWarning = mailWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    private func subscribeToPassword() {<br>        $password<br>            .map { password in<br>                return password.isEmpty || password.count &gt;= 6 ? &quot;&quot; : &quot;Password should be at least 6 characters&quot;<br>            }<br>            .sink { [weak self] passwordWarning in<br>                self?.passwordWarning = passwordWarning<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><p>Let’s take a look at subscribeToMail func step by step.</p><ul><li>We accessed publisher mail value using by “$” symbol.</li><li>Since typing operation occurs on main thread we didn’t need to use receive func to switch threads.</li><li>We subscribed to publisher using sink func and retrieved the receiveValue.</li><li>Then we stored AnyCancellable object in cancellable set.</li></ul><p><strong>Why did we use map func and what would happen if we didn’t?</strong></p><p>If we didn’t use map func, receiveValue would be the same string that user typed. We processed this string according to our validation rules and passed it to sink function as mailWarning string.</p><p>Next step call these functions in initializer of LoginViewModel.</p><pre>    init() {<br>        subscribeToMail()<br>        subscribeToPassword()<br>    }</pre><h4>CombineLatest</h4><p>To enable login button when mail and password inputs pass validations, we need to subscribe and<em> </em>listen these two values <strong>simultaneously.</strong> CombineLatest func is really handy for this kind of situations.</p><blockquote><strong><em>Note:</em></strong> <em>CombineLatest func can subscribe up to 4 publishers.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUCo1RKJObbgpeWnTNeotQ.png" /></figure><p>First, we define a bool value and initially set it to false.</p><pre>@Published var isButtonEnabled = false</pre><p>Then we call combineLatest function of mail publisher and pass password publisher as a parameter .</p><pre>private func subscribeToAll() {<br>        $mail<br>            .combineLatest($password) <br>            .map { mail, password in<br>               return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .sink { [weak self] value in<br>                self?.isButtonEnabled = value<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><p>In subscribeToAll function we used combineLatest to monitor two publishers <strong>simultaneously</strong>, mapped them based on our rules, then passed resulting bool value to sink func and set isButtonEnabled property. Finally we stored AnyCancellable object.</p><p><strong>You can also do the same thing using CombineLatest struct.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*NkhwBR_f9M-MLPc-wueLrg.png" /></figure><p>To do this, call <strong>Publishers </strong>enum and select a CombineLatest func based on number of publishers you need. (up to 4 again)</p><pre>private func subscribeToAll() {<br>        Publishers.CombineLatest($mail, $password)<br>            .map { mail, password in<br>                return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .sink { [weak self] value in<br>                self?.isButtonEnabled = value<br>            }<br>            .store(in: &amp;cancellables)<br>    }</pre><h4>Assign</h4><p>We used sink function to assign receiveValue to isButtonEnabled property. If you want to <strong>assign one single value directly to another</strong>, you can use assign func.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*5zqvep4vcv8G0RwhVRSs6g.png" /></figure><p>There are two types of assign functions.</p><p>The first one allows you to <strong>pass publisher directly</strong>, does not require on parameter and <strong>manages subscription lifecycle internally </strong>❗ so you <strong>don’t need to use store func</strong>.</p><pre>private func subscribeToAll() {<br>        $mail<br>            .combineLatest($password)<br>            .map { mail, password in<br>               return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .assign(to: &amp;$isButtonEnabled) // assign to <br>    }</pre><p>The second one includes <strong>keyPath</strong> and<strong> root of the value</strong>. It <strong>requires storing subscription </strong>using store func or assigning it to an AnyCancellable property.</p><pre>private func subscribeToAll() { // used cancellable set<br>        $mail<br>            .combineLatest($password)<br>            .map { mail, password in<br>               return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .assign(to: \.isButtonEnabled, on: self)<br>            .store(in: &amp;cancellables)<br>    }<br><br>or<br><br>   private func subscribeToAll() { // used single cancellable<br>        cancellable = $mail <br>            .combineLatest($password)<br>            .map { mail, password in<br>                return ( mail.contains(&quot;@gmail.com&quot;) &amp;&amp;  password.count &gt;= 6 )<br>            }<br>            .assign(to: \.isButtonEnabled, on: self)<br>    }</pre><p>Here is the final result;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*yQRKQ-JlD_ZT4wmee-1vMg.gif" /></figure><p>I tried to briefly explain how ObservableObject works with Combine. To avoid making this article so long, I’ll cover “@Observable” macro in the next article. Thank you for reading and don’t forget to follow me 🌸</p><p>Source code: <a href="https://github.com/glnygl/Medium">https://github.com/glnygl/Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b33dd51749f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things to consider when using “@Observable” macro in async operations | SwiftUI #2]]></title>
            <link>https://medium.com/@glnygl94/things-to-consider-when-using-observable-macro-in-async-operations-swiftui-2-a509807d5230?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a509807d5230</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[observableobject]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 12:02:55 GMT</pubDate>
            <atom:updated>2024-11-25T14:15:30.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AUgHb_YuqglObN5_ankpA.jpeg" /></figure><p>In my previous article I explained “@Observable” macro and shared some tips. If you haven&#39;t read it yet I highly recommend starting there before diving into this one.</p><p><a href="https://medium.com/@glnygl94/using-observable-macro-instead-of-observableobject-and-passing-multiple-objects-swiftui-1-e6a6d5a1c181">Using “@Observable” macro instead of ObservableObject and passing multiple objects| SwiftUI #1</a></p><p>In this article we’ll discuss a common issue that you might encounter when using “@Observable” macro for async operations.</p><p>Let’s imagine we’re building a simple app that fetches data from service and displays data in a list view.</p><p>The endpoint we’ll use is: <a href="https://jsonplaceholder.typicode.com/posts"><strong>https://jsonplaceholder.typicode.com/posts</strong></a></p><p>First define a basic Network class like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d770add40ecd0c49103dcb86849182f9/href">https://medium.com/media/d770add40ecd0c49103dcb86849182f9/href</a></iframe><p>We have two request functions in our protocol. The first one uses <strong>URLSession.data</strong> func to fetch data and then decode this data to our generic model, while the second one uses <strong>dataTaskPublisher</strong> func to create publisher that we’ll use it later in our Combine func.</p><blockquote><strong>Note:</strong> The .data func works on iOS 15 and later.</blockquote><p>These funcs are just simple examples for combine and async/await cases. You can also use you own network funcs. <strong>The main idea is to fetch data asynchronously</strong>.</p><p>Next define a Post model based on API response.</p><pre>struct Post: Decodable {<br>    let userId : Int<br>    let id : Int<br>    let title : String<br>    let body : String<br>}</pre><p>I created a PostListViewModel that conforms <strong>ObservableObject</strong> protocol and in this view model we’ll fetch posts data using async<strong> fetchPosts </strong>func. After fetching we’ll send this data to UI with <strong>“@Published”</strong> posts variable and update our list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41a2c7ef8cd22d55148e25add72685f9/href">https://medium.com/media/41a2c7ef8cd22d55148e25add72685f9/href</a></iframe><p>In PostListView, we’ll call <strong>fetchPosts</strong> within <strong>.task</strong> block. Using “@StateObject” wrapper, we’ll bind updated posts data to ForEach loop to display posts in our list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4a0a67fd0ba303b2ead9b457bda871/href">https://medium.com/media/0a4a0a67fd0ba303b2ead9b457bda871/href</a></iframe><p>Everything seems fine so far and app will run as expected until you encounter a<strong> thread warning.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiauMf_uKD8mmKNUU7Qt3Q.png" /><figcaption>ObservableObject thread issue</figcaption></figure><p><strong>When you perform background tasks that affect UI (which runs on main thread) compiler alerts you about thread issue.</strong></p><p>In this example we’re trying to fetch data and setting posts array in background thread. However posts variable is marked with <strong>“@Published”</strong> property wrapper which means that <strong>variable will affect and update UI</strong>.</p><p>There are several ways to solve this issue.</p><p><strong>1- Using “@MainActor”</strong></p><p>The most common and straightforward solution is using “@MainActor”. <strong>“@MainActor” is a global actor that ensures async operations run on main thread.</strong></p><blockquote>You can mark <strong>entire class </strong>or<strong> specific functions </strong>with<strong> </strong>“@MainActor”.</blockquote><pre>@MainActor // Marked entire class <br>final class PostListViewModel: ObservableObject {<br>         ...<br>         ...<br>         ...<br> }<br><br>@MainActor // Marked specific func <br>func fetchPosts() async throws {<br>        ...<br>        ...<br>        ...<br> }</pre><p><strong>2- Using MainActor.run</strong></p><p>Another approach is to call <strong>MainActor.run</strong> within function where the value is being set.</p><blockquote><strong>Note:</strong> MainActor.run only works for <strong>sync</strong> operations.</blockquote><pre>            await MainActor.run {<br>                self.posts = data<br>            }</pre><p><strong>3- Using DispatchQueue</strong></p><p>You can also use DispatchQueue to switch to main thread. However, we don’t prefer to use this method anymore in modern Swift concurrency .</p><pre>          DispatchQueue.main.async {<br>               self.posts = data<br>          }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40SGx4JmCzY5zCxlJtRmnQ.jpeg" /><figcaption>Thread issue is solved with “@MainActor”</figcaption></figure><p>Let’s code the same case with “@Observable” macro.</p><pre>@Observable<br>final class NewPostListViewModel {<br>    <br>    var posts: [Post] = []<br>    var network: NetworkServiceProtocol<br>    <br>    init(network: NetworkServiceProtocol) {<br>        self.network = network<br>    }<br>    <br>    func fetchPosts() async throws  {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        do {<br>            let data = try await network.request(url: url, responseType: [Post].self)<br>            self.posts = data<br>        } catch {<br>            print(error.localizedDescription)<br>        }<br>    }<br>}</pre><p>We marked our NewPostListViewModel class with “@Observable”. Fetched data with <strong>async</strong> func and then <strong>published value by</strong> <strong>default. (No need to use “@Published” property wrapper to publish values in “@Observable”)</strong></p><pre>import SwiftUI<br><br>struct PostListView: View {<br><br>    @State var newViewModel = NewPostListViewModel(network: NetworkService())<br>    <br>    var body: some View {<br>        List {<br>            ForEach(newViewModel.posts, id: \.id) { post in<br>                VStack(alignment: .leading) {<br>                    Text(post.title)<br>                        .font(.headline)<br>                    Text(post.body)<br>                        .font(.subheadline)<br>                }<br>            }<br>        }<br>        .task {<br>            try? await newViewModel.fetchPosts()<br>        }<br>    }<br>}</pre><p>In PostListView we declare view model as a “@State” and call fetchPosts func in <strong>.task</strong>.</p><p>When you run the app you’ll notice that <strong>data is fetched without any thread warnings</strong>. But does “@Observable” guarantee main thread execution?</p><p>Add following code to check if your function runs on main thread or not:</p><blockquote><em>Thread.isMainThread</em></blockquote><pre>func fetchPosts() async throws  {<br>        print(&quot;fetchPosts starts \(Thread.isMainThread)&quot;)<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        do {<br>            let data = try await network.request(url: url, responseType: [Post].self)<br>            self.posts = data<br>            print(&quot;posts data set \(Thread.isMainThread)&quot;)<br>        } catch {<br>            print(error.localizedDescription)<br>        }<br>    }</pre><p>Since the function is <strong>async </strong>both print statements will be false and that means <strong>code isn’t running on main thread</strong>.</p><blockquote>⚠️ Compiler does not show thread issue even if UI related data is updated, when “@Observable&quot; macro is used. ⚠️</blockquote><p>Why is the reason of that?</p><p>In my previous article I explained that ObservableObject is part of the <strong>Combine </strong>framework.<strong> So UI related properties marked with “@Published”, must be updated on main thread</strong>. If not, compiler warns you to switch to main thread.</p><p>When you remove <strong>“@Published”</strong> property wrapper from posts array, data will be set in fetchPosts func but <strong>IU will not update so there will be no thread warning.</strong></p><p>On the other hand “@Observable” macro is part of the <strong>Observation </strong>framework and <strong>all values are published by default</strong> <strong>but changes are only observed when used in UI.</strong></p><blockquote>📌 When using “@Observable&quot;, values published by default and system doesn’t know that whether they are used in UI or not. So you should manually ensure that UI related changes happen on main thread. ✔️</blockquote><p>You can use any of three solutions that i mentioned earlier to fix this thread issue. I’ll use “@MainActor” again because it’s easiest and most commonly used. When you run the app you’ll see that it works on main thread.</p><pre>@Observable<br>final class NewPostListViewModel {<br>    <br>    var posts: [Post] = []<br>    var network: NetworkServiceProtocol<br>    <br>    init(network: NetworkServiceProtocol) {<br>        self.network = network<br>    }<br>    <br>    @MainActor<br>    func fetchPosts() async throws  {<br>        print(&quot;fetchPosts starts \(Thread.isMainThread)&quot;)<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        do {<br>            let data = try await network.request(url: url, responseType: [Post].self)<br>            self.posts = data<br>            print(&quot;posts data set \(Thread.isMainThread)&quot;)<br>        } catch {<br>            print(error.localizedDescription)<br>        }<br>    }<br>}</pre><p>Now let’s fetch posts data in PostListViewModel using Combine.</p><h3><strong>Combine</strong></h3><p>First create a cancellables value and use it in <strong>fetchPostsWithCombine </strong>func as shown below.</p><blockquote><strong>Note: </strong>You can also create single cancellable value and it’ll work but in this example i prefer to use cancellable set.</blockquote><pre>var cancellable = AnyCancellable? // single cancellable <br>var cancellables = Set&lt;AnyCancellable&gt;() // cancellable set</pre><pre>func fetchPostsWithCombine() {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        network.request(url: url, responseType: [Post].self)<br>            .replaceError(with: [])<br>            .sink(receiveValue: { [weak self] posts in<br>                self?.posts = posts // posts array is set<br>            })<br>            .store(in: &amp;cancellables)<br>    }</pre><p>In fetchPostsWithCombine func, we used <strong>sink</strong> to get <strong>receiveValue</strong> from publisher that returned by <strong>request</strong> func and assigned that data to posts array. In case of an error we used <strong>replaceError</strong> to return an empty array. Then finally we saved <strong>AnyCancellable </strong>value to <strong>cancellables </strong>using <strong>store</strong> func.</p><p>When we call that func from an <strong>ObservableObject</strong>, it will throw a thread warning just like before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWhzxDqc4FJdt1ldjLiT4Q.png" /></figure><p>If you attempt to solve this issue using any of three methods I mentioned earlier, you’ll notice that <strong>they don’t work</strong>.</p><blockquote>⚠️ “@MainActor&quot; macro does not work with Combine functions ⚠️</blockquote><p>But why?</p><blockquote>📌 Combine framework uses its own threading system.<br>Even if you apply “@MainActor” to func or class it wont affect ✔️</blockquote><p>So if you want to switch to main thread you should use<strong> .receive</strong> func.</p><blockquote><strong><em>.receive(on: DispatchQueue.main)</em></strong></blockquote><pre>func fetchPostsWithCombine() {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        network.request(url: url, responseType: [Post].self)<br>            .receive(on: DispatchQueue.main)<br>            .replaceError(with: [])<br>            .sink(receiveValue: { [weak self] posts in<br>                self?.posts = posts<br>            })<br>            .store(in: &amp;cancellables)<br>    }</pre><p>When performing the same operation with <strong>“@Observable”</strong> macro, compiler will not warn you about thread issue for the reasons I explained earlier. To resolve this, you can once again use receive func.</p><pre>@Observable<br>final class NewPostListViewModel {<br>    <br>    var posts: [Post] = []<br>    var network: NetworkServiceProtocol<br>    <br>    var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init(network: NetworkServiceProtocol) {<br>        self.network = network<br>    }<br>    <br>    @MainActor<br>    func fetchPosts() async throws  {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        do {<br>            let data = try await network.request(url: url, responseType: [Post].self)<br>            self.posts = data<br>        } catch {<br>            print(error.localizedDescription)<br>        }<br>    }<br>    <br>    func fetchPostsCombine() {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        network.request(url: url, responseType: [Post].self)<br>            .receive(on: DispatchQueue.main)<br>            .replaceError(with: [])<br>            .sink(receiveValue: { [weak self] posts in<br>                self?.posts = posts<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><p>So here it is. We solved all issues. 🚀 Now you know what to do if you encounter a thread warning using ObservableObject, “@Observable” macro or Combine.</p><p>I hope I was able to explain it clearly. If you have any questions don’t hesitate to contact me. Thank you for reading and see you next time 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a509807d5230" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using “@Observable” macro instead of ObservableObject and passing multiple objects | SwiftUI #1]]></title>
            <link>https://medium.com/@glnygl94/using-observable-macro-instead-of-observableobject-and-passing-multiple-objects-swiftui-1-e6a6d5a1c181?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a6d5a1c181</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-macros]]></category>
            <category><![CDATA[observableobject]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 10:11:40 GMT</pubDate>
            <atom:updated>2024-11-30T15:39:51.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5yuWkx9_BWH4aHIVP-GVQ.jpeg" /></figure><p>“@Observable” macro is used in SwiftUI projects because it is easier compared to ObservableObject however you should be careful while using it at some points. Before diving into these points let me explain what are “@Observable” and ObservableObject and how they work.</p><h3>ObservableObject</h3><p>ObservableObject is a protocol in Combine Framework that simplifies data observing and data binding. Classes conform this protocol and use “<strong>@Published</strong>” property wrapper to publish their variables.</p><p>Here is an example of how ObservableObject protocol works in SwiftUI.</p><p>Lets assume that we have a class called Counter with an integer property currentCount and increaseCount func. Class must conform <strong>ObservableObject</strong> protocol and publish currentCount with “<strong>@Published</strong>” if we want to update text in UI whenever increaseCount func triggered. In CounterView we should define counter object with “<strong>@StateObject</strong>” to track state change.</p><pre>final class Counter: ObservableObject {<br>  <br>    @Published var currentCount: Int = 0<br>    <br>    func increaseCount() {<br>        currentCount += 1<br>    }<br>}<br><br>import SwiftUI<br><br>struct CounterView: View {<br>    <br>    @StateObject var counter = Counter() <br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(counter.currentCount)&quot;)<br>            Button {<br>                counter.increaseCount()<br>            } label: {<br>                Text(&quot;Increase count&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>“@Observable”</h3><p>“@Observable” macro part of Observation Framework and it’s doing the same thing as ObservableObject but requires less code.</p><blockquote>Minimum development target iOS 17.0+</blockquote><p>To use this macro in the same example you need to add “@Observable” to Counter class first.</p><pre>@Observable<br>final class Counter {<br>    <br>    var currentCount: Int = 0<br>    <br>    func increaseCount() {<br>        currentCount += 1<br>    }<br>}</pre><blockquote>Note: If compiler doesn’t recognize “@Observable”macro, import Observation framework.</blockquote><p>When using “@Observable” macro, no need to publish values because <strong>all values are published by default</strong>. If you don’t want to publish a value on purpose, all you need to do is adding <strong>“@ObservationIgnored” </strong>macro to that value.</p><pre>@Observable<br>final class Counter {<br>    <br>    var currentCount: Int = 0<br>    @ObservationIgnored var newCount: Int = 0<br>    <br>    func increaseCount() {<br>        currentCount += 1<br>        newCount += 1<br>    }<br>}</pre><p>In CounterView since counter object does’t conform ObservableObject protocol, you should declare with “<strong>@State</strong>” property wrapper instead of “@StateObject”</p><pre>struct CounterView: View {<br>    <br>    @State var counter = Counter() <br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(counter.newCount)&quot;)<br>            Button {<br>                counter.increaseCount()<br>            } label: {<br>                Text(&quot;Increase count&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>Pretty easy right? However you may still encounter problems when using ObservableObject or “@Observable” in certain situations.</p><h3>EnvironmentObject / Environment</h3><p>In SwiftUI, when you want to pass an object from a parent view to subviews you must use “<strong>@EnviromentObject</strong>” or “<strong>@Enviroment</strong>” property wrappers. If class conforms ObservableObject you can use<strong> .enviromentObject</strong> func or class has “@Observable” macro you can call <strong>.enviroment</strong> func.</p><p><strong>ObservableObject:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOY5aFjnxZDZ40TfAEL8aw.jpeg" /><figcaption>ObservableObject</figcaption></figure><p>In this example Counter class conforms ObservableObject so we declared counter as “<strong>@StateObjec</strong>t” then we called <strong>.enviromentObject</strong> func and passed counter object to CounterSecondView. In CounterSecondView we retrieved this value with “<strong>@EnviromentObject</strong>”.</p><p>Lets do the same thing with “@Observable” macro.</p><p><strong>“@Observable”:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5HQNnsDtR5SwEqoTvBwTw.jpeg" /><figcaption>“@Observable”</figcaption></figure><p>We defined counter object as “<strong>@State</strong>”. Then we called <strong>.enviroment</strong> func and passed counter object. In CounterSecondView we used “<strong>@Enviroment</strong>” wrapper and<strong> added class type as a value </strong>to “@Enviroment”.</p><pre>@Environment(Counter.self) var counter: Counter // Counter.self class type as value</pre><h3><strong>What if we want to pass multiple objects of the same class type?</strong></h3><p>Imagine we have two different Counter objects and they conform ObservableObject protocol. When we click increase button currentCount value for the first counter will increase but secondCounter will remain the same. Lets try to pass these objects to CounterSecondView with .enviromentObject func.</p><pre>struct CounterView: View {<br>    <br>    @StateObject var counter = Counter()<br>    @StateObject var secondCounter = Counter()<br>    <br>    var body: some View {<br>        NavigationView {<br>            VStack(spacing: 20) {<br>                Text(&quot;\(counter.currentCount)&quot;)<br><br>                Button {<br>                    counter.increaseCount()<br>                } label: {<br>                    Text(&quot;Increase count&quot;)<br>                }<br>                <br>                NavigationLink {<br>                    CounterSecondView()<br>                } label: {<br>                    Text(&quot;Go to second screen&quot;)<br>                }.buttonStyle(.automatic)<br>            }<br>        }<br>        .environmentObject(counter) // first counter object pass  <br>        .environmentObject(secondCounter) // second counter object pass<br>    }<br>}</pre><pre>struct CounterSecondView: View {<br>    <br>    @EnvironmentObject var counter: Counter<br>    @EnvironmentObject var secondCounter: Counter<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(counter.currentCount)&quot;)<br>            Text(&quot;\(secondCounter.currentCount)&quot;)<br>        }<br>    }<br>}</pre><p>Even though there are two different counter enviroment object in CounterSecondView, they will be equal to <strong>counter</strong> object because we passed this object first. <strong>If secondCounter were passed first, both values would be equal to secondCounter </strong>like below. 👇🏻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*hDCswiQ_uDrpdE9tO7EeFg.gif" /><figcaption>Passed counter first / Passed secondCounter first</figcaption></figure><p>The reason of this, “@EnviromentObject” lacks of a “key” to distinguish between these values. So to resolve this problem <strong>we should use “@Enviroment” with a specified key instead of “@EnviromentObject”</strong></p><p>How do we create keys?</p><h3>“@Entry”</h3><p>“@Entry” macro allows us to define specific keys for “@Enviroment”. We extend <strong>EnviromentValues</strong> struct and define desired keys and types with “@Entry” macro.</p><blockquote><strong>Each key must have a default value !</strong></blockquote><pre>extension EnvironmentValues {<br>    @Entry var firstCounter: Counter = Counter()<br>    @Entry var secondCounter: Counter = Counter()<br>}</pre><p>We defined two keys like firstCounter and secondCounter, specified their types and default values. Now, we can assign these keys to “@Enviroment” wrappers.</p><p><strong>To pass “@StateObject” with .enviroment function we need to select function with keyPath argument.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*IwUAaTslYOOZV0RpbL6e3g.png" /></figure><p><strong>ObservableObject:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fnK-ASaI0FoJnZISncERw.jpeg" /></figure><pre>        .environment(\.firstCounter, counter)<br>        .environment(\.secondCounter, secondCounter)</pre><p>So the first text in CounterSecondView will display number of button presses while second text remains at zero and objects will correctly pass to second view. Now let’s do the same example with “@Observable”</p><p><strong>“@Observable”:</strong></p><p>We can use <strong>class type as value</strong> in “@Enviroment” wrapper.</p><pre>@Environment(Counter.self) var counter: Counter // Counter.self class type as value</pre><p>However in this example since we try to pass multiple objects and using class type, objects will not match correctly. To avoid this issue we should use environment keys instead.</p><pre>    @Environment(\.firstCounter) var counter: Counter<br>    @Environment(\.secondCounter) var secondCounter: Counter</pre><p>As you can see below the <strong>first .enviroment func</strong> accepts “@Observable” object directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*HzOgFwPqzGlxdn8sC-hx0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*Karq2M0J3AhA2fMe8P01sw.png" /></figure><p>Would this function really work for our case? Let’s see.</p><pre>struct CounterView: View {<br>    <br>    @State var counter = Counter()<br>    @State var secondCounter = Counter()<br><br>    var body: some View {<br>        NavigationView {<br>            VStack(spacing: 20) {<br>                Text(&quot;\(counter.currentCount)&quot;)<br><br>                Button {<br>                    counter.increaseCount()<br>                } label: {<br>                    Text(&quot;Increase count&quot;)<br>                }<br>                <br>                NavigationLink {<br>                    CounterSecondView()<br>                } label: {<br>                    Text(&quot;Go to second screen&quot;)<br>                }.buttonStyle(.automatic)<br>            }<br>        }<br>        .environment(counter) // enviroment func without keyPath<br>        .environment(secondCounter) // enviroment func without keyPath<br>    }<br>}</pre><pre>struct CounterSecondView: View {<br>    <br>    @Environment(\.firstCounter) var counter: Counter<br>    @Environment(\.secondCounter) var secondCounter: Counter<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(counter.currentCount)&quot;)<br>            Text(&quot;\(secondCounter.currentCount)&quot;)<br>        }<br>    }<br>}</pre><pre>extension EnvironmentValues {<br>    @Entry var firstCounter: Counter  = Counter()<br>    @Entry var secondCounter: Counter = Counter()<br>}</pre><p>❌ Even though the code seems correct, it will not work as expected. ❌</p><p>In this case, .enviroment function will pass<strong> default value</strong> we created with “@Entry” macro to the second view, not modified value. To fix this <strong>we must use .enviroment function with a keyPath argument again.</strong></p><pre>        .environment(\.firstCounter, counter)<br>        .environment(\.secondCounter, secondCounter)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li3V5-gb6KcCJk8pqT2Ung.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*p0Uu0_SGfxhLB8CUcFM8OA.gif" /></figure><p>I hope this article clarified a little bit more ObservableObject and “@Observable”. If you have any questions feel free to reach out. In my next article I’ll discuss key points to consider when using the “@Observable” macro with asynchronous tasks. See you next time 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a6d5a1c181" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.bug trait| Swift Testing #7]]></title>
            <link>https://medium.com/@glnygl94/bug-trait-swift-testing-7-1dbc4b985cf7?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dbc4b985cf7</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xctest]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 11:22:59 GMT</pubDate>
            <atom:updated>2024-10-28T11:31:03.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>.bug trait | Swift Testing #7</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmwV2wiB1iv9YLRC9oRsmg.jpeg" /></figure><p>In Swift Testing, if we want to add a warning or bug information to test functions, we use <strong>.bug </strong>trait. As you may remember from my previous posts, we had a test function that only worked for version v1. So we can add info that it won’t work in newer versions using .bug trait.</p><pre>@Test(.enabled(if: currentVersion == .v1))<br>    func addTwoNegativeNumbers() {<br>        <br>        let num1 = -2<br>        let num2 = -5<br>        <br>        let sum = calculator.add(num1: num1, num2: num2)<br>        <br>        #expect(sum == -7)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2MELA2ysC8kG7CHEo6nyg.png" /></figure><p>The .bug trait requires a URL and can also take a title or id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LB_tYNr7xVlS5pNL1LEpag.png" /></figure><p>Since the current version is v3, test was skipped. To see bug details you must first select the correct test from local tests at the panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AZhrEnA00sXRN21xSQ9xw.png" /></figure><p>Then click right and select View Details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*lTbXNzjcjY-YxqkoXuUV8w.png" /></figure><p>In this screen, you can see bug title at top right hand corner, and by clicking you’ll be directed to the link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHP6OEJnQ5noy9SjDkpBwA.jpeg" /></figure><p>If you add an id to trait, you’ll see this id instead of title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex57-hTTAOPXWxPP3SFMMA.jpeg" /></figure><p>Thank you for reading and see you next time 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dbc4b985cf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.bug kullanımı| Swift Testing #7]]></title>
            <link>https://medium.com/@glnygl94/bug-kullan%C4%B1m%C4%B1-swift-testing-7-2cb3c6a28780?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb3c6a28780</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 11:22:18 GMT</pubDate>
            <atom:updated>2024-10-28T11:22:18.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmwV2wiB1iv9YLRC9oRsmg.jpeg" /></figure><p>Swift Testing’de test fonksiyonlarına warning ya da bug bilgisi eklemek istersek <strong>.bug </strong>traitini kullanırız.</p><p>Daha önceki yazılardan hatırlayacağınız gibi yalnızca v1 versiyonunda çalışan bir test fonksiyonumuz vardı. Bu fonksiyona, yeni versiyonlarda çalışmayacağı bilgisini .bug ile ekleyebiliriz.</p><pre>    @Test(.enabled(if: currentVersion == .v1))<br>    func addTwoNegativeNumbers() {<br>        <br>        let num1 = -2<br>        let num2 = -5<br>        <br>        let sum = calculator.add(num1: num1, num2: num2)<br>        <br>        #expect(sum == -7)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2MELA2ysC8kG7CHEo6nyg.png" /></figure><p>.bug traiti url zorunlu olmak üzere title ya da id değerlerini alabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LB_tYNr7xVlS5pNL1LEpag.png" /></figure><p>Test, current versiyon v3 olduğu için enable traiti ile skipped edildi. Bug detayını görüntülemek içinse öncelikle paneldeki local testler arasından doğru testi seçmelisiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AZhrEnA00sXRN21xSQ9xw.png" /></figure><p>Sonrasında bu teste sağ tıklayarak detayı görüntüleyin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*lTbXNzjcjY-YxqkoXuUV8w.png" /></figure><p>Bu ekranda sağ köşede bug titleını görebilir ve tıklayarak eklediğiniz bug issuesunun linkine yönlenebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHP6OEJnQ5noy9SjDkpBwA.jpeg" /></figure><p>Eğer traite id eklerseniz bu kısımda title yerine bugın idsini göreceksiniz.</p><pre>    @Test(<br>        .enabled(if: currentVersion == .v1),<br>        .bug(&quot;https://github.com/glnygl/SwiftTestingExample&quot;,<br>             id: 214,<br>             &quot;This func doesn&#39;t work anymore&quot;)<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex57-hTTAOPXWxPP3SFMMA.jpeg" /></figure><p>Okuduğunuz için teşekkürler bir sonraki yazıda görüşmek üzere 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb3c6a28780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#require macro | Swift Testing #6]]></title>
            <link>https://medium.com/@glnygl94/require-macro-swift-testing-6-47d386b001dc?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/47d386b001dc</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[swift-testing]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 09:09:21 GMT</pubDate>
            <atom:updated>2024-10-21T09:09:21.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbw9w8Sw2uzty_YMGHESJA.jpeg" /></figure><p>In my first post I explained how we can check the test result using <strong>#expect </strong>in Swift Testing. If you haven&#39;t read it yet the link is below.</p><p><a href="https://medium.com/@glnygl94/what-is-swift-testing-swift-testing-1-b95ff521ab8a">What is Swift Testing? | Swift Testing #1</a></p><p>Today I’ll show you how to use #require macro in Swift Testing.</p><p><strong>When/Where we should use #require macro?</strong></p><ul><li>Check optional values <strong><em>(if value is nil throw an error and terminate the test earlier than expected)</em></strong></li><li>If test depends on a condition <strong><em>(condition must be true, if is not then again terminate the test and throw an error)</em></strong></li></ul><p>Here is an example,</p><p>You already know from previous article, we have a function called areaOfZeroLength and the area function in Rectangle struct return nil when either length or width value is 0.</p><pre>@Test()<br>    func areaOfZeroLength() throws {<br>        <br>        let length = 0<br>        let width = 5<br>        let sum = rectangle.area(length: length, width: width)<br>        <br>        #expect(sum == nil)<br>        <br>        print(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; areaOfZeroLength &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;)<br>    }</pre><p>According to this condition test works successfully. However if we expect result not to be nil then it will throw an error as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyUjSQFA2W3wvvu2cYpTNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UjXPNiNk2GmXGoeYG1ifw.png" /><figcaption>print(“&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; areaOfZeroLength &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;”)</figcaption></figure><p>As you can see above, even though test failed print statement in the next line was executed and printed to the console. Now let&#39;s try the same example with #require macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJoHhJHaqvtdABNq3nWeew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUr5z-s482PC6BlDisziTw.png" /><figcaption>print(“&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; areaOfZeroLength &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;”)</figcaption></figure><p>Our test failed at line 34 and ended without printing. Condition is not true so test terminated and threw an error.</p><p>In conclusion, there may be situations where you can use #require instead of #expect and also scenarios where you might use both together.</p><p>Thank you for reading and see you next time 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47d386b001dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#require kullanımı | Swift Testing #6]]></title>
            <link>https://medium.com/@glnygl94/require-kullan%C4%B1m%C4%B1-swift-testing-6-5e99bab0378e?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e99bab0378e</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 09:07:11 GMT</pubDate>
            <atom:updated>2024-10-21T09:07:11.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbw9w8Sw2uzty_YMGHESJA.jpeg" /></figure><p>Swift Testing’de test sonucunu #expect ile nasıl kontrol edebileceğimizi ilk yazımda anlatmıştım. Hala okumadıysanız aşağıdaki linkten ulaşabilirsiniz.</p><p><a href="https://medium.com/@glnygl94/swift-testing-nedir-swift-testing-1-ec850d9db1f2">Swift Testing Nedir? | Swift Testing #1</a></p><p><strong>#require</strong> macrosu ise <strong>optional değerleri kontrol etmekte</strong> ve <strong>bu değerlerin nil gelmesi halinde hata fırlatarak testi olması gerekenden daha önce bitirmekte</strong> kullanılır. Ayrıca <strong>bir koşulun mutlaka sağlanmasını</strong>, <strong>bu koşul sağlandığında devam etmesini, sağlanmadığı takdirde teste son verilmesini istiyorsak</strong> yine #require macrosu kullanırız.</p><p>Daha önce areaOfZeroLength isimli fonksiyon için aşağıdaki testi yazmıştık. Rectangle structı içindeki area fonksiyonu length ya da width değerlerinden biri 0 olduğunda nil dönüyordu.</p><pre>    @Test()<br>    func areaOfZeroLength() throws {<br>        <br>        let length = 0<br>        let width = 5<br>        let sum = rectangle.area(length: length, width: width)<br>        <br>        #expect(sum == nil)<br>        <br>        print(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; areaOfZeroLength &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;)<br>    }</pre><p>Bu koşula göre yukarıdaki test başarılı bir şekilde çalışır ancak beklenen sonucun nil olmamasını istediğimizde aşağıdaki gibi hata verecektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyUjSQFA2W3wvvu2cYpTNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UjXPNiNk2GmXGoeYG1ifw.png" /><figcaption>print(“&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; areaOfZeroLength &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;”)</figcaption></figure><p>Yukarıda gördüğünüz gibi test hata vermesine rağmen bir sonraki satır olan print kodunu çalıştırılıp konsola yazdırıldı. Şimdi aynı örneği #require macrosuyla deneyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJoHhJHaqvtdABNq3nWeew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUr5z-s482PC6BlDisziTw.png" /></figure><p>Testimiz olması gerektiği gibi 34. satırda hata verdi ve print satırını yazdırmadan sona erdi.</p><p>Sonuç olarak #expect yerine yukarıdaki gibi #require kullanabileceğiniz durumlar olabileceği gibi her ikisini birlikte kullandığınız senaryolar da olabilir.</p><p>Okuduğunuz için teşekkürler bir sonraki yazıda görüşmek üzere 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e99bab0378e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.timeLimit trait | Swift Testing #5]]></title>
            <link>https://medium.com/@glnygl94/timelimit-trait-swift-testing-5-39da6a3aec52?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/39da6a3aec52</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 10:15:53 GMT</pubDate>
            <atom:updated>2024-10-14T10:15:53.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTZnFQuEczIys7GSp0eZwA.jpeg" /></figure><p>Sometimes tests may take longer than expected and it may lead to performance issues as well as require refactoring. In Swift Testing we can limit the runtime of tests using by<strong> timeLimit.</strong></p><p>Here we have a function called multiply that returns result after 100 seconds.</p><pre>    func multiply(num1: Int, num2: Int) async -&gt; Int {<br>        try? await Task.sleep(nanoseconds: 100_000_000_000)<br>        return num1 * num2<br>    }</pre><p>Let’s write a test for this function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FYajeNrBrcbrtx-GZ5COA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*O07pw9BBB__-RShnE6xUEw.png" /></figure><p>As you can see above test ran successfully but it took around 100 seconds. So if we want to limit runtime of this test we should add timeLimit trait.</p><blockquote>@Test(.timeLimit(.minutes(1)))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7S7tjzXAxVL5N7VzH-JymQ.png" /></figure><p>We got an error because of our test’s runtime is longer than 1 minute.</p><p>So adding this traits to your functions you can easily understand which functions are running slowly and which one requires refactoring.</p><p>Thank you for reading and see you next time 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39da6a3aec52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.timeLimit kullanımı | Swift Testing #5]]></title>
            <link>https://medium.com/@glnygl94/timelimit-kullan%C4%B1m%C4%B1-swift-testing-5-7f3e0cfb6e1e?source=rss-e9d1f580f5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f3e0cfb6e1e</guid>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[xctest]]></category>
            <dc:creator><![CDATA[Gülenay Gül]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 10:14:32 GMT</pubDate>
            <atom:updated>2024-10-14T10:14:32.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTZnFQuEczIys7GSp0eZwA.jpeg" /></figure><p>Testlerin beklenenden uzun sürede çalışması performans sorunlarına yol açabileceği gibi aynı zamanda kodların refactorünü gerektirebilir. Swift Testing’de testlerimizin çalışma süresini <strong>timeLimit </strong>ile<strong> </strong>kısıtlayabiliriz.</p><p>Örneğin doğru sonucu 100 saniye sonra ileten multiply isimli bir fonksiyonumuz olsun.</p><pre>    func multiply(num1: Int, num2: Int) async -&gt; Int {<br>        try? await Task.sleep(nanoseconds: 100_000_000_000)<br>        return num1 * num2<br>    }</pre><p>Bu fonksiyon için bir test yazalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FYajeNrBrcbrtx-GZ5COA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*O07pw9BBB__-RShnE6xUEw.png" /></figure><p>Yukarıda gördüğünüz gibi test başarılı bir şekilde çalıştı ancak çalışması yaklaşık 100 saniye sürdü.</p><p>Bu testin süresini 1 dakika ile kısıtlamak istersek teste timeLimit eklemeliyiz.</p><blockquote>@Test(.timeLimit(.minutes(1)))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7S7tjzXAxVL5N7VzH-JymQ.png" /></figure><p>Test beklenen süreden daha uzun sürdüğü için hata aldı.</p><p>Bu yöntemle hangi fonksiyonun yavaş çalıştığını bulabilir refactör gerektiren kodları gözden geçirebilirsiniz.</p><p>Okuduğunuz için teşekkürler bir sonraki yazıda görüşmek üzere 🌸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f3e0cfb6e1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>