<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>mobidevtalk</title>
	<atom:link href="https://mobidevtalk.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://mobidevtalk.com/</link>
	<description>deep dive, Learning through case study</description>
	<lastBuildDate>Tue, 24 Jun 2025 03:10:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2018/11/cropped-favicon-52.jpg?fit=32%2C32&#038;ssl=1</url>
	<title>mobidevtalk</title>
	<link>https://mobidevtalk.com/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">160120831</site>	<item>
		<title>Swift Test Doubles Spy Stub Dummy Fake Mock</title>
		<link>https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/</link>
					<comments>https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/#respond</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Thu, 23 Nov 2023 00:47:18 +0000</pubDate>
				<category><![CDATA[Pragmatic]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=2064</guid>

					<description><![CDATA[<p>Unit testing is most effective when the unit tests are deterministic. And by deterministic means, the...</p>
<p><a href="https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Test Doubles Spy Stub Dummy Fake Mock</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/">Swift Test Doubles Spy Stub Dummy Fake Mock</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Unit testing is most effective when the unit tests are deterministic. And by deterministic means, the output is always the same for a specific input. No surprise, no randomness whatsoever. Not only in Swift but in all languages, test doubles like spy, stub, dummy, fake, and mock play crucial roles in making those tests deterministic. Without understanding the fundamental differences among them will create confusion in a team. In this blog post, we will be elaborating each test doubles with examples.</p>



<p>Usually, any component we want to unit test has one or more dependencies. To test an expected behavior, we need to fake some input somehow. Assume we need to store a user preference in some persistence store. For now, assume it will be User Defaults. We will use abstraction so the high-level business logic and low-level details do not depend on each other. Instead, they both depend on abstraction. Here, the logic to store the user preference is high-level logic. And the actual storing of User details is the low-level details. </p>



<h2 class="wp-block-heading">The basics of dependency Inversion</h2>



<p>We just mentioned both the higher-level logic and the low-level details should depend on abstraction. We have some details in our <a href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/">Introduction of Dependency Inversion on Swift</a> talk. Also, in our <a href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/">Swift Dependency Inversion through Protocol</a> talk, we share how to achieve Dependency Inversion in Swift. Finally, in the <a href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/">Dependency Injection in Swift</a> talk, we demonstrated the details of dependency Injection. Feel free to visit those for a crystal idea of dependency inversion and injection. </p>



<h2 class="wp-block-heading">Persistence store case study</h2>



<p>We will use the persistence store storage as our case study for this blog post. Our goal is to store some user preferences in some persistence stores like User Defaults. Now, we will do TDD here. And by doing that, we will clarify the Test Doubles in Swift. </p>



<p>We will have three different user preferences. We will be storing those values in User Defaults.</p>



<pre><code class="language-swift">
public enum Preference {
    case notNow
    case never
    case save(Credential)
}
</code></pre>



<p><code>Credential</code> is a simple <code>struct</code> with <code>username</code> and <code>password</code>.</p>



<pre><code class="language-swift">
public struct Credential {
    public let username: String
    public let password: String
}
</code></pre>



<p>Let us start TDD for this case study and explore the Swift test Doubles like Spy, Stub, Dummy, Fake, and Mock.</p>



<h2 class="wp-block-heading">Implementation through abstraction</h2>



<p>Here is the abstraction, protocol, to separate the high-level business login from the low-level details. </p>



<pre><code class="language-swift">
protocol PreferenceStorable{
    func save(_ data: Data, for key: String) -> Error?
}
</code></pre>



<p>We will have a controller who will be making the business decisions. We can call it <code>StorageController</code>. <code>StorageController</code> will have one instance of type <code>PreferenceStorable</code>. Through this instance, the controller will save the preference. The User Defaults will confirm  <code>PreferenceStorable</code> and implement the low-level details (<code>save</code> requirement).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" width="491" height="82" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Basic.png?resize=491%2C82&#038;ssl=1" alt="" class="wp-image-2164 img-fluid" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Basic.png?w=491&amp;ssl=1 491w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Basic.png?resize=300%2C50&amp;ssl=1 300w" sizes="(max-width: 491px) 100vw, 491px" /><figcaption class="wp-element-caption">Dependency Diagram</figcaption></figure></div>


<h2 class="wp-block-heading">Swift Test Doubles Code Implementation</h2>



<p>On the <a href="https://github.com/mobidevtalk/TestDoubles/tree/main/UnitTestFundamental">TestDoubles GitHub repo</a>, we have <a href="https://github.com/mobidevtalk/TestDoubles/pulls?q=is%3Apr+is%3Aclosed+sort%3Acreated-asc">closed Pull requests</a> demonstrating the usage of each test double. We can go through the pull request and select the <code>next</code> or <code>previous</code> button to see the evaluation of the code in TDD.</p>



<h2 class="wp-block-heading">Spy</h2>



<p>The very first thing we want to test is the <a href="https://github.com/mobidevtalk/TestDoubles/pull/1/commits/7120954098ea542d8e6b0634dc284c182f93cbd4">initialization of the <code>StorageController</code> does not initiate the saving</a>. Then, we will confirm the <a href="https://github.com/mobidevtalk/TestDoubles/pull/1/commits/259e15a6bc6469a8ce9cd78b3046aaae02b108b9">save of <code>StorageController</code> actually storing the preference</a>. These two scenarios tell us we need to verify the saved value. That sounds like a Spy.</p>



<p>The concept of Spy is straightforward. <strong>Spy will only store values, nothing else</strong>. We will use this stored value of the Spy to validate the assumption through assertion. Here is an implementation of Spy. Note that return is a method-only requirement. The nil return does not have any relation with the Spy, <code>SpyPreferenceStorage</code>.</p>



<pre><code class="language-swift">
class SpyPreferenceStorage: PreferenceStorable {
    private(set) var preferences = [String: Data]()

    func save(_ data: Data, for key: String) -> Error? {
        preferences[key] = data
        return nil
    }
}
</code></pre>



<p>So, the required tests will be as follows.</p>



<pre><code class="language-swift">
class TestDoublesTests: XCTestCase {
    func test_init_doesnotStorePreference() {
        let (_, spy) = makeSUT()

        XCTAssertTrue(spy.preferences.isEmpty)
    }

    func test_savePreference_storesPref() {
        let (sut, spy) = makeSUT()
        XCTAssertTrue(spy.preferences.isEmpty)

        sut.save(preference: .never)

        XCTAssertFalse(spy.preferences.isEmpty)
    }

    // MARK: - Helper
    private func makeSUT() -> (sut: StorageController, spy: SpyPreferenceStorage) {
        let spy = SpyPreferenceStorage()
        let sut = StorageController(presistenceStore: spy)
        return (sut, spy)
    }
}
</code></pre>



<p>The resulting code for the SpyPreferenceStorage will be the following. </p>



<pre><code class="language-swift">

struct StorageController {
    let presistenceStore: PreferenceStorable

    func save(preference: Preference){
        let encoder = JSONEncoder()
        guard let data = try? encoder.encode(preference) else { return }
        _ = presistenceStore.save(data, for: Self.PreferenceStoreKey)
    }
}

extension StorageController{
    static var PreferenceStoreKey: String {"PreferenceStoreKey"}
}
</code></pre>



<h2 class="wp-block-heading">Stub</h2>



<p>Now, once can confirm the value is stored now let us turn our attention to error handling. The <code>StorageController</code> should be able to handle errors properly. If there is no error then the <code>StorageController</code> should not propagate any error. And if an error occurs the <code>StorageController</code> should propagate that exact error to the caller. So it seems like we need to mimic the erroneous state of the system to validate the error-handling behavior of the <code>StorageController</code>. This is the job for <code>Stub</code>.</p>



<p><strong>Stub returns a predefined response</strong>. When we need one component to return some specific value we use a stub. Here is an example of Stub.</p>



<pre><code class="language-swift">
struct StubPreferenceStorage: PreferenceStorable {
    let error: Error?

    func save(_ data: Data, for key: String) -> Error? { error }
}
</code></pre>



<p>On our <code>StubPreferenceStorage</code> stub we will set the error on init time. If we want some specific error then we will set that error on the init time. Otherwise, we can set the error to nil on init time to reflect a no error state of the system. Let us have a look at the <code>test_save_throwsError_onErroneousStoring</code> test which simulates an erroneous state. On the other hand, the <code>test_save_throwsNoError_onSuccessfulStoring</code> simulates no error state.</p>



<pre><code class="language-swift">
final class ResponseAfterStoringTests: XCTestCase {
    func test_save_throwsError_onErroneousStoring() {
        let expectedError = NSError(domain: "any error", code: -100)
        let (sut, _) = makeSUT(expectedError)

        do {
            try sut.save(preference: .never)
            XCTFail("Expected error but got none")
        } catch {
            XCTAssertEqual(error as NSError, expectedError)
        }
    }

    func test_save_throwsNoError_onSuccessfulStoring() {
        let noError: Error? = nil
        let (sut, _) = makeSUT(with: noError)

        do {
            try sut.save(preference: .never)
        } catch {
            XCTFail("Expected no error but got an \(error)")
        }
    }

    // MARK: - Helper
    private func makeSUT(_ error: Error?) -> (sut: StorageController, stub: StubPreferenceStorage){
        let stub = StubPreferenceStorage(error: error)
        let sut = StorageController(presistenceStore: stub)
        return (sut, stub)
    }
}
</code></pre>



<p>Here we are setting the <code>StubPreferenceStorage</code> with an <code>NSError</code>. This error will be returned on the <code>save(_ data: Data, for key: String)</code> call. Now let us update our production code  <code>StorageController</code> to return any error if occurs.</p>



<pre><code class="language-swift">
public struct StorageController {
    private let presistenceStore: PreferenceStorable
    
    public init(presistenceStore: PreferenceStorable) {
        self.presistenceStore = presistenceStore
    }

    public func save(preference: Preference) throws{
        let encoder = JSONEncoder()
        guard let data = try? encoder.encode(preference) else { return }

        if let error = presistenceStore.save(data, for: Self.PreferenceStoreKey) {
            throw error
        }
    }
}

extension StorageController{
    public static var PreferenceStoreKey: String {"PreferenceStoreKey"}
}
</code></pre>



<p>As you can see once we have an error in <code>presistenceStore.save</code> we are throwing that error. So using stub we can define the <code>presistenceStore</code> erroneous state which helps us to confirm the production code error handling behavior.</p>



<h2 class="wp-block-heading">Dummy</h2>



<p>Till now we were only concerned with the <code>presistenceStore: PreferenceStorable</code>. But there is still another hidden dependency on the <code>StorageController</code>. The <code>JSONEncoder</code> that we are initiating on <code>save</code> method. If some error occurs during the encoding time we have no way to return that error to the caller. So let us move our focus on that part of the code. </p>



<p>If we want to stub any error during the encoding process we need to inject this dependency, <code>JSONEncoder</code>. So let us take an encoder on the <code>init</code> method. As a result, the StorageController will look like the following.</p>



<pre><code class="language-swift">
public struct StorageController {
    private let presistenceStore: PreferenceStorable
    private let encoder: JSONEncoder

    public init(presistenceStore: PreferenceStorable, encoder: JSONEncoder) {
        self.presistenceStore = presistenceStore
        self.encoder = encoder
    }

    public func save(preference: Preference) throws{
        let data: Data
        do{
            data = try encoder.encode(preference)
        }catch{
            throw error
        }

        if let error = presistenceStore.save(data, for: Self.PreferenceStoreKey) {
            throw error
        }
    }
}
</code></pre>



<p>Now returning the error state during the encoding process of the <code>JSONEncoder</code> is a stub job. But what role the <code>presistenceStore</code> now will take? The response of <code>save</code> now does not matter. This sounds like a Dummy.</p>



<p>The Dummy is a filler. <strong>Dummy always returns a response, that does not have any impact on that specific test scenario</strong>. So here is a dummy look at the <code>PreferenceStorable</code>.</p>



<pre><code class="language-swift">
class DummyPreferenceStorage: PreferenceStorable {
    func save(_ data: Data, for key: String) -> Error? { nil }
}
</code></pre>



<p>On the <code>save</code> method of the <code>DummyPreferenceStorage</code>, we are not concerned about the return param. We just need a <code>PreferenceStorable</code> to initiate the <code>StorageController</code> like following.</p>



<pre><code class="language-swift">
let sut = StorageController(presistenceStore: DummyPreferenceStorage(), 
                                    encoder: StubFailableJsonEncoder(error: anyEncodingError))
</code></pre>



<p>The implementation of Dummy is visible on the corresponding <a href="https://github.com/mobidevtalk/TestDoubles/pull/3/commits/15c7012bd32dbf8b838750d98f80895d92e7c039#diff-e8eea0b0a7c9c430a15d8dcab79561d3615d1ec1c23d7409c6fe8eba8193e7c3R27">pull request</a>.</p>



<h2 class="wp-block-heading">Fake</h2>



<p>Among all test doubles, the Fake is different from its kind. Fake has its brain. So, <strong>a Fake will return results based on the business logic in it</strong>. </p>



<p>One usage can be the dictionary-based implementation of the <code>PreferenceStorable</code> rather than the actual <code>UserDefaults</code>. So <code>UserDefaults</code> has two methods to set and retrieve the data. <code>func set(_ value: Any?, forKey defaultName: String)</code> and <code>func value(forKey key: String) -&gt; Any?</code>. Let us invert the dependency. Rather than depending on UserDefaults let us make our system depend on abstraction, <code>protocol</code>.</p>



<pre><code class="language-swift">
protocol UserDefaultsStorage {
    func set(_ value: Any?, forKey defaultName: String)
    func value(forKey key: String) -> Any?
}
</code></pre>



<p>The <code>UserDefaultsStorage</code> encapsulate the methods that are required for setting and retrieving the value. So the <code>UserDefaults</code> confirmation will be like the following.</p>



<pre><code class="language-swift">
extension UserDefaults: UserDefaultsStorage{}
</code></pre>



<p>And now, this should be enough to get going. But if we program against the abstraction, then we will use the <code>UserDefaultsStorage</code> instead of <code>UserDefaults</code>. That way, we can use another test double which can store the value in a dictionary rather than directly saving it to <code>UserDefaults</code>.</p>



<pre><code class="language-swift">
class FakeStorage: UserDefaultsStorage{
    var dictionary = [String: Any]()
    
    func set(_ value: Any?, forKey defaultName: String) {
        dictionary[defaultName] = value
    }
    
    func value(forKey key: String) -> Any? {
        dictionary[key]
    }
}
</code></pre>



<p>In the above code set and value methods use a dictionary to store and return the value. This is pure business logic to store the value in a non-persistence store rather than a persistence store, ie UserDefaults. So this is a Fake test double as it is using its business logic to store and deliver the stored result from within a Dictionary.</p>



<h2 class="wp-block-heading">Mock</h2>



<p>Mock always looks like Spy. But there is a distinct difference between Spy and Mock. On Spy, we just capture the values. The assertion happens in the corresponding test. On the other hand, in a mock, we do the verification in the mock itself.</p>



<p><strong>In the mock, we expose verifications so that the test can assert the expected behavior</strong>. Following is an example of Mock.</p>



<pre><code class="language-swift">
class MockPUTAPI: PUTAPI{
    private var isCalled = false
    private var completion: ((Result<HTTPURLResponse, Error>)-> Void)?
    
    func put(preference: Preference, completion: @escaping (Result<HTTPURLResponse, Error>)-> Void) {
        isCalled = true
        self.completion = completion
    }
    
    var verifyCall: Bool{
        isCalled == true
    }
    
    var verifyCompletionSetup: Bool{
        completion != nil
    }
}
</code></pre>



<p>The <code>verifyCall</code> and <code>verifyCompletionSetup</code> does not explicitly expose the underlying value, but rather just confirms if they are set to an expected value. So now the corresponding tests will just assert these verifications.</p>



<pre><code class="language-swift">
func test_init_doesNotInitiateRemoteCall() {
        let (_, mockAPI) = makeSUT()
        
        XCTAssertFalse(mockAPI.verifyCall)
        XCTAssertFalse(mockAPI.verifyCompletionSetup)
    }
    
func test_put_initiateRemoteCall() {
        let (sut, mockAPI) = makeSUT()
        
        sut.executePUTRequest(for: URL(string: "any-url")!, with: .never){_ in}
        
        XCTAssertTrue(mockAPI.verifyCall)
        XCTAssertTrue(mockAPI.verifyCompletionSetup)
    }
</code></pre>



<p>All the not-shown entities can be found on <a href="https://github.com/mobidevtalk/TestDoubles/blob/main/UnitTestFundamentalTests/Interactor/IteractorContentTests.swift">GitHub</a>.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Swift Test Doubles such as Spy, Stub, Fake, and Mock gives us the ability to make our test deterministic. But knowing them is not just enough. We also need to know what difference they pose compared to one another. Also when to use which one? All these questions can not be answered in a single blog post. So we will be resuming our test doubles talks in the next talk. Till then take care. </p>
<p>The post <a href="https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/">Swift Test Doubles Spy Stub Dummy Fake Mock</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-test-doubles-spy-stub-dummy-fake-mock/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2064</post-id>	</item>
		<item>
		<title>Certificates Identifiers Devices Profiles in iOS app distribution</title>
		<link>https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/</link>
					<comments>https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/#respond</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Tue, 10 Oct 2023 00:27:53 +0000</pubDate>
				<category><![CDATA[Process]]></category>
		<category><![CDATA[App ID]]></category>
		<category><![CDATA[App Store]]></category>
		<category><![CDATA[Certificates]]></category>
		<category><![CDATA[Identifiers]]></category>
		<category><![CDATA[Provisioning Profile]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=2066</guid>

					<description><![CDATA[<p>If you are or want to be an iOS app developer, you know words like Certificates,...</p>
<p><a href="https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Certificates Identifiers Devices Profiles in iOS app distribution</span></a></p>
<p>The post <a href="https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/">Certificates Identifiers Devices Profiles in iOS app distribution</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="">If you are or want to be an iOS app developer, you know words like Certificates, Identifiers, Devices, and Profiles. We go through those terms once we publish our apps to the world or an external group. They are not rocket science, but sometimes they become very daunting. Nowadays, Certificates, Identifiers, Devices, and Profiles are automatically handled by Xcode. But knowing them upfront gives us an understanding of how things are happening behind the scenes. Moreover, if we are distributing the iOS app other than the Apple platform(like the TestFlight), then it is always the manual way. In this blog post, we will address those terms(Certificates, Identifiers, Devices, and Profiles) to draw a relationship among them.</p>



<p class="">To move further, we also need to go through the different types of Distribution schemas like Development distribution, App Store distribution, and Ad Hoc distribution. After that, we will map those distributions with the regular distribution concepts like Alpha and Beta distribution.</p>



<h2 class="wp-block-heading">Purchase of the subscription</h2>



<p class="">This is the phase when we want to distribute our developed app to the customer. The iOS app distribution is not free. To distribute an iOS app, it is necessary to purchase an Apple developer program subscription, which costs $99 yearly. On the <a href="https://developer.apple.com/support/enrollment/">Apple developer program,</a> we can find more details. There will be some email confirmation after the subscription purchase.</p>



<h2 class="wp-block-heading">Mapping App Store, App Store Connect, and Developer portal</h2>



<p class="">Usually, we distribute our app through the App Store. But to get that app to the App Store, we need to have an entry of that app on the App Store Connect. And to get to the App Store Connect, we need to create some entitlement on the Apple developer portal. That means we will create app identifiers, certificates, device lists, and provisioning profiles on the Apple developer portal. Once we have the provisioning profile, we can upload the app binary to the App Store Connect. After that, we need to submit our app for review. And once it gets reviewed, we can distribute the app to the users.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" decoding="async" width="640" height="51" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Overview.png?resize=640%2C51&#038;ssl=1" alt="" class="wp-image-2068 img-fluid" style="width:836px;height:67px" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Overview.png?w=761&amp;ssl=1 761w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Overview.png?resize=300%2C24&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Overview.png?resize=750%2C61&amp;ssl=1 750w" sizes="(max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">App idea to App Store process overview</figcaption></figure></div>


<p class="">Let us now move to a more granular level.</p>



<h2 class="wp-block-heading" id="alpha-beta-distribution-mapping">How Alpha and Beta distribution are mapped in iOS app distribution</h2>



<p class="">First, let us talk a bit more about different types of iOS app distribution. We can say there are mainly two types of distribution based on build variance. One is Development distribution, and the other is Production distribution. </p>



<p class="">In the case of Development distribution, we need to run our undergoing development app on some devices that we can/will not plug into our Mac. An example can be the verification of a hotfix. The hotfix can not be merged into the production code without the tester&#8217;s approval. In this situation, Development distribution helps a lot.</p>



<p class="">Another one is Production distribution. Production distribution can be of three types. They are App Store Distribution, Ad Hoc Distribution, and Enterprise Distribution. App Store Distribution is the standard distribution of our iOS app to the general people through the App Store. We distribute the iOS app to a limited number of customers on Ad Hoc distribution. Finally, on the Enterprise Distribution, we distribute the iOS app to the employees of an organization.</p>



<p class="">We often use the terms Alpha and Beta versions of an iOS app. Let us see how they map with the above distribution types.</p>



<p class="">In general, Alpha testing is done by the development team. It is very common to ad testers or QA guys in the Alpha testing. Alpha testing is regarded as the very first level of testing of an iOS app. As a result, the Development distribution of an iOS app is the Alpha distribution for that iOS app. We might use the dev environment APIs here on the Alpha/Development distribution.</p>



<p class="">On the other hand, Beta testing is done by some specific groups, not conducted by the Development team. Multiple small groups are invited to the Beta iOS app testing. The diverse groups give the development team a wide range of perspectives. One important thing is that the Beta iOS app is very close to the actual release. As a result, production APIs are used here. Thus, the Beta distribution is the Ad Hoc distribution of an iOS app.</p>



<p class="">Let us have an overview of different types of distribution in a single image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="640" height="750" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Distribution.png?resize=640%2C750&#038;ssl=1" alt="" class="wp-image-2096 img-fluid" style="width:846px;height:991px" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Distribution.png?w=692&amp;ssl=1 692w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Distribution.png?resize=256%2C300&amp;ssl=1 256w" sizes="(max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">Alpha Beta distribution mapped according to the Apple distribution</figcaption></figure></div>


<h2 class="wp-block-heading">Code to Apple developer portal</h2>



<p class="">In this flow, most of our app distribution process will be addressed. Here are the concepts for this flow.</p>



<ul class="wp-block-list">
<li class="">Identifiers</li>



<li class="">Devices</li>



<li class="">Certificates</li>



<li class="">Profiles</li>
</ul>



<h2 class="wp-block-heading" id="Identifiers-App-ID">Identifiers,  App ID</h2>



<p class="">There are various types of IDs available on the Apple dev portal. But we will only concentrate on App IDs. This App ID will uniquely identify the app. App ID is required to avail of different Apple services. Another important thing is that the Provisioning Profile, which we will discuss shortly, will use this App ID to identify the app.</p>



<p class="">The standard format of App ID uses a reverse domain name notion. An example can be <code>com.mobidevtalk.blog</code> where <code>blog</code> the app name <code>mobidevtalk</code> is the company/organization name <code>com</code> is the domain type of that organization.</p>



<p class="">The certificates, provisioning profiles, and the app&#8217;s bundle identifier all use App ID. So please think before picking a name for our app. 🤔</p>



<p class="">There is sometimes a tendency to use a wildcard app ID. This has a name format like <code>com.mobidevtalk.*</code>. The only use case of this wildcard app ID is to support multiple apps sharing the same bundle seed ID. However, using the wildcard app ID has huge limitations. Wildcard ID can not used in the Apple Push Notification, Purchase, etc. We can use the wildcard for temporal cases. But for permanent cases, we need to use the proper app ID.</p>



<h2 class="wp-block-heading" id="Device">Device(s)</h2>



<p class="">Apple only allows registered devices to run the beta version of an app. If we want to run our debug app, directly build and run the app from our Mac, we need to register the device. For ad hoc distribution, registration is also required. We can not run our app on devices without registering them in the Apple dev portal. Thats it!</p>



<p class="">The Xcode will automatically register the device for development if we allow the automatic signing of our app in the Xcode and then connect a device with our Mac. But we will need to register devices over the air. Moreover, we will not always use automatic signing.</p>



<p class="">How can we register devices, iPhones, iPads, Macs, etc.? There are three ways such as automatic, half-manual, and full-manual.</p>



<p class="">The automatic way works only on the Apple platform. That means using TestFlight from Apple for the OTA(Over-the-air) distribution. Here is the workflow.</p>



<ul class="wp-block-list">
<li class="">Push the app builds to the App Store Connect</li>



<li class="">Invite the people, either adding them as internal or external tester on the App Store Connect</li>



<li class="">The invitee needs to open the invitation link, sent to his email, on the iPhone/iPad/Mac</li>



<li class="">A new App will be downloaded called TestFlight from the App Store</li>



<li class="">From Now on the invitee can download the app directly through TestFlight, even the old versions</li>
</ul>



<p class="">Interestingly, TestFlight way to the distribution does not decrease the total number of devices in the Apple Dev Portal. We will continue this talk in future talks regarding the Xcode Cloud part of our CI/CD blog post.</p>



<p class="">Now, let us talk about the half-manual way of adding the devices. This is true for most Beta App Testing Platforms like Firebase, TestFairy, HockeyApp, and App Center. All of them except Firebase will provide a Device Management feature to collect the UUIDs of the testers. On the other hand, Firebase will provide a dynamic link to the tester. All of those platforms ultimately let the tester download their app from where the UUID of the tester&#8217;s device will be collected and sent to the corresponding Beta App Testing platform. After that, the developer will collect those UUIDs from there. Then, the developer will add those UUIDs to the Apple Developer portal.</p>



<p class="">On Manual device registration, we need to ask the tester to send the UUID of his iPhone/iPad. And then add it to the Device section of the <a href="https://developer.apple.com/account/resources/devices/list">Apple developer portal</a> by the developer. </p>



<p class="">Remember, you can add a limited number of devices.</p>



<p class="">Keep in mind that people in your organization will come and leave. If you are registering an organization-owned device, please ensure the appropriate name for it. Perhaps add a suffix before the device name. So, anyone can understand those names and remove that device entry if required. Once an employee leaves the organization, you must remove his iDevice entry from the Device and Profile section of the Apple developer portal. Thus, he will lose access to the builds using the latest provisioning profile.</p>



<h2 class="wp-block-heading" id="Certificates">Certificates</h2>



<p class="">Certificates are the most important and most confusing part of iOS app distribution. These Certificates digitally sign the iOS apps. </p>



<p class="">Now, why digitally sign our iOS app? Because Apple wants to make sure every time an app is run on an iPhone/iPad/Mac, that app is digitally signed by a known authority. So, how does Apple know that authority? The developer creates a CSR(Certificate Signing Request) file on his Mac. He uses his keychain. He will provide the email with other information. Then, the developer uploads the CSR file to the Apple Developer. He has to have access to the Apple Developer portal. That&#8217;s how Apple knows the authority.</p>



<p class="">The following diagram shows the general process of Certificate creation.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" width="502" height="281" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Certificate.png?resize=502%2C281&#038;ssl=1" alt="" class="wp-image-2083 img-fluid" style="width:571px;height:320px" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Certificate.png?w=502&amp;ssl=1 502w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/Certificate.png?resize=300%2C168&amp;ssl=1 300w" sizes="auto, (max-width: 502px) 100vw, 502px" /><figcaption class="wp-element-caption">Certificate creation process</figcaption></figure></div>


<h3 class="wp-block-heading">Types of Certificates</h3>



<p class="">Based on the <a href="#alpha-beta-distribution-mapping">distribution type</a> we will have two different types of certificates. One is a Development Certificates, and another is a Distribution Certificates. Development certificates are used to run the iOS app on the developer&#8217;s iPhone/iPad/Mac. On the other hand, Distribution certificates are used to run the app on the customer&#8217;s iPhone/iPad/Mac. The customer can be internal or external.</p>



<p class="">Both types of certificates are created the <a href="#certificates">same way</a>.</p>



<h3 class="wp-block-heading">Development Certificates</h3>



<p class="">Ideally, one developer should create his Development certificate. How can he share his Development certificate on his other Mac? He needs to export that Development certificate from the existing Mac and then import it into the other Mac. What if we use this process to share a Development certificate among teammates? Then, this is a very wrong process. Again, ideally, each developer should create his development certificate. On a team, they should have access to the Company/Organization&#8217;s Apple Developer Program as individual developers.</p>



<h3 class="wp-block-heading">Distribution Certificates</h3>



<p class="">Distribution certificates are used to distribute the iOS app to the customers. Ideally, all the production-type distributions, such as Ad Hoc and App Store distributions, use identical distribution certificates. Unlike the Development Certificate, one team member manages the Distribution Certificate. Yes, he is a bottleneck. But that&#8217;s how Apple designs the Distribution Certificates. Fastlane, an automation tool, has an elegant way of resolving this issue. We will see this in detail in some future blog posts.</p>



<p class="">Here is an insight into different types of certificates.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="204" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CertificateTeypes.png?resize=640%2C204&#038;ssl=1" alt="" class="wp-image-2109 img-fluid" style="width:731px;height:233px" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CertificateTeypes.png?w=661&amp;ssl=1 661w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CertificateTeypes.png?resize=300%2C96&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">Types of Certificates</figcaption></figure></div>


<h2 class="wp-block-heading" id="Provisioning-Profile">Provisioning Profile</h2>



<p class="">The Provisioning Profile is a container. I like to think of the Provisioning Profile as a container or a bag. So in this bag, Provisioning Profile, two things/concepts are at least kept. What are those two things? Well, Certificates, list of authorized devices (iPhone/iPad) list. Both the Development and Ad Hoc Provisioning Profiles contain these two. But on an App Store provisioning profile, there is no device list. Most of the time, the Provisioning Profile also carries an app identifier. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="246" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/ProvisioningProfile.png?resize=640%2C246&#038;ssl=1" alt="Certificates Identifiers Devices are put together in Profiles." class="wp-image-2119 img-fluid" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/ProvisioningProfile.png?w=740&amp;ssl=1 740w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/ProvisioningProfile.png?resize=300%2C115&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">Provisioning Profile</figcaption></figure></div>


<h2 class="wp-block-heading" id="Combining-all-together">Combining all together</h2>



<p class="">Let us combine all the basic concepts(Certificates, Identifiers, Devices, and Profiles) in a single place. The takeaway here is the Developer provisioning profile will contain a Developer Certificate. Similarly, an Ad Hoc provisioning profile will hold its Ad Hoc certificate. Finally, the App Store profile will carry its App Store certificate. Only the App Store provisioning profile will not contain any device list, as this one is used to upload the build for the App Store.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="497" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CombiningAllConcepts.png?resize=640%2C497&#038;ssl=1" alt="Certificates Identifiers Devices Profiles in one picture." class="wp-image-2123 img-fluid" style="width:876px;height:681px" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CombiningAllConcepts.png?w=812&amp;ssl=1 812w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CombiningAllConcepts.png?resize=300%2C233&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2023/10/CombiningAllConcepts.png?resize=768%2C597&amp;ssl=1 768w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">Certificates Identifiers Devices Profiles in one picture</figcaption></figure></div>


<h2 class="wp-block-heading">Conclusion</h2>



<p class="">Knowing the basic concepts like Certificates, Identifiers, Devices, and Profiles will give us the confidence to use those properly. Not understanding how these concepts are glued together creates confusion and frustration. A simple go-through will reduce the frustration always. So please revisit this blog before these basic concepts get dusted. See you in the next blog. ✌️ ✋</p>
<p>The post <a href="https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/">Certificates Identifiers Devices Profiles in iOS app distribution</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/certificates-identifiers-devices-profiles-in-ios-app-distribution/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2066</post-id>	</item>
		<item>
		<title>associatedtype on Protocol, making Protocol  Generic</title>
		<link>https://mobidevtalk.com/associatedtype-on-protocol/</link>
					<comments>https://mobidevtalk.com/associatedtype-on-protocol/#respond</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Tue, 27 Jul 2021 10:30:22 +0000</pubDate>
				<category><![CDATA[Q/A]]></category>
		<category><![CDATA[associatedType]]></category>
		<category><![CDATA[generic]]></category>
		<category><![CDATA[protocol]]></category>
		<guid isPermaLink="false">http://mobidevtalk.com/?p=1859</guid>

					<description><![CDATA[<p>When we talk about generic code we have to come to an associatedtype for protocol. The...</p>
<p><a href="https://mobidevtalk.com/associatedtype-on-protocol/" class="more-link btn btn-primary">more...<span class="screen-reader-text">associatedtype on Protocol, making Protocol  Generic</span></a></p>
<p>The post <a href="https://mobidevtalk.com/associatedtype-on-protocol/">associatedtype on Protocol, making Protocol  Generic</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>When we talk about generic code we have to come to an associatedtype for protocol. The protocol is the contract between two entities. And to make that contract more generic Swift provides the associatedtype for generic type on the protocol. To develop the proper Protocol Oriented Programming, POP, skill the associatedtype plays an important role. In this blog post, we will have a base understanding of the associatedtype on Protocol which will lead us to some more advanced level talk on the future blog post of this associated type series.</p>



<p>We have some talks over Protocol on our <a href="https://mobidevtalk.com/swift-protocol-hub/">Swift Protocol Hub</a> page. Where we evaluate the protocol usage on Swift. And on the last blog post, we talk about <a href="https://mobidevtalk.com/swift-generic-protocol/" target="_blank" rel="noreferrer noopener">Swift Generic &amp; Protocol</a> where we talk about both Protocol and Generic. For any kind of confusion and deeper knowledge, we should visit those blog posts.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#associatedtype">What is associatedtype</a></li><li><a href="#typealias">Why &amp; how confirming a protocol with&nbsp;<code>associatedType</code>&nbsp;turns into&nbsp;<code>typealias</code>?</a></li><li><a href="#associatedtype-generic-type">Why associatedtype rather than generic type</a></li><li><a href="#when-to-choose-generic-associated-type">When to choose the generic and when to choose the associated type on Protocol</a></li></ul>



<h2 class="wp-block-heading" id="associatedtype">associatedtype</h2>



<p><code>associatedtype</code> is an associated type on a Protocol. Associated means connected to. So when a type needs to be connected with a Generic protocol we use the associatedtype. Basically <code>associatedtype</code> is a placeholder type for a protocol. This placeholder type will be replaced by the concrete type at the time of implementing the protocol. Let us go through an example.</p>



<pre><code class="language-swift">
protocol Energy{
    associatedtype EnergyBar
    
    func consume(unit: EnergyBar)
    func loss()
}
</code></pre>



<p>On the above the <code>EnergyBar</code> is the <code>associatedtype</code>. This <code>EnergyBar</code> is used on the <code>consume</code> method as a parameter. As we want to make our <code>Energy</code> protocol as a generic one we have to make the type generic. That&#8217;s why we are using the <code>associatedtype</code> on this protocol. Now let us have an example of replacing that associatedtype or EnergyBar with a concrete type.</p>



<p>To have the concrete implementation of <code>associatedtype</code> we will take two entirely different characters. Popeye and Superman. We already know it is the Spinach that boosts Popeye with energy. So Spinach is the EnergyBar for Popeye. On the other hand, Superman doesn&#8217;t get that much of a bug out on the case of losing energy, but when he does he has to make sure there is a radiation source like Sun around him. So the <code>SunRay</code> is the <code>EnergyBar</code> for SuperMan.</p>



<p>Let us start the implementation. So the EnergyConsumption will have two ways; eating and radiation.</p>



<pre><code class="language-swift">
enum EnergyConsumption{
    case eat
    case radiation
}
</code></pre>



<p>Let define Spinach.</p>



<pre><code class="language-swift">
struct Spinach{
    let consumptionType = EnergyConsumption.eat
    
    let iron = 2.71
    let magnesium = 79
    let calcium = 99
}

extension Spinach: CustomStringConvertible{
    var description: String{
        return "\(iron) mg, \(magnesium) mg, \(calcium) mg"
    }
}
</code></pre>



<p>And we have a description of Spinach by confirming the <code>CustomStringConvertible</code>.</p>



<p>Now let us define SunRay. SunRay will have a different wavelength of light/radiation.</p>



<pre><code class="language-swift">
struct Wavelengths{
    let name: String
    let start: Float
    let end: Float
}

extension Wavelengths: CustomStringConvertible{
    var description: String{
        return "\(name): \(start)-\(end)"
    }
}

struct SunRay{
    let consumptionType = EnergyConsumption.radiation
    
    let visibleWavelengths = Wavelengths(name: "visibleLight", start: 0.4, end: 0.8)
    let ultravioletWavelengths = Wavelengths(name: "ultravioletLight", start: 0.2, end: 0.3)
    let infraredWavelengths = Wavelengths(name: "infraredRadiation", start: 0.9, end: 1.0)
}

extension SunRay: CustomStringConvertible{
    var description: String{
        return "wavelengths[micrometre]\n\(visibleWavelengths.description)\n\(ultravioletWavelengths.description)\n\(infraredWavelengths.description)"
    }
}
</code></pre>



<p>Again we are conforming the <code>CustomStringConvertible</code> to have a description.</p>



<h2 class="wp-block-heading" id="typealias">Why &amp; how confirming a protocol with&nbsp;<code>associatedType</code>&nbsp;turns into&nbsp;<code>typealias</code>?</h2>



<p>Now it is time to conforming our <code>Energy</code> protocol on the <code>Popeye</code> and <code>SuperMan</code> struct.</p>



<pre><code class="language-swift">
struct Popeye: Energy{
    typealias EnergyBar = Spinach

    func consume(unit: Spinach) {
        "Energy is increased by \(unit.description)"
    }
    
    func loss() {
        "Energy lost"
    }
}
</code></pre>



<p>But why is typealias EnergyBar = Spinach rather than associatedtype EnergyBar = Spinach? What is the play between typealias  &amp; associatedtype? Let us talk about this in short. </p>



<p>So at the time of defining the generic protocol Energy, we have to inform the compiler about the type of unit parameter on the func consume(unit) method. Otherwise, the compiler will give us a compile-time error. Now we can not fix the type of that parameter to a concrete type yet. As we do not know what will be the type of that parameter unless the protocol is confirmed. So we say that <code>EnergyBar</code> is an associate type for the protocol <code>Energy</code>.</p>



<p>But things get a different perspective when we want to confirm the protocol. Now we need to say to the compiler that this time we are using the <code>Spinach</code> in place for <code>Energy</code>. So the <code>Spinach</code> will be the Energy. In other words, we are renaming the <code>Energy</code> to <code>Spinach</code>. And that action of renaming the type is done by <code>typealias</code> on Swift. </p>



<p><code>Protocol</code> is the boundary/fence of a garden in the real world where the gardener will operate. The protocol sets the boundary of the operating area. And the associatedtype is the tools he will use at the time of gardening. One day the gardener can have a shovel. Another day he can have a fork. Whatever he uses, the shovel or the fork, it is another name of the tools.</p>



<p>Back to our original example. Swift is a modern language. It can infer the type. We can exclude the typealias keyword once we have enough context for the type. Now the following example we are excluding the <code>typealias EnergyBar = SunRay</code>.</p>



<pre><code class="language-swift">
struct SuperMan: Energy{
    func consume(unit: SunRay) {
        unit.description
    }
    
    func loss() {
        "SuperMan in now a human"
    }
}
</code></pre>



<h2 class="wp-block-heading" id="associatedtype-generic-type">Why associatedtype rather than generic type</h2>



<p>This is an interesting question. Why we will use the associatedtype when we can use the generic type for a method even on a Protocol. Or more importantly when to use generic and when to use associatedtype on the protocol. To begin the discussion let us have an example of a couple of generic type-based methods on a protocol.</p>



<pre><code class="language-swift">
protocol EnergyOperator{
    func boostEnergy< T >(unit: T)
    func decreaseEnergy< T >(unit: T)
}
</code></pre>



<p>Here we are defining the <code>EnergyOperator</code> protocol, which has two generic methods under it. The <code>boostEnergy</code> and the <code>decreaseEnergy</code> both take generic type, <code>T</code>, as their param. The protocol confirming entity needs to define the solid types for those generic params. Let <code>Popeye</code> confirms the <code>EnergyOperator</code>.</p>



<pre><code class="language-swift">
extension Popeye: EnergyOperator{
    func boostEnergy<SpinachUnit>(unit: SpinachUnit) {
        "Energy is now boosted by 1 Can full of Spinach it has \(unit) on per-unit"
    }
    
    func decreaseEnergy<EnergyLoosingUnit>(unit: EnergyLoosingUnit) {
        "Popeye's energy is decreased by \(unit)"
    }
}

popeye.boostEnergy(unit: Spinach())
popeye.decreaseEnergy(unit: "Fighting")

popeye.boostEnergy(unit: Spinach())
</code></pre>



<p>Now here is the interesting part. For the <code>boostEnergy</code> and the <code>decreaseEnergy</code> methods they required two different data types. <code>boostEnergy</code> is using the <code>Spinach</code> datatype and decreaseEnergy is using the <code>String</code> datatype. But if we would have used <code>associatedtype</code> then they both should be having the same data type.</p>



<h2 class="wp-block-heading" id="when-to-choose-generic-associated-type">When to choose the generic type and when to choose the associated type on Protocol</h2>



<p>Here is the most important question of this blog post. When we will choose the generic type and when to choose the associated type once we decide our protocol should be generic. Well, the very basic rule applies here. According to the need obviously. What the requirements need. We just need to notice the following to make the right decision for a generic protocol.</p>



<ul class="wp-block-list"><li>We need to use <code><strong>associatedtype</strong></code> when all the methods under a generic protocol need to use the <strong>same datatype</strong>.</li><li>The <strong>generic</strong> will be used when the methods under a protocol are required <strong>different data type</strong> for them individually.</li></ul>



<p>Simple, right? Hmm. Now let us move to another discussion. What if we need to use the <code>where</code> clause on Protocol and even when we need to use those types of clauses? Also, what does the <code>Self</code> with capital <code>S</code> means when it comes to Protocol. Well, they need another blog post. This one is already a big one. So see you in the next blog post.</p>



<h2 class="wp-block-heading">End talk</h2>



<p>The definition of associate stands for a connection. Which draws the same meaning here in Swift also. We saw the association of a value with the <a aria-label="case of enum (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-enum-basic-introduction/#associated-Values" target="_blank">case on enum</a> which is called associated-values. And here on this blog post, we see the association of type with a protocol called associatedtype. Understanding the core meaning helps a lot to clarify the concept behind it. Hope we all got the message. See you in the next blog post. Till then take care.</p>



<h2 class="wp-block-heading">Reference</h2>



<ul class="wp-block-list"><li><a href="https://github.com/mobidevtalk/Generic/blob/master/Generic.playground/Pages/associatedtype.xcplaygroundpage/Contents.swift" target="_blank" rel="noreferrer noopener">Code for this blog post @GitHub</a></li><li><a href="https://mobidevtalk.com/swift-protocol-hub/">Swift Protocol Hub</a></li><li><a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-generic-protocol/" target="_blank">Swift Generic &amp; Protocol</a></li><li><a aria-label="Documentation of Swift (opens in a new tab)" rel="noreferrer noopener" href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html" target="_blank">Documentation of Swift</a></li><li><a aria-label="Generics in Swift (opens in a new tab)" rel="noreferrer noopener" href="https://github.com/apple/swift/blob/master/docs/Generics.rst" target="_blank">Generics in Swift</a></li><li><a aria-label="Swift Generic Manifesto (opens in a new tab)" rel="noreferrer noopener" href="https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md" target="_blank">Swift Generic Manifesto</a></li><li><a aria-label="Generic in Swift (opens in a new tab)" rel="noreferrer noopener" href="https://github.com/apple/swift/blob/master/docs/Generics.rst" target="_blank">Generic in Swift</a></li><li><a aria-label="GENERIC PROTOCOLS &amp; THEIR SHORTCOMINGS (opens in a new tab)" href="https://krakendev.io/blog/generic-protocols-and-their-shortcomings" target="_blank" rel="noreferrer noopener">GENERIC PROTOCOLS &amp; THEIR SHORTCOMINGS</a></li><li><a aria-label="Swift Associated Type Design Patterns (opens in a new tab)" href="https://medium.com/@bobgodwinx/swift-associated-type-design-patterns-6c56c5b0a73a" target="_blank" rel="noreferrer noopener">Swift Associated Type Design Patterns</a></li></ul>



<p> </p>
<p>The post <a href="https://mobidevtalk.com/associatedtype-on-protocol/">associatedtype on Protocol, making Protocol  Generic</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/associatedtype-on-protocol/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1859</post-id>	</item>
		<item>
		<title>Swift Generic &#038; Protocol</title>
		<link>https://mobidevtalk.com/swift-generic-protocol/</link>
					<comments>https://mobidevtalk.com/swift-generic-protocol/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Wed, 30 Oct 2019 01:46:44 +0000</pubDate>
				<category><![CDATA[Pragmatic]]></category>
		<category><![CDATA[associatedType]]></category>
		<category><![CDATA[generic]]></category>
		<category><![CDATA[protocol]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">http://mobidevtalk.com/?p=1813</guid>

					<description><![CDATA[<p>In the Swift world, Generic is a very powerful tool the same way protocol is. In...</p>
<p><a href="https://mobidevtalk.com/swift-generic-protocol/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Generic &#038; Protocol</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-generic-protocol/">Swift Generic &#038; Protocol</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In the Swift world, Generic is a very powerful tool the same way protocol is. In fact, the protocol is the core concept of Swift. The power of swift comes from its extensibility which is facilitated by protocol. When we are able to use these core concepts, protocol, with Generic our code becomes very agile. And we all know the benefit of Agile code when it comes to real software development. The target of this blog post is to initiate the talk about implementing a Swift generic solution through the protocol.</p>



<p>Here on this blog post, Swift Generic &amp; Protocol, we will start with Generic Stack &amp; Generic Queue. Then we will advance to a generic protocol-based solution for those Stack &amp; Queue.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#Generic-Stack">Generic Stack</a></li><li><a href="#Generic-Queue">Generic Queue</a></li><li><a href="#Protocol-with-Generic">Protocol with Generic</a></li><li><a href="#Out-of-bound-crash">Out of bound crash</a></li><li><a href="#Generic-Stack-with-Generic-protocol">Generic Stack with Generic protocol</a></li><li><a href="#Generic-Queue-with-Generic-protocol">Generic Queue with Generic protocol</a></li><li><a href="#Summary">Summary</a></li></ul>



<p>The protocol is amazing stuff on Swift world. Here we can always have a visit to our protocol hub page where all the talks related to the protocol are listed. And on our <a aria-label="last talk (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-generic-introduction/" target="_blank">last talk</a>, we have some very basic about generic. Now it is time to mix them up.</p>



<p>Stack and Queue are two of the most common linear data structures. For this blog post, we will use the Stack and Queue to have some data operations. And obviously, we will use the Generic approach for a better solution. For <a aria-label="more info (opens in a new tab)" rel="noreferrer noopener" href="https://www.geeksforgeeks.org/difference-between-stack-and-queue-data-structures/" target="_blank">more info</a> on Stack and Queue.</p>



<p>We can move directly to the <a href="#Out-of-bound-crash">Out of bound crash</a> section if we already have the basic idea about Stack and Queue.</p>



<h2 class="wp-block-heading" id="Generic-Stack">Generic Stack</h2>



<p>Let us have a generic Stack, generic in a scene that we will be able to use this stack for different types.</p>



<p>A quick note about the stack. Data operation on Stack is done through <code>LIFO</code>. Insertion is called <code>push</code> and deletion is called <code>pop</code>.</p>



<pre><code class="language-swift">
struct DS_Stack< Element >{
    private var items = [Element]()
    
    mutating func push(item: Element){
        items.append(item)
    }
    
    mutating func pop() -> Element{
        return items.removeLast()
    }
}
</code></pre>



<p>Here we use the <code>Element</code> keyword rather than the more common <code>T</code> for a generic type. Because Element has a better match for our current use case. <a aria-label=" (opens in a new tab)" href="https://mobidevtalk.com/swift-generic-introduction/#Summarizing-the-generic-evolution-for-the-problem" target="_blank" rel="noreferrer noopener">Here</a> is the basic talk over the generic syntax, if we need it. </p>



<p>Let us have <code>Int</code> and <code>String</code> Stack example.</p>



<pre><code class="language-swift">
var intStack = DS_Stack<Int>()
intStack.push(item: 200)
intStack.push(item: 2)

intStack.pop()

var stringStack = DS_Stack<String>()
stringStack.push(item: "mobidevtalk")
stringStack.push(item: ".com")

stringStack.pop()
</code></pre>



<p>We will see <code>2</code> and <code>.com</code> was popped from the <code>intStack</code> and <code>stringStack</code> receptively. </p>



<h2 class="wp-block-heading" id="Generic-Queue">Generic Queue</h2>



<p>Now it is time for a generic Queue. Queue follows the <code>FIFO</code> approach for data operation. Insertion is called <code>enqueue</code> and deletion is called <code>dequeue</code>.</p>



<pre><code class="language-swift">
struct DS_Queue< Element >{
    private var items = [Element]()
    
    mutating func enqueue(item: Element){
        items.append(item)
    }
    
    mutating func dequeue() -> Element{
        return items.removeFirst()
    }
}
</code></pre>



<p>Example with <code>Int</code> and <code>String</code> as follows:</p>



<pre><code class="language-swift">
var intQueue = DS_Queue<Int>()
intQueue.enqueue(item: 200)
intQueue.enqueue(item: 2)

intQueue.dequeue()

var stringQueue = DS_Queue<String>()
stringQueue.enqueue(item: "mobidevtalk")
stringQueue.enqueue(item: ".com")

stringQueue.dequeue()
</code></pre>



<p>So this time we will see <code>200</code> and <code>mobidevtalk</code> being removed as Queue follows the <code>FIFO</code> approach.</p>



<p>On the <code>Stack</code> and <code>Queue</code> we are actually mutating the struct because of the requirements of the current time. <a aria-label="More on mutating the value type (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/mutating-enum-struct-on-swift/" target="_blank">More on mutating the value type</a>.</p>



<h2 class="wp-block-heading" id="Out-of-bound-crash">Out of bound crash</h2>



<p>What if for both Stack and Queue we want to remove more elements than they have. So trying to removing the third element of a two-element Stack or Queue will generate a crash. Why? Because there is no element on that index. Let us fix that. We want to tell our users that they are trying to remove data from an empty data structure. Let us define the Error.</p>



<pre><code class="language-swift">
enum OperatingError: Error{
    case outOfBound
    case empty
}
</code></pre>



<p>If we are wondering why to use an enum for Error definition we can always visit the <a aria-label="Error handling (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#enum-as-Error-why?" target="_blank">Error handling</a> blog for some more details.</p>



<p>We will also have a description for the <code>OperatingError</code>. By confirming <code>CustomStringConvertible</code> we can have that.</p>



<pre><code class="language-swift">
extension OperatingError: CustomStringConvertible{
    var description: String{
        switch self {
        case .outOfBound:
            return "Oops! There is nothing to remove"
        case .empty:
            return "Empty Stack"
        }
    }
}
</code></pre>



<p>The <code>CustomStringConvertible</code> the protocol provides a customization point for describing. <a aria-label="More on CustomStringConvertible (opens in a new tab)" href="https://developer.apple.com/documentation/swift/customstringconvertible" target="_blank" rel="noreferrer noopener">More on CustomStringConvertible</a>.</p>



<h2 class="wp-block-heading" id="Protocol-with-Generic">Protocol with Generic</h2>



<p>We have a basic understanding of Stack and Queue from the above sections. Now we should move to a more advanced data operating procedure. So the target is to generalize the data operation. And for that, we gonna use Protocol. But How?</p>



<p>By defining a <code>DataOperator</code> the protocol we will centralize the operations like inserting, deleting. Moreover, we will also add some status checks. Like the total count of elements. Also, we can add some description of the specific data structure.</p>



<pre><code class="language-swift">
protocol DataOperator: CustomStringConvertible{
    associatedtype Component
    
    mutating func insert(item: Component)
    mutating func remove() throws -&gt; Component
    func numberOfComponent() throws -&gt; Int
}
</code></pre>



<p>The <code>CustomStringConvertible</code> has a property called <code>description</code>. We want our <code>DataOperator</code> confirming types to provide a description of their Data structure.</p>



<p>Now let us talk about the <code>associatedtype</code> keyword. On Internet the <code>associatedtype</code> is a confusing word to understand when it comes to protocol and generic. We already talked about the <a href="https://mobidevtalk.com/associatedtype-on-protocol/" target="_blank" rel="noreferrer noopener">associatedtype in Protocol</a>, reach out to that post for more details. But for now, we will have the very basics of <code>associatedtype</code>. </p>



<p><code>associatedtype</code> is a placeholder for type. What type? Any type. It cloud be <code>Int</code> <code>String</code> or some custom type. The practice of using the associatedtype is to define a placeholder type which will be replaced later on by some Concrete type on build time. </p>



<p>To make any <code>protocol</code> generic we need to make the operating type on that <code>protocol</code> generic. And that&#8217;s where <code>associatedtype</code> plays its role.</p>



<p>The <code>insert</code> and <code>remove</code> will mutate the underneath struct so the <code>mutating</code> keyword is used.</p>



<h2 class="wp-block-heading" id="Generic-Stack-with-Generic-protocol">Generic Stack with Generic protocol</h2>



<p>When we use the <code>associatedtype</code> with a protocol, that protocol becomes a more generic one. So Now let us use our generic protocol, <code>DataOperator</code>, in action. We gonna define Stack which will be generic itself and will also be able to use the generic protocol.</p>



<pre><code class="language-swift">
struct Stack< Element >: DataOperator{
    var description: String{
        "Stack is a linear Data structure. Follows the LIFO(Last In First Out) patterns. Only one tracker called Top."
    }
    
    private var items = [Element]()
    
    private mutating func push(item: Element){
        items.append(item)
    }
    
    private mutating func pop() -> Element{
        return items.removeLast()
    }
    
    typealias Component = Element
    
    mutating func insert(item: Element) {
        push(item: item)
    }
    
    mutating func remove() throws -> Element {
        if items.count == 0 {
            throw OperatingError.outOfBound
        }else{
            return pop()
        }
    }
    
    func numberOfComponent() throws -> Int {
        let count = items.count
        if count == 0 {
            throw OperatingError.empty
        }else{
            return count
        }
    }
}
</code></pre>



<p>We make the underneath data and its operation, <code>items</code> <code>push</code> <code>pop</code>, <code>private</code>. So those can not be accessed by others outside of the struct. At the same time, we are using the signature methods of <code>DataOperator</code> to make the data operation and status update.</p>



<p>On the <code>typealias Component = Element</code> we are defining the associated type as <code>Element</code>. So after this statement all the <code>Component</code> on the <code>DataOperator</code> in <code>Stack</code> will be replaced by <code>Element</code>. More interestingly when we will use the <code>Int</code> or <code>String</code> or any custom type of <code>Stack</code> the <code>Element</code> will be replaced by that concrete type.</p>



<p>Now we are throwing Error when the count is equal to zero both on <code>remove</code> and <code>numberOfComponent</code>. If we need some help on Error handling and its mechanism like the <code>do</code> <code>try</code> <code>catch</code> don&#8217;t tense. We have that cover on the <a aria-label="Error Handling through try variance (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/" target="_blank">Error Handling through try variance</a> blog post. </p>



<p>Here comes the <code>stack</code> instance. This time we will use the <code>Int</code> based Stack. So the <code>Element</code> on the <code>Stack</code> and eventually the <code>Component</code> on the <code>DataOperator</code> will be replaced with the concrete type <code>Int</code>.</p>



<pre><code class="language-swift">
var stack = Stack< Int >()
stack.description
</code></pre>



<p>So we will have the stack description. Now it is time for the <code>empty</code> error state.</p>



<pre><code class="language-swift">
do {
    try stack.numberOfComponent()
} catch OperatingError.empty {
    OperatingError.empty.description
}
</code></pre>



<p><code>Empty Stack</code> will be printed as we yet not inserted any of the elements. So let insert some.</p>



<pre><code class="language-swift">
stack.insert(item: 10)
stack.insert(item: 30)
</code></pre>



<p>Now, what about some removal. What if we want to remove more elements than the <code>stack</code> have.</p>



<pre><code class="language-swift">
for _ in 1..<4 {
    do {
        try stack.remove()
    } catch OperatingError.outOfBound {
        OperatingError.outOfBound.description
    }
}
</code></pre>



<p>Aha, we don't have the crash. We have the <code>Oops! There is nothing to remove</code> message been printed out. Savvy 🤓. Again if we need help on <a aria-label="do try catch (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/" target="_blank">do try-catch</a>.</p>



<h2 class="wp-block-heading" id="Generic-Queue-with-Generic-protocol">Generic Queue with Generic protocol</h2>



<p>So now it's time for some generic queue with the generic protocol. This will be nearly a copy on the stack other than the operation will be based on queue style.</p>



<pre><code class="language-swift">
struct Queue< Element >: DataOperator{
    var description: String{
        "Queue is a linear Data structure. Follows the FIFO(First In First Out) patterns. Uses two tracker. Font for insertion. Rear for deletion"
    }
    
    private var items = [Element]()
    
    private mutating func enqueue(item: Element){
        items.append(item)
    }
    
    private mutating func dequeue() -> Element{
        return items.removeFirst()
    }
    
    typealias Component = Element
    
    mutating func insert(item: Element) {
        enqueue(item: item)
    }
    
    mutating func remove() throws -> Element {
        if items.count == 0 {
            throw OperatingError.outOfBound
        }else{
            return dequeue()
        }
    }
    
    func numberOfComponent() throws -> Int {
        let count = items.count
        if count == 0 {
            throw OperatingError.empty
        }else{
            return count
        }
    }
}
</code></pre>



<p>Let us have a <code>String</code> queue and have the same operation as the stack.</p>



<pre><code class="language-swift">
var queue = Queue< String >()
queue.description

do {
    try queue.numberOfComponent()
} catch OperatingError.empty {
    OperatingError.empty.description
}

queue.insert(item: "mobidevtalk")
queue.insert(item: ".com")

for _ in 1..<4 {
    do {
        try queue.remove()
    } catch OperatingError.outOfBound {
        OperatingError.outOfBound.description
    }
}
</code></pre>



<h2 class="wp-block-heading" id="Summary">Summary</h2>



<p>Let us have a look at how the associatedtype got replaced by the more concrete type like Int. The following image is for Stack. The same will be for <code>Queue</code>.</p>



<figure class="wp-block-image"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="474" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/10/TypeTransformation.jpg?resize=640%2C474" alt="Generic Protocol associatedtype" class="wp-image-1851 img-fluid" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/10/TypeTransformation.jpg?w=977&amp;ssl=1 977w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/10/TypeTransformation.jpg?resize=300%2C222&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/10/TypeTransformation.jpg?resize=768%2C568&amp;ssl=1 768w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption>Generic with protocol type transforming</figcaption></figure>



<p>The above picture tells the story of Swift's generic solution through the protocol. All the source code used on this blog post is available on <a aria-label="GitHub (opens in a new tab)" href="https://github.com/mobidevtalk/Generic/blob/master/Generic.playground/Pages/Protocol.xcplaygroundpage/Contents.swift" target="_blank" rel="noreferrer noopener">GitHub</a>.</p>



<h2 class="wp-block-heading">End Talk</h2>



<p>Here on this blog post, Swift Generic &amp; Protocol talk, We make the <code>protocol</code> generic when we use <code>associatedtype</code>. By defining the <code>associatedtype</code> on a protocol we remove the dependency from any specific/fixed type from that <code>protocol</code>. The <code>protocol</code> becomes more generic to embrace any type.</p>



<p>But we can't say we cover all the Generic &amp; Protocol combination-related talk. This one was the tip of the iceberg. A long way to go. So stay tuned. Take care.</p>



<h2 class="wp-block-heading">Reference</h2>



<ul class="wp-block-list"><li><a href="https://github.com/mobidevtalk/Generic/blob/master/Generic.playground/Pages/Protocol.xcplaygroundpage/Contents.swift" target="_blank" rel="noreferrer noopener" aria-label="Source code (opens in a new tab)">Source code</a></li><li><a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-protocol-hub/" target="_blank">Protocol Hub Page</a></li><li><a href="https://mobidevtalk.com/swift-generic-introduction/">Swift Generic introduction</a></li><li><a aria-label="Adopting Common Protocols (opens in a new tab)" href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/">Error Handling through try variance</a></li><li><a rel="noreferrer noopener" aria-label="Adopting Common Protocols (opens in a new tab)" href="https://developer.apple.com/documentation/swift/adopting_common_protocols" target="_blank">Adopting Common Protocols</a></li><li><a rel="noreferrer noopener" aria-label="Protocol-oriented programming &amp; generics (opens in a new tab)" href="https://www.tensorflow.org/swift/tutorials/protocol_oriented_generics" target="_blank">Protocol-oriented programming &amp; generics</a></li><li><a rel="noreferrer noopener" aria-label="Generic on Swift Doc (opens in a new tab)" href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html" target="_blank">Generic on Swift Doc</a></li></ul>
<p>The post <a href="https://mobidevtalk.com/swift-generic-protocol/">Swift Generic &#038; Protocol</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-generic-protocol/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1813</post-id>	</item>
		<item>
		<title>Swift Protocol Hub</title>
		<link>https://mobidevtalk.com/swift-protocol-hub/</link>
					<comments>https://mobidevtalk.com/swift-protocol-hub/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Thu, 19 Sep 2019 00:56:52 +0000</pubDate>
				<category><![CDATA[Hub]]></category>
		<category><![CDATA[protocol]]></category>
		<category><![CDATA[Protocol-oriented programming]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1444</guid>

					<description><![CDATA[<p>According to Apple, declared on WWDC 2015, Swift is the first Protocol Oriented Programming (POP) language....</p>
<p><a href="https://mobidevtalk.com/swift-protocol-hub/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Protocol Hub</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-protocol-hub/">Swift Protocol Hub</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>According to Apple, declared on WWDC 2015, Swift is the first Protocol Oriented Programming (POP) language. As it seems Protocol is one of the core foundations for Swift learning. To have a better understanding of Swift one has to have a better understanding of Protocol. The Swift book from Apple covers all the basic parts related to the protocol. But here we are more concerned about the usage of Protocol. Such as how and when we should related protocol on our problem domain. In fact what specific problem protocol does resolve. What benefits we will have on using the protocol. Things like those are discussed all through on mobidevtalk through different blog posts. The purpose of this blog post, Swift Protocol Hub, is to list them all in one place. So that we can have a common place to start from. </p>



<p>As always we consider, you already have some reading on the protocol from the apple provided book or through any other medium. Because we will not cover the basic part of protocol on the blog posts. We are focusing on the protocol used on the real problems. Talking about the real problems, we will have some little to medium size use case-based problems to ease our learning of protocol. So let get started.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#At-a-glance">At a glance</a></li><li><a href="#Inheritance-Initiator-of-coupling">Inheritance, Initiator of coupling</a></li><li><a href="#Composition-breaker-of-chains">Composition, breaker of chains</a></li><li><a href="#Protocol-Swift-way-of-thinking">Protocol, Swift way of thinking</a></li><li><a href="#Introduction-of-Dependency-Inversion-on-Swift">Introduction of Dependency Inversion on Swift</a></li><li><a href="#Swift-Dependency-Inversion-through-Protocol">Swift Dependency Inversion through Protocol</a></li><li><a href="#Dependency-Injection-in-Swift">Dependency Injection in Swift</a></li></ul>



<h2 class="wp-block-heading" id="At-a-glance">At a glance</h2>



<p>Now on Swift Protocol Hub we will be introduced with the following talks.</p>



<div class="wp-block-columns has-2-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a rel="noreferrer noopener" aria-label="￼
Inheritance, Initiator of coupling (opens in a new tab)" href="https://mobidevtalk.com/inheritance-initiator-of-coupling/" target="_blank"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="99" class="wp-image-883" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Couple.jpg?resize=350%2C99&#038;ssl=1" alt="Inheritance results Coupling" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Couple.jpg?w=1024&amp;ssl=1 1024w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Couple.jpg?resize=300%2C85&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Couple.jpg?resize=768%2C218&amp;ssl=1 768w" sizes="auto, (max-width: 350px) 100vw, 350px" /><br>Inheritance, Initiator of coupling</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a rel="noreferrer noopener" aria-label="￼
Composition, breaker of chains (opens in a new tab)" href="https://mobidevtalk.com/composition-breaker-of-chains/" target="_blank"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="151" class="wp-image-880" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Composition-breaker-of-chains-e1553947320707.jpg?resize=350%2C151&#038;ssl=1" alt="Swift protocol composition" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Composition-breaker-of-chains-e1553947320707.jpg?w=1024&amp;ssl=1 1024w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Composition-breaker-of-chains-e1553947320707.jpg?resize=300%2C130&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/03/Composition-breaker-of-chains-e1553947320707.jpg?resize=768%2C332&amp;ssl=1 768w" sizes="auto, (max-width: 350px) 100vw, 350px" /><br>Composition, breaker of chains</a></p>
</div>
</div>



<div class="wp-block-columns has-2-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a rel="noreferrer noopener" aria-label="￼
Protocol, Swift way of thinking (opens in a new tab)" href="https://mobidevtalk.com/protocol-swift-practical-use-case/" target="_blank"><img data-recalc-dims="1" loading="lazy" decoding="async" width="250" height="188" class="wp-image-973" style="width: 250px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/04/Protocol-Swift-way-of-thinking.jpg?resize=250%2C188&#038;ssl=1" alt="Protocol Swift way of thinking" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/04/Protocol-Swift-way-of-thinking.jpg?w=1024&amp;ssl=1 1024w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/04/Protocol-Swift-way-of-thinking.jpg?resize=300%2C225&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/04/Protocol-Swift-way-of-thinking.jpg?resize=768%2C576&amp;ssl=1 768w" sizes="auto, (max-width: 250px) 100vw, 250px" /><br>Protocol, Swift way of thinking</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a rel="noreferrer noopener" aria-label="￼
Introduction of Dependency Inversion on Swift (opens in a new tab)" href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/" target="_blank"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="263" class="wp-image-1127" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/Introduction-of-Dependency-Inversion-on-Swift.jpg?resize=350%2C263&#038;ssl=1" alt="Introduction of Dependency Inversion on Swift" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/Introduction-of-Dependency-Inversion-on-Swift.jpg?w=1024&amp;ssl=1 1024w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/Introduction-of-Dependency-Inversion-on-Swift.jpg?resize=300%2C225&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/Introduction-of-Dependency-Inversion-on-Swift.jpg?resize=768%2C576&amp;ssl=1 768w" sizes="auto, (max-width: 350px) 100vw, 350px" /><br>Introduction of Dependency Inversion on Swift</a></p>
</div>
</div>



<div class="wp-block-columns has-2-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" target="_blank" rel="noreferrer noopener" aria-label="￼
Swift Dependency Inversion through Protocol (opens in a new tab)"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="237" class="wp-image-1180" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?resize=350%2C237&#038;ssl=1" alt="Dependency Inversion Principle through protocol, UITableViewDataSource, on Swift" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?w=723&amp;ssl=1 723w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?resize=300%2C203&amp;ssl=1 300w" sizes="auto, (max-width: 350px) 100vw, 350px" /><br>Swift Dependency Inversion through Protocol</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center"><a aria-label="￼
Dependency Injection in Swift (opens in a new tab)" rel="noreferrer noopener" href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/" target="_blank"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="303" class="wp-image-1286" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/07/DI_feature_image-e1562483327185.png?resize=350%2C303&#038;ssl=1" alt="Dependency Injection" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/07/DI_feature_image-e1562483327185.png?w=1051&amp;ssl=1 1051w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/07/DI_feature_image-e1562483327185.png?resize=300%2C260&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/07/DI_feature_image-e1562483327185.png?resize=768%2C666&amp;ssl=1 768w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/07/DI_feature_image-e1562483327185.png?resize=1024%2C888&amp;ssl=1 1024w" sizes="auto, (max-width: 350px) 100vw, 350px" /><br>Dependency Injection in Swift</a></p>
</div>
</div>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:100%">
<p class="has-text-align-center"><a href="https://mobidevtalk.com/associatedtype-on-protocol/"><img data-recalc-dims="1" loading="lazy" decoding="async" width="350" height="176" class="wp-image-2004" style="width: 350px;" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2021/07/FI_associatedtype_Protocol-Generic.jpg?resize=350%2C176&#038;ssl=1" alt="associatedtype Protocol Generic" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2021/07/FI_associatedtype_Protocol-Generic.jpg?w=1196&amp;ssl=1 1196w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2021/07/FI_associatedtype_Protocol-Generic.jpg?resize=300%2C151&amp;ssl=1 300w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2021/07/FI_associatedtype_Protocol-Generic.jpg?resize=1024%2C515&amp;ssl=1 1024w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2021/07/FI_associatedtype_Protocol-Generic.jpg?resize=768%2C386&amp;ssl=1 768w" sizes="auto, (max-width: 350px) 100vw, 350px" /></a><br><a href="https://mobidevtalk.com/associatedtype-on-protocol/" target="_blank" rel="noreferrer noopener">associatedtype on Protocol</a></p>
</div>
</div>



<p>Let have some small review on each of the posts.</p>



<h2 class="wp-block-heading" id="Inheritance-Initiator-of-coupling"><a rel="noreferrer noopener" href="https://mobidevtalk.com/inheritance-initiator-of-coupling/" target="_blank">Inheritance, Initiator of coupling</a></h2>



<p>One the first part of our protocol journey, <a rel="noreferrer noopener" href="https://mobidevtalk.com/inheritance-initiator-of-coupling/" target="_blank">Inheritance, Initiator of coupling</a>, we talk about how we initiate the inheritance on the code base for removing the code duplicity. We also talked about the benefit of inheritance we can have. But moreover how this simple benefit can lead us to a very tightly coupled code, which slows us down to adapt to the ever-changing requirements.</p>



<h2 class="wp-block-heading" id="Composition-breaker-of-chains"><a rel="noreferrer noopener" href="https://mobidevtalk.com/composition-breaker-of-chains/" target="_blank">Composition, breaker of chains</a></h2>



<p>In the second talk, Composition, breaker of chains, we move our focus to composition. Which enables us to adopt the requirements changes far more quickly and easily than the typical inheritance. We build a Justice league(theoretically of course 😉) and resolve the issues we had with inheritance way. We talk about multiple inheritances and finish that talk with the pros and cons of composition.</p>



<h2 class="wp-block-heading" id="Protocol-Swift-way-of-thinking"><a rel="noreferrer noopener" href="https://mobidevtalk.com/protocol-swift-practical-use-case/" target="_blank">Protocol, Swift way of thinking</a></h2>



<p>This talk, <a rel="noreferrer noopener" href="https://mobidevtalk.com/protocol-swift-practical-use-case/" target="_blank">Protocol, Swift way of thinking</a>, can be the center of protocol-based talking on mobidevtalk. Because here we talk about the core concepts of protocol usage. So things like why we need to use protocol and why it is the best choice on Swift are discussed here. This time we bring the Avengers(again theoretically 🤓) to provide us the protocol-oriented programming concepts. Basically, this blog post is the very first step of protocol first thinking patterns on this blog site.</p>



<h2 class="wp-block-heading" id="Introduction-of-Dependency-Inversion-on-Swift"><a rel="noreferrer noopener" href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/" target="_blank">Introduction of Dependency Inversion on Swift</a></h2>



<p>From this talk, <a rel="noreferrer noopener" href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/" target="_blank">Introduction of Dependency Inversion on Swift</a>, we start to shift our focus more on the problem that protocol resolves. In that direction, the very first concept is dependency inversion. Here we talk about what is actually dependency inversion. Through the diagram of code example, we had an in-depth discussion over dependency inversion. Basically, this blog post is the go first when we need to know, how the protocol functions on Swift to have a swift way of coding.</p>



<h2 class="wp-block-heading" id="Swift-Dependency-Inversion-through-Protocol"><a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" target="_blank">Swift Dependency Inversion through Protocol</a></h2>



<p>This talk, <a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" target="_blank">Swift Dependency Inversion through Protocol</a>, is the star of the day. Because this part is the practical implementation of dependency inversion on Swift through the protocol. This blog post not only talks about the how-when of the protocol used for gaining dependency inversion but also the best possible way for achieving that.</p>



<h2 class="wp-block-heading" id="Dependency-Injection-in-Swift"><a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/" target="_blank">Dependency Injection in Swift</a></h2>



<p>Face it, Dependency injection is an alien for us. A very simple concept surrounded by some very unknown myths. But Dependency Injection need not be like that. Surely you will believe the same way after you read Dependency Injection in Swift. In this blog post, we first remove those myths and express the simple picture of dependency injection. Then gradually we start to implement the same concept on our swift code base. We discussed how the protocol can come in handy on dependency injection. We talked about the benefits and drawbacks of dependency inversion. In the end, we finish the talk with some tricks and tips to achieve dependency inversion on Swift.</p>



<h2 class="wp-block-heading"><a href="https://mobidevtalk.com/associatedtype-on-protocol/">associatedtype in Protocol</a></h2>



<p>associatedtype is not always been very clear to us all. But in reality, associatedtype is not a very big deal. We just need four mins reading. That is it. Once we have a clear concept of the associatedtype we can move further to understand a lot more complex errors, which usually occurs when dealing with the generic protocol. So this blog post is an introductory one for a bigger concept, Generic Protocol.</p>



<h2 class="wp-block-heading">End Talk</h2>



<p>Whether it is inheritance or composition, there is no single way to go. Programming is all about choosing the balance. The right amount of balance is the sweet spot. But to find that sweet spot we need to have the necessary knowledge on each end. The knowledge about the pros and cons for each end will ease a lot for finding the proper balance. Swift Protocol Hub discusses the highlights of the post that gonna make us a bit more knowledgeable on the protocol domain and its related concepts. Hope you enjoy it. Take care.</p>



<h2 class="wp-block-heading">Reference</h2>



<ul class="wp-block-list"><li><a href="https://books.apple.com/us/book/the-swift-programming-language-swift-5-1/id881256329">Swift Book from Apple</a></li></ul>
<p>The post <a href="https://mobidevtalk.com/swift-protocol-hub/">Swift Protocol Hub</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-protocol-hub/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1444</post-id>	</item>
		<item>
		<title>Swift Generic introduction</title>
		<link>https://mobidevtalk.com/swift-generic-introduction/</link>
					<comments>https://mobidevtalk.com/swift-generic-introduction/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Mon, 16 Sep 2019 00:50:26 +0000</pubDate>
				<category><![CDATA[Q/A]]></category>
		<category><![CDATA[generic]]></category>
		<category><![CDATA[generic introduction]]></category>
		<category><![CDATA[Swift]]></category>
		<category><![CDATA[TDD]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1399</guid>

					<description><![CDATA[<p>The Generic realm is that kind of world, which we think we have some good understanding....</p>
<p><a href="https://mobidevtalk.com/swift-generic-introduction/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Generic introduction</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-generic-introduction/">Swift Generic introduction</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The Generic realm is that kind of world, which we think we have some good understanding. And probably so. But things start to get messy when we initiate the implementation of so called Generic solution on our code base. The implementation doesn&#8217;t go so well as we used to see them on the example of books or blog-posts. Why? There are couple of reasons for that. Either we are not clear on the concepts of Generic. Or we still don&#8217;t have the understanding of when and how to implement the Generic solution on our code. So here on this blog post series we will talk about Generic. On this first blog post we will talk about Swift Generic introduction. After that on the second blog post we will have a more advance level implementation of Generic solution on our Swift code base.</p>



<p>As Apple already had some awesome details on Generic and its related concepts on different section on <a rel="noreferrer noopener" href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html" target="_blank">Apple doc on Generic</a>. So going through those will definitely be a redundant talk. </p>



<p>However on this blog post we will touch the basic concepts of generic on Swift as an introduction talk through a very basic case study implementation. This time our case study will be <code>Palindrome</code>. Let us get started.</p>



<p>For a bit more advance level we can check out our <a href="https://mobidevtalk.com/swift-generic-protocol/" target="_blank" rel="noreferrer noopener" aria-label="Swift Generic &amp; Protocol (opens in a new tab)">Swift Generic &amp; Protocol</a> blog post.</p>



<h2 class="wp-block-heading">Background</h2>



<p>Our target is to build a simple playground project which can verify if an input is a Palindrome or not. On this case study we will add one by one requirement to make our solution generic. This should be the regular practice on implementing generic solution. On the evolution of the case study we will talk or share the reference of generic concepts if any needed.</p>



<ul class="wp-block-list"><li><a href="#What-is-Palindrome">What is Palindrome</a></li><li><a href="#The-Test-Observer-snippet">The Test Observer snippet</a></li><li><a href="#Detecting-a-String-Palindrome">Detecting a </a><code><a href="#Detecting-a-String-Palindrome">String</a></code><a href="#Detecting-a-String-Palindrome"> Palindrome</a></li><li><a href="#TDD-approach">TDD approach</a></li><li><a href="#Continuing-with-string-palindrome">Continuing with string palindrome</a></li><li><a href="#How-about-a-Palindrome-of-Int">How about a Palindrome of </a><code><a href="#How-about-a-Palindrome-of-Int">Int</a></code></li><li><a href="#Can-we-have-Double-Palindrome">Can we have </a><code><a href="#Can-we-have-Double-Palindrome">Double</a></code><a href="#Can-we-have-Double-Palindrome"> Palindrome</a></li><li><a href="#Converting-into-a-more-Generic-solution-for-detecting-Palindrome">Converting into a more Generic solution for detecting Palindrome</a></li><li><a href="#Summarizing-the-generic-evolution-for-the-problem">Summarizing the generic evolution for the problem</a></li><li><a href="#Best-practice-for-implementing-generic-solution">Best practice for implementing generic solution</a></li></ul>



<p>On the playground project we will use the TDD approach to verify our tinny solution. We need not to fear on that, because it will be pretty simple and understandable. Big thanks to Sundell for his awesome snippets for <a rel="noreferrer noopener" href="https://www.swiftbysundell.com/posts/writing-unit-tests-in-a-swift-playground" target="_blank">Test on Playground</a>. We will write a <code>TestObserver</code> to run our test on playground. Details code are available on GitHub.</p>



<p>And if we need some memory recall about snippets, then surely we can have a look on our <a rel="noreferrer noopener" aria-label="snippets talk (opens in a new tab)" href="https://mobidevtalk.com/xcode-code-snippets/" target="_blank">snippets talk</a>. Thats a small talk containing all the necessary things related with Snippets on Xcode. Video is also included to ease the different steps.</p>



<h2 class="wp-block-heading" id="What-is-Palindrome">What is Palindrome</h2>



<p>It is an interesting concept. But rather a simple one. Palindrome sequence is same on both forward and backward reading. We often say <code>wow</code>. This <code>wow</code> is a simple palindrome. As it is same on forward and backward read. Other examples are <code>noon</code>, <code>madam</code>, <code>refer</code>, <code>mom</code> etc. Guessing we can find a lot through simple google search on Palindrome, so moving on the case study implementation now.</p>



<h2 class="wp-block-heading" id="The-Test-Observer-snippet">The Test Observer snippet</h2>



<p>To continuing our playground project we will use the following Snippets to run our test. Again thanks to Sundell.</p>



<pre><code class="language-swift">
class TestObserver: NSObject, XCTestObservation {
    func testCase(_ testCase: XCTestCase,
                  didFailWithDescription description: String,
                  inFile filePath: String?,
                  atLine lineNumber: Int) {
        assertionFailure(description, line: UInt(lineNumber))
    }
}

let testObserver = TestObserver()
XCTestObservationCenter.shared.addTestObserver(testObserver)
<#TestSuite#>.defaultTestSuite.run()
</code></pre>



<h2 class="wp-block-heading" id="Detecting-a-String-Palindrome">Detecting a <code>String</code> Palindrome</h2>



<p>On the very start let us build a simple solution to detect if an input string is a Palindrome or not.  We will write some test codes for verifying our solution. </p>



<p>Now what should be our first test case. Hmmm. Let say if a <code>string</code> is not a palindrome then we will say its not a palindrome, right? Simple. 🤓</p>



<p>As it goes on the TDD, let us first have a fail test case. So we will write:</p>



<pre><code class="language-swift">
func test_nonPalindrome_string_false() {
        let input = "nonPalindrome"
        XCTAssertFalse(input.isPalindrome, "\(input) is not be a Palindrome")
    }
</code></pre>



<p>As we can see the <code>nonPalindrome</code> is no way a palindrome. So we should have a false return on <code>isPalindrome</code>. But we have an error: <code>Value of type 'String' has no member 'isPalindrome'</code>. Hmm failed case. Let us define the minimal code to pass the test.</p>



<pre><code class="language-swift">
extension String{
    var isPalindrome: Bool {
        return false
    }
}
</code></pre>



<p>Now we have a <code>isPalindrome</code> which passes our test. But wait! Returning false not gonna work on future. Ya ya we know, but it&#8217;s the TDD way. </p>



<h2 class="wp-block-heading" id="TDD-approach">TDD approach</h2>



<p>For the each test case repeat the following:</p>



<ul class="wp-block-list"><li>Write a fail test</li><li>Write minimal code to pass that test</li><li>Refactor the code</li></ul>



<p>Then we will move to the next test case and follow the above approaches. And will continue on this way until all the test cases are passed. On some future time we will have details talk on TDD.</p>



<h2 class="wp-block-heading" id="Continuing-with-string-palindrome">Continuing with string palindrome</h2>



<p>Now for our next test case we will have a valid palindrome and for that the <code>isPalindrome</code> should return <code>true</code>. </p>



<pre><code class="language-swift">
func test_palindrome_string_true() {
        let input = "wow"
        XCTAssertTrue(input.isPalindrome, "\(input) is a Palindrome")
    }
</code></pre>



<p>Guess what, we have a fail test case. <code>isPalindrome</code> is returning <code>false</code>, where it should return <code>true</code>. Minimal code to fix that, right:</p>



<p>Replace the value of <code>isPalindrome</code> with <code>return self == String(self.reversed())</code> where in previously it was returning <code>false</code>. So the <code>isPalindrome</code> on the <code>String</code> extension becomes as following:</p>



<pre><code class="language-swift">
extension String{
    var isPalindrome: Bool {
        return self == String(self.reversed())
    }
}
</code></pre>



<p>Re run the tests and everything pass. Now let us have some other tests to verify our solution.</p>



<pre><code class="language-swift">
func test_nonPalindrome_text_false() {
        let input = "This is a non-palindrome text"
        XCTAssertFalse(input.isPalindrome, "Should have return false for: \n \(input)")
    }
    
    func test_palindrome_text_true() {
        let input = "wow wow"
        XCTAssertTrue(input.isPalindrome, "Should have return true for: \(input)")
    }
    
    func test_nonPalindrome_textWithSpace_false() {
        let input = "wow wow "
        XCTAssertFalse(input.isPalindrome, "Should have return true for: \(input)")
    }
    
    func test_nonPalindrome_mixCase_false() {
        let input = "Wow wow"
        XCTAssertFalse(input.isPalindrome, "Should return false as there is a capital W on the\n \(input)")
    }
    
    func test_palindrome_mixCase_true() {
        let input = "Wow woW"
        XCTAssertTrue(input.isPalindrome, "Even case is mixed but this is a palindrome text:\n \(input)")
    }
</code></pre>



<p>Think we have cover for <code>String</code> type now. Let us move to other type such as <code>Int</code>.</p>



<h2 class="wp-block-heading" id="How-about-a-Palindrome-of-Int">How about a Palindrome of <code>Int</code></h2>



<p>Now heres come the new requirement. We need to support Int also. So what will be some example of Int palindrome? 121, 44, 12321 etc. </p>



<p>Our first test case is 100 which is not a palindrome. </p>



<pre><code class="language-swift">
func test_nonPalindrome_Int_false(){
        let input = 100
        XCTAssertFalse(input.isPalindrome, "\(input) is not a palindrome Int")
    }
</code></pre>



<p>Same way the test fails as <code>isPalindrome</code> is not defined for Int. Let us fix that.</p>



<p>Here we will go for a very simple implementation  for palindrome in Int. We will just convert the Int to String and use the String type&#8217;s <code>isPalindrome</code> to verify.</p>



<pre><code class="language-swift">
extension Int{
    var isPalindrome: Bool{
        return String(self).isPalindrome
    }
}
</code></pre>



<p>Our primary goal of this talk is to build the generic environment rather than solving the palindrome problem. So let us stick with the solution and continue with it.</p>



<p>Now after having this test code we can see the test case<code>100</code> is passing. Let us add a Palindrome Int then.</p>



<pre><code class="language-swift">
func test_palindrome_Int_true() {
        let input = 121
        XCTAssertTrue(input.isPalindrome, "\(input) is a palindrome Int")
    }
</code></pre>



<p>Ok this one also pass and finally we have a Int palindrome test. </p>



<p>How about some more test on Int.</p>



<pre><code class="language-swift">
    func test_longPalindrome_Int_true() {
        let input = 0000000000
        XCTAssertTrue(input.isPalindrome, "Long sequence on Zero should be a palindrome")
    }
    
    func test_nonPalindrome_negativeInt_false() {
        let input = -111
        XCTAssertFalse(input.isPalindrome, "\(input) should not be a palindrome")
    }
</code></pre>



<p>Hmm things are passing and we are good. Moving to Double palindrome.</p>



<h2 class="wp-block-heading" id="Can-we-have-Double-Palindrome">Can we have <code>Double</code> Palindrome</h2>



<p>Ok now how about Double palindrome. Palindrome on Double happens to be not only same sequence before and after the period <code>.</code>, but also the sequence should themself be palindrome like Int palindrome. So 131.131 is a palindrome. On the other hand 12.121 is not a palindrome. Even though the numbers without period/dot is a palindrome.</p>



<p>Time for some double palindrome test.</p>



<pre><code class="language-swift">
    func test_nonPalindrome_double_false() {
        let input = 12.01
        XCTAssertFalse(input.isPalindrome, "\(input) should not be a Palindrome Double")
    }
    
    func test_Palindrome_double_true() {
        let input = 12.21
        XCTAssertTrue(input.isPalindrome, "\(input) should be a Palindrome Double")
    }
    
    func test_Palindrome_double_true_aroundPeriod() {
        let input = 12.121
        XCTAssertFalse(input.isPalindrome, "Even though the 12121 is a palindrome, but \(input) must be palindrome around period")
    }
</code></pre>



<p>As we already guess for now the double <code>isPalindrome</code> is as following:</p>



<pre><code class="language-swift">
extension Double{
    var isPalindrome: Bool{
        return String(self).isPalindrome
    }
}
</code></pre>



<h2 class="wp-block-heading" id="Converting-into-a-more-Generic-solution-for-detecting-Palindrome">Converting into a more Generic solution for detecting Palindrome</h2>



<p>Now we already have the big picture. So now let us have a introduction to a more Generic solution on our Swift code.</p>



<p>We gonna have a generic solution based on the way we just compare the String format of a type(Int, Double) with the reverse String format to validate the Palindrome sequence. For doing so we have to make sure that the type is confirming the <code>LosslessStringConvertible</code> protocol. Otherwise the conversion to String will fail on compile time. So our generic solution as follows:</p>



<pre><code class="language-swift">
func palindrome<T: LosslessStringConvertible>(input: T) -> Bool{
    let stringFormatted = String(input)
    return stringFormatted == String(stringFormatted.reversed())
}
</code></pre>



<p>As a result we can have the test as following:</p>



<pre><code class="language-swift">
func test_String() {
        let palindromeString = "wow wow"
        XCTAssertTrue(palindrome(input: palindromeString), "Should be a palindrome String")
        
        let nonPalindromeString = "nonPalindrome"
        XCTAssertFalse(palindrome(input: nonPalindromeString), "Should not be a palindrome string")
        
    }
    
    func test_Int() {
        let palindromeInt = 121
        XCTAssertTrue(palindrome(input: palindromeInt), "Should be a Int Palindrome")
        
        let nonPalindromeInt = 100
        XCTAssertFalse(palindrome(input: nonPalindromeInt), "Should not be a Palindrome Int")
    }
    
    func test_Double() {
        let palindromeDouble = 12.21
        XCTAssertTrue(palindrome(input: palindromeDouble), "Should be a Double Palindrome")
        
        let nonPalindromeDouble = 12.121
        XCTAssertFalse(palindrome(input: nonPalindromeDouble), "Should not be a Palindrome Double")
    }
</code></pre>



<h2 class="wp-block-heading" id="Summarizing-the-generic-evolution-for-the-problem">Summarizing the generic evolution for the problem</h2>



<p>Maybe the overall solution and the case study is pretty easy and strait forward. But this was meant to be an introductory post on Generic. So let us have some basic discussion aka easy-peasy talk with the generic solution. We will continue the discussion with some very basic question. Now we had the Generic method which is as follow:</p>



<pre><code class="language-swift">
func palindrome<T: LosslessStringConvertible>(input: T) -> Bool
</code></pre>



<h3 class="wp-block-heading"> What is the <code>T</code>?</h3>



<p>So <code>T</code> defines a generic type, the type can be <code>Int</code> <code>Double</code> <code>String</code> or any other type. On run time the Generic type <code>T</code> will be replaced with the actual type.  </p>



<p>Commute can be a similar example of generic type ,<code>T</code> , if we want to relate the generic concept with the real life. So when we say a 10 mins commute, the commute does not say anything about the commute type like walking biking or commuting through car bus. This just say a 10 mins commute. We implement the commute on run time or in real life when we start the commute through any of the commute type.</p>



<p>Now what if  there is multiple Generic type. Convention is to use <code>U</code> or any other you like to use.</p>



<h3 class="wp-block-heading">does <code>T</code> inherits from <code>LosslessStringConvertible</code>?</h3>



<p>Second question does <code>T</code> inherits from <code>LosslessStringConvertible</code>? Well on Swift world we would use the term confirms to <code>LosslessStringConvertible</code> rather than the inherits. Because <code>LosslessStringConvertible</code> is a protocol. Ok but whats with the inheritance and protocol confirmation? Hmm let us have some shared links. <a rel="noreferrer noopener" aria-label="Here (opens in a new tab)" href="https://mobidevtalk.com/inheritance-initiator-of-coupling/" target="_blank">Here</a> you will get the inheritance talk. And <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://mobidevtalk.com/composition-breaker-of-chains/" target="_blank">here</a> you will get the protocol confirmation talk. Both of these two are a series of continuous blog post where we discussed why composition over inheritance is better and how to achieve composition? Feel free to pay a visit on those blog post on your free time.</p>



<h3 class="wp-block-heading">what does the  <code>T: LosslessStringConvertible</code> mean?</h3>



<p>Now in plain word <code>T: LosslessStringConvertible</code> means <code>T</code> can be any type but that type need to confirm <code>LosslessStringConvertible</code> protocol. Thats why the <code>Float</code> can not call the generic function as <code>Float</code> does not confirms the <code>LosslessStringConvertible</code> protocol.</p>



<h3 class="wp-block-heading">Do the angle brackets <code>&lt; &gt;</code> has some value on generic?</h3>



<p>It is a generic way of representing generic definition. Those two angle brackets tells the reader and the compiler that we have a generic type with its requirements.</p>



<h3 class="wp-block-heading">Do we read <code>input: T</code> the same way as we do on other functions</h3>



<p>Yes, that is what <code>input: T</code> mean. It says <code>input</code> is a <code>T</code> type of instance when it is compiled. And on run time the <code>T</code> is replaced with the actual type.</p>



<p>Why do we need the <code>T</code> to confirm <code>LosslessStringConvertible</code></p>



<p>Because we are converting the Generic type to <code>String</code> when we are writing <code>String(input)</code>, where <code>input: T</code>. </p>



<h2 class="wp-block-heading" id="Best-practice-for-implementing-generic-solution">Best practice for implementing generic solution</h2>



<p>Though this was a pretty easy talk on Generic introduction on Swift, but this can a good place to know when we should go for generic solution. </p>



<p>Let us consider another solution of this same problem through Swift extensibility feature. Let us extend <code>LosslessStringConvertible</code> to have the same functionality. So the final pice of code.</p>



<pre><code class="language-swift">
extension LosslessStringConvertible{
    var palindrome: Bool{
        let stringForm = String(self)
        return stringForm == String(stringForm.reversed())
    }
}
</code></pre>



<p>Now this version is very concise.  So which one is the right approach?</p>



<p>If we use the approach of extending the <code>LosslessStringConvertible</code> protocol then all the types that confirms <code>LosslessStringConvertible</code> now have the <code>palindrome</code> var. Do our use case suggest that? If not the the generic function approach is the solution.</p>



<p>So let us finish this blog post by having some guidelines on best practice for implementing generic solution:</p>



<ul class="wp-block-list"><li>Generic solution is must when type safety is a major priority.</li><li>Generic solution is good for implementing algorithm.</li><li>When ever there is code duplication we can count generic on that case.</li><li>Most importantly we can avoid the ugly type casting.</li><li>And finally to restrict ourself from using <code>Any</code>.</li></ul>



<h3 class="wp-block-heading">Generic vs Any</h3>



<p>On this Introduction of Swift Generic talk we have not cover a very important topic. The topic of when to choose <code>Any</code> over Generic or vice versa. Perhaps that needs a separated talk. On some future talk we will highlight the points for reducing the use of <code>Any</code> on our beloved code base.</p>



<h2 class="wp-block-heading">End talk</h2>



<p>It takes time and patient to set our mind for using Generic. This Swift Generic introduction blog post is the very first one of a series where we will try to achieve this goal. Let stay tune. The <a href="https://mobidevtalk.com/swift-generic-protocol/">next one</a> will not be so easy-peasy. The source code of this talk is shared on <a href="https://github.com/mobidevtalk/Generic/blob/master/Generic.playground/Pages/Introduction.xcplaygroundpage/Contents.swift">Github</a>.</p>



<h2 class="wp-block-heading">Reference</h2>



<ul class="wp-block-list"><li><a href="https://mobidevtalk.com/swift-generic-protocol/">Swift Generic &amp; Protocol</a></li><li><a href="https://mobidevtalk.com/xcode-code-snippets/">Snippets</a></li><li><a href="https://github.com/mobidevtalk/Generic/blob/master/Generic.playground/Pages/Introduction.xcplaygroundpage/Contents.swift">Playground source code @GitHub</a></li><li><a rel="noreferrer noopener" aria-label="Apple doc on Generic (opens in a new tab)" href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html" target="_blank">Apple doc on Generic</a></li><li><a rel="noreferrer noopener" aria-label="Swift Generic (expanded) (opens in a new tab)" href="https://developer.apple.com/videos/play/wwdc2018/406/" target="_blank">Swift Generic (expanded)</a></li><li><a aria-label="Test on Playground by Sundell (opens in a new tab)" rel="noopener noreferrer" href="https://mobidevtalk.com/xcode-code-snippets/" target="_blank">Swift snippets</a></li><li><a aria-label="Test on Playground by Sundell (opens in a new tab)" rel="noreferrer noopener" href="https://www.swiftbysundell.com/posts/writing-unit-tests-in-a-swift-playground" target="_blank">Test on Playground by Sundell</a></li><li><a rel="noreferrer noopener" aria-label="Playground tips &amp; tricks by Sundell (opens in a new tab)" href="https://www.swiftbysundell.com/posts/swift-playgrounds-tips-tricks" target="_blank">Playground tips &amp; tricks by Sundell</a></li></ul>



<p></p>
<p>The post <a href="https://mobidevtalk.com/swift-generic-introduction/">Swift Generic introduction</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-generic-introduction/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1399</post-id>	</item>
		<item>
		<title>Xcode Shortcuts the iOS Cheat Sheet</title>
		<link>https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/</link>
					<comments>https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Fri, 02 Aug 2019 19:13:06 +0000</pubDate>
				<category><![CDATA[Pragmatic]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[Simulator shortcut]]></category>
		<category><![CDATA[Xcode shortcuts]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1323</guid>

					<description><![CDATA[<p>On our Xcode Snippets talk, we introduce the term Sloths Speed Coder. None of us want...</p>
<p><a href="https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Xcode Shortcuts the iOS Cheat Sheet</span></a></p>
<p>The post <a href="https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/">Xcode Shortcuts the iOS Cheat Sheet</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>On our <a rel="noreferrer noopener" aria-label="Xcode Snippets talk (opens in a new tab)" href="https://mobidevtalk.com/xcode-code-snippets/" target="_blank">Xcode Snippets talk</a>, we introduce the term Sloths Speed Coder. None of us want to be a slow boring coder. We can choose, not be a Sloths Speed Coder. We said the first step is to start using Code Snippets and today we gonna talk about the second step. Shortcuts, Xcode Shortcuts. A craftsman always knows his tool. He knows how to use it. In order to be a better craftsman on iOS we also need to put some special care on Xcode Shortcuts, the iOS Cheat Sheet. Why the iOS Cheat Sheet? Well there is no shortcut on success, but there are always some boost on the path of learning. The Xcode Shortcuts are similarly the boost for iOS learning. Suddenly you act like a pro. It is kind of a cheat sheet for achieving the next pro batch from the starter. </p>



<p>Well if you use some other cool stuff like <a rel="noreferrer noopener" aria-label="AppCode (opens in a new tab)" href="https://www.jetbrains.com/objc/" target="_blank">AppCode</a>, then this blog post may not add value to your craftsmanship. Otherwise let us dive deep 🌊.</p>



<p>Another very useful shortcut for me is the slowing down the Simulator&#8217;s animation. By toggling the animation I can see the transformation in a far more greater details. There are also some shortcuts for scaling the simulator. These various Simulator Shortcuts are also the topic of this blog post. </p>



<p>At the end of this blog we can have <a href="#Give-me-my-free-Xcode-shortcut-resources">the Xcode and Simulator shortcuts in different format</a> to make life a lot easier.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#Build-&amp;-Run-Shortcuts">Build &amp; Run Shortcuts</a></li><li><a href="#Playground">Playground</a></li><li><a href="#Scheme-&amp;-Destination-based-Shortcuts">Scheme &amp; Destination based Shortcuts</a></li><li><a href="#Breakpoint">Breakpoint</a></li><li><a href="#Intra-File-Navigation">Intra File Navigation</a></li><li><a href="#Inter-File-Navigation">Inter File Navigation</a></li><li><a href="#Editor-shortcuts">Editor shortcuts</a></li><li><a href="#Moving-Focus-to-different-editor">Moving Focus to different editor</a></li><li><a href="#Find-&amp;-Replace">Find &amp; Replace</a></li><li><a href="#Tab-&amp;-Window-selection">Tab &amp; Window selection</a></li><li><a href="#Simulator-Shortcuts">Simulator Shortcuts</a></li><li><a href="#Adding-shortcuts-on-Xcode">Adding shortcuts on Xcode</a></li><li><a href="#Adding-Refactor-Renaming-shortcuts">Adding Refactor Renaming shortcuts</a></li><li><a href="#Xcode-Shortcuts-Conflict-resolving">Xcode Shortcuts Conflict resolving</a></li><li><a href="#How-to-use-this-blog-post">How to use this blog post</a></li><li><a href="#Give-me-my-free-Xcode-shortcut-resources">Give me my free Xcode shortcut resources</a></li><li><a href="#Reference">Reference</a></li></ul>



<p>Before we start we have to understand that the number of Xcode shortcuts are not short at all. There are thousands of shortcuts people use regularly. On this blog post I will share mine. </p>



<p>Some very obvious &amp; popular shortcuts like</p>



<ul class="wp-block-list"><li>toggling comment  <code>⌘ /</code> or <code>Command /</code></li><li>opening the Xcode preference <code>⌘ ,</code> or <code>Command ,</code></li></ul>



<p>will not be discussed here. Because either shortcuts like toggle comment is very well known or shortcuts like opening the Xcode preference is not regularly used. </p>



<p>We can watch the various Xcode &amp; Simulator shortcuts in action on our <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.youtube.com/playlist?list=PL2oMRmw1TrdkjlmRvJM54aw53_TXNn_X1" target="_blank">youtube playlist</a>. </p>



<h2 class="wp-block-heading" id="Build-&amp;-Run-Shortcuts">Build &amp; Run Shortcuts</h2>



<p>I believe we all use those shortcuts. </p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Build for Running</strong>
</td><td>
⌘ B
</td><td>
Command B
</td></tr><tr><td>
<strong>Build for Testing</strong>
</td><td>
⌘ ⇧ U
</td><td>
Command Shift U
</td></tr><tr><td>
<strong>Clean Build Folder</strong>
</td><td>
⌘ ⇧ K
</td><td>
Command Shift K
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Run</strong>
</td><td>
⌘ R
</td><td>
Command R
</td></tr><tr><td>
<strong>Stop running app</strong>
</td><td>
⌘ .
</td><td>
Command .
</td></tr><tr><td>
<strong>Run All Test</strong>
</td><td>
⌘ U
</td><td>
Command U
</td></tr></tbody></table>



<h2 class="wp-block-heading" id="Playground">Playground</h2>



<p>There are two useful playground shortcuts. Specially after you disable the auto run option.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Run</strong>
</td><td>
⌤&nbsp; R
</td><td> Control R <br>*customized </td></tr><tr><td>
<strong>Stop</strong>
</td><td>
⌤&nbsp; .
</td><td> Control . <br>*customized </td></tr></tbody></table>



<p>This two shortcuts are customized by me. It is my preference. You can add your based on your preference. Later on this blog post we have <a href="#Adding-shortcuts-on-Xcode">Adding shortcuts on Xcode</a> section, visit the section for more details on adding shortcuts on Xcode.</p>



<h2 class="wp-block-heading" id="Scheme-&amp;-Destination-based-Shortcuts">Scheme &amp; Destination based Shortcuts</h2>



<p>Now this Xcode shortcuts are not very common among us. But once you start to using those I am sure you can&#8217;t stop using these shortcuts. </p>



<p>Multiple scheme is a requirements now a days. We usually have two to three scheme like staging, production and release. All of those target individual endpoints for data fetching plus the other configuration setup. To support localization you also may have one or two schema. So now that you have multiple scheme how would you like them to run? Each time by clicking the schema from the list by a mouse or trackpad?</p>



<p>And what about the device or simulator selection? Agin will you use the mouse or trackpad?</p>



<p>Oh come on there is a far more better way than this. Let start using the shortcuts for Xcode Scheme and destination selection.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Next Scheme</strong>
</td><td>
⌘ ⌤&nbsp; ]
</td><td>
Command Control ]
</td></tr><tr><td>
<strong>Previous Scheme</strong>
</td><td>
⌘ ⌤&nbsp; [
</td><td>
Command Control [
</td></tr><tr><td>
<strong>Scheme selection list</strong>
</td><td>
⌤&nbsp; 0
</td><td>
Control 0
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Next Destination</strong>
</td><td>
⌘ ⌤ ⌥ &nbsp; ]
</td><td>
Command Control Option ]
</td></tr><tr><td>
<strong>Previous Destination</strong>
</td><td>
⌘ ⌤ ⌥ [
</td><td>
Command Control Option [
</td></tr><tr><td>
<strong>Destination selection list</strong>
</td><td>
⌤&nbsp; ⇧ 0
</td><td>
Control Shift 0
</td></tr></tbody></table>



<p>Let us have look on the Schema &amp; Destination based shortcuts in action.</p>



<figure class="wp-block-embed-youtube aligncenter wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Scheme &amp; Destination" width="640" height="360" src="https://www.youtube.com/embed/PrCreGw2g6U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Scheme &amp; Destination shortcuts</figcaption></figure>



<h2 class="wp-block-heading" id="Breakpoint">Breakpoint</h2>



<p>There are many of the breakpoints. But the most used are as following.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Add/Remove Breakpoint</strong>
</td><td>
⌘ \
</td><td>
Command \
</td></tr><tr><td>
<strong>Activate/Deactivate Break Point</strong>
</td><td>
⌘ Y
</td><td>
Command Y
</td></tr></tbody></table>



<p>Let&#8217;s see those in action.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Breakpoint" width="640" height="360" src="https://www.youtube.com/embed/RS72ZKrbCZY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Breakpoint shortcut</figcaption></figure>



<h2 class="wp-block-heading" id="Intra-File-Navigation">Intra File Navigation</h2>



<p>Now this one is a bit huge. It is far more faster movement once you have the mastery on the intra file or in file navigation.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Start of line</strong>
</td><td>
⌘ ←
</td><td>
Command Left Arrow
</td></tr><tr><td>
<strong>End of line</strong>
</td><td>
⌘ →
</td><td>
Command Right Arrow
</td></tr><tr><td>
<strong>Go to Line number</strong>
</td><td>
⌘ L
</td><td> Command L <br>Then type the line number </td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Start of Word</strong>
</td><td> ⌥ ←</td><td>
Option Left Arrow
</td></tr><tr><td>
<strong>End of Word</strong>
</td><td> ⌥ →</td><td>
Option Right Arrow
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Forward camelCase</strong>
</td><td> ⌤&nbsp;→&nbsp; </td><td> Control Right Arrow <br>*customized </td></tr><tr><td>
<strong>Backward camelCase</strong>
</td><td> ⌤&nbsp;←&nbsp; </td><td> Control Left Arrow <br>*customized </td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Scroll up</strong>
</td><td> ⌤ ↑&nbsp; </td><td> Control Up Arrow <br>*customized </td></tr><tr><td>
<strong>Scroll down</strong>
</td><td> ⌤ ↓&nbsp; </td><td> Control Down Arrow <br>*customized </td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Start of file</strong>
</td><td>
⌘ ↑
</td><td>
Command Up Arrow
</td></tr><tr><td>
<strong>End of file</strong>
</td><td>
⌘ ↓
</td><td>
Command Down Arrow
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Quick access on properties and methods</strong>
<strong>[Show Document items]</strong>
</td><td>
⌤&nbsp; 6
</td><td> Then write down the property/method name</td></tr></tbody></table>



<p>Let us watch the Intra file navigation in action.</p>



<figure class="wp-block-embed-youtube aligncenter wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Intra File Navigation" width="640" height="360" src="https://www.youtube.com/embed/81s273F0TBk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Intra file navigation</figcaption></figure>



<h2 class="wp-block-heading" id="Inter-File-Navigation">Inter File Navigation</h2>



<p>Now let us have a look on the inter file navigation. </p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Opening a file</strong>
</td><td>
⌘ ⇧ O
</td><td>
Command Shift O
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Previous Opened file</strong>
</td><td>
⌘ ⌤&nbsp; ←&nbsp;
</td><td>
Command Control Left
</td></tr><tr><td>
<strong>Latest Opened file</strong>
</td><td>
⌘ ⌤&nbsp; →&nbsp;
</td><td>
Command Control Right
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Related items like siblings, protocol, super/sub class etc.</strong>
</td><td>
⌤&nbsp; 1
</td><td>
Control 1
</td></tr><tr><td>
<strong>Selecting Project</strong>
</td><td>
⌤&nbsp; 4
</td><td>
Control 4
</td></tr><tr><td>
<strong>Selection among group</strong>
</td><td>
⌤&nbsp; 5
</td><td>
Control 5
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Toggling between Interface &amp; Implementation&nbsp;</strong>
</td><td> ⌘ ⌤ ↑&nbsp; <br>⌘ ⌤ ↓&nbsp; </td><td> Command Control Up <br>Command Control Down </td></tr></tbody></table>



<p>In action.</p>



<figure class="wp-block-embed-youtube aligncenter wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Inter file navigation" width="640" height="360" src="https://www.youtube.com/embed/0HnweTLjHqo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Inter file navigation</figcaption></figure>



<h2 class="wp-block-heading" id="Editor-shortcuts">Editor shortcuts</h2>



<p>The editor shortcuts as follows.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Showing Standard editor</strong>
</td><td>
⌘ ↩︎&nbsp;
</td><td>
Command Return
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Opening Assistant editor</strong>
</td><td>
⌘ ⌥ ↩︎&nbsp;
</td><td>
Command Option Return
</td></tr><tr><td>
<strong>Reseting Assistant editor</strong>
</td><td>
⌘ ⌥ ⇧ Z
</td><td>
Command Option Shift Z
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Opening Version editor</strong>
</td><td>
⌘ ⌥ ⇧ ↩︎&nbsp;
</td><td>
Command Option Shift Return
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Debug area toggling</strong>
</td><td>
⌘ ⇧ Y
</td><td>
Command Shift Y
</td></tr></tbody></table>



<p>In action.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Editor" width="640" height="360" src="https://www.youtube.com/embed/eY_2VY9ZrWE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Editor Shortcut</figcaption></figure>



<h2 class="wp-block-heading" id="Moving-Focus-to-different-editor">Moving Focus to different editor</h2>



<p>Suppose we have some editors open. But clicking is no doubt a time consuming task. So let us introduce ourself with editor focusing in Xcode.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Move focus to editor</strong>
</td><td>
⌘ J
</td><td>
Command J
</td></tr></tbody></table>



<p>In action.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Focusing Editor" width="640" height="360" src="https://www.youtube.com/embed/00Mov2-Ce4E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Xcode Editor Shortcuts</figcaption></figure>



<h2 class="wp-block-heading" id="Find-&amp;-Replace">Find &amp; Replace</h2>



<p>Find is one of the most common used shortcuts. The Find and Replace was a very useful one before Xcode&#8217;s refactoring was available 😜. Also the Refactoring in current scope and all through the project are also super useful shortcuts.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Find in file</strong>
</td><td>
⌘ F&nbsp;
</td><td>
Command F
</td></tr><tr><td>
<strong>Find in project</strong>
</td><td>
⌘ ⇧ F&nbsp;
</td><td>
Command Shift F
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Find &amp; Replace in file</strong>
</td><td>
⌘ ⌥ F
</td><td>
Command Option F
</td></tr><tr><td>
<strong>Find &amp; Replace in project</strong>
</td><td>
⌘ ⌥ ⌤ F
</td><td>
Command Option Control F
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Edit all in scope, in current file</strong>
</td><td>
⌘ ⌤&nbsp; E
</td><td>
Command Control E
</td></tr><tr><td>
<strong>Refactor, Renaming in all files</strong>
</td><td>
⌘ ⌥ ⌤&nbsp; E
</td><td>
Command Option Control E
*customized
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Navigation filtering</strong>
</td><td>
⌘ ⇧ J
</td><td>
Command Shift J
</td></tr></tbody></table>



<h2 class="wp-block-heading" id="Tab-&amp;-Window-selection">Tab &amp; Window selection</h2>



<p>Selection between different tab and window selection shortcuts as follows.</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Open the current file in new tab</strong>
</td><td>
⌘ T
</td><td>
Command T
</td></tr><tr><td>
<strong>Next Tab</strong>
</td><td>
⌤&nbsp; ⇥
</td><td>
Command Tab
</td></tr><tr><td>
<strong>Previous Tab</strong>
</td><td>
⌤&nbsp; ⇧ ⇥&nbsp;
</td><td>
Command Shift Tab
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Selection between two Xcode window</strong>
</td><td>
⌘ ~
</td><td>
Command ~ [tilde sign]
</td></tr></tbody></table>



<h2 class="wp-block-heading" id="Simulator-Shortcuts">Simulator Shortcuts</h2>



<p>We not only have the Xcode Shortcuts only but we also some simulator shortcuts.  which definitely add more value on the iOS day to day Cheat Sheet. Let us have some simulator shortcuts.</p>



<p>Now we can say the Xcode and Simulator Shortcut Cheat Sheet</p>



<table class="table" class="wp-block-table is-style-stripes"><tbody><tr><td>
<strong>Rotate simulator</strong>
</td><td> ⌘ ←&nbsp; <br>⌘ →&nbsp; </td><td> Command left <br>Command right </td></tr><tr><td>
<strong>Home screen</strong>
</td><td>
⌘ ⇧ H
</td><td>
Command Shift H
</td></tr><tr><td>
<strong>Recent Apps</strong>
</td><td>
⌘ ⇧ H&nbsp;
</td><td> Command Shift H&nbsp; <br>Quickly press H two times without releasing <br>⌘ and ⇧ </td></tr><tr><td>
<strong>Toggling In Call status bar</strong>
</td><td>
⌘ Y
</td><td>
Command Y
</td></tr><tr><td>
<strong>Toggle keyboard visibility</strong>
</td><td>
⌘ ⇧ K
</td><td>
Command Shift K
</td></tr><tr><td>
<strong>Screen shot</strong>
</td><td>
⌘ S
</td><td>
Command S
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Toggle animation</strong>
</td><td>
⌘ T
</td><td>
Command T
</td></tr><tr><td></td><td></td><td></td></tr><tr><td>
<strong>Actual Size</strong>
</td><td>
⌘&nbsp; 1
</td><td> Command 1 </td></tr><tr><td>
<strong>Point accurate Size</strong>
</td><td>
⌘&nbsp; 2
</td><td> Command 2 </td></tr><tr><td>
<strong>Pixel accurate Size</strong>
</td><td>
⌘&nbsp; 3
</td><td> Command 3 </td></tr></tbody></table>



<p>Let us watch the simulator shortcuts on action.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Simulator Shortcuts" width="640" height="360" src="https://www.youtube.com/embed/dHnlN5HKA0Q?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Simulator Shortcuts</figcaption></figure>



<h2 class="wp-block-heading" id="Adding-shortcuts-on-Xcode">Adding shortcuts on Xcode</h2>



<p>Move to <code>Xcode -&gt; Preferences... -&gt; Key Bindings</code>. Here you can add or update the Xcode shortcuts. The <code>Customized</code> section have all the customize shortcuts that we previously defined. Also best not to have any <code>Conflicts</code>Shortcuts. On the next section we will watch to add a custom shortcut and man that&#8217;s an important one. It&#8217;s none other than the Renaming shortcut scoped on the whole project 😉.</p>



<h2 class="wp-block-heading" id="Adding-Refactor-Renaming-shortcuts">Adding Refactor Renaming shortcuts</h2>



<p>The <code>refactoring to rename</code> a property, is given a separated section on this blog post because of the importance it has on our daily use. Xcode took some time to revel the Swift refactoring. But still it is one of the most use feature. Currently we do not have a default shortcut for Renaming a property. So let us add that shortcut and watch it on action. Let us have a better understanding through a video.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts Adding Refactoring shortcut" width="640" height="360" src="https://www.youtube.com/embed/chNtlEn_OiQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Refactor Renaming shortcut adding and view in action</figcaption></figure>



<h2 class="wp-block-heading" id="Xcode-Shortcuts-Conflict-resolving">Xcode Shortcuts Conflict resolving</h2>



<p>Now as we start to add some shortcuts as by our preference, Xcode will start to notify us if we make some conflicting shortcuts. However those shortcuts may not only be conflicting with already defined Xcode shortcuts, but also with System shortcuts. </p>



<p>Anyway the solution is simple. We need to remove one of the conflicting shortcut. On Xcode press the <code>command ,</code> <code>⌘ ,</code> to open the Xcode preference. Go to <code>Key Bindings</code> . Then select the <code>Conflicts</code> section. Now you will have the conflicting shortcuts list. The <code>Red</code> marker are conflicting shortcuts with-ing Xcode.  And the <code>Yellow</code> are the conflicting shortcuts with the system.</p>



<p>For inter Xcode shortcut conflict just select the one that you want to remove. Tap/click on the <code>-</code> negative sign to remove that shortcut. Simple right.</p>



<p>On the other hand for conflicting shortcuts with system shortcut we need to remove those from <code>System Preference</code>. Open the <code>System Preference</code>, tap/click on the <code>Keyboard</code> and select the <code>Shortcuts</code> section. Now just deselect those which are conflict with Xcode. We need to remember that those system shortcuts now will not be active after we deselect those. So cut your coat according you needs. Let see the System level conflict resolving in action.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts System conflict resolving" width="640" height="360" src="https://www.youtube.com/embed/RQa0FBtaV3E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Conflict resolving among Xcode and System shortcuts</figcaption></figure>



<h2 class="wp-block-heading" id="How-to-use-this-blog-post">How to use this blog post</h2>



<p>There are couple of ways to use this blog post as your benefit. The very first and easy way is to bookmark this page, which I not gonna recommended. Because this blog post may not be something you need to visit on some timely manner. </p>



<p>There is another way, a better way. I can send you the related docs which includes a pdf and a Page Document and an epub formatted book. </p>



<p>Now you can use the pdf as reference by printing or keeping somewhere from where you can access more quickly.</p>



<p>Better way is to add the epub book on your <code>Books.app</code> application and use it as the reference for finding the Shortcuts of Xcode and Simulator. </p>



<p>The best way I believe, will also need your effort. You can pick the specific shortcut table and make it a pdf or an image and can keep it as your wallpaper on your working space. Once you become expert on that shortcut, then move to the next table of shortcuts and follow the same way until you become also an expert on that part also. Continue until you think you are good enough. On the mean time you can also add your preferred shortcuts on the way.</p>



<p>When I started to use Xcode and Simulator shortcuts, I didn&#8217;t have this resources. I believe it is a very good resource to have. Now you can have it. Use the Xcode Shortcuts resource as a  Cheat Sheet for iOS development to boost ur level. </p>



<h2 class="wp-block-heading" id="Give-me-my-free-Xcode-shortcut-resources">Give me my free Xcode shortcut resources</h2>



<p>I will need your email id for sending the resources. I can confirm I don&#8217;t like unnecessary emails on my mail box, so I confirm I won&#8217;t send anything unnecessary.</p>



<div class='mailmunch-forms-short-code mailmunch-forms-widget-809282' style='display: none !important;'></div>



<p>If you already filled the email, you can still have the resources again. Just fill the email and continue to confirm section. On the confirming section you will have the download link. Never mind to submit your email more than once to get those resources. Though you will get the resource on your mail once, after that you need to download it form the mail confirmation section.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Xcode Shortcuts  email Resources" width="640" height="360" src="https://www.youtube.com/embed/mbN5x16fLDI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption>Free resources includes Xcode Shortcuts as list on a page file, on an epub and on a pdf</figcaption></figure>



<p>Welcome to Xcode Shortcuts paradigm, the iOS dev Cheat Sheet.</p>



<h2 class="wp-block-heading">End talk</h2>



<p>The Xcode Shortcuts is one of the coolest Cheat Sheet we can have on our disposal. Let us deposit those Xcode Shortcuts more often so that it makes a boost on our iOS career, you know this is the Cheat Sheet. See you around.</p>



<h2 class="wp-block-heading" id="Reference">Reference</h2>



<ul class="wp-block-list"><li>Xcode &amp; Simulator shortcuts <a href="https://www.youtube.com/playlist?list=PL2oMRmw1TrdkjlmRvJM54aw53_TXNn_X1">playlist on youtube</a></li><li>More on <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://nshipster.com/xcode-key-bindings-and-gestures/" target="_blank">NSHipster</a> about some cool gesture use</li><li>Initial inspired from <a rel="noreferrer noopener" aria-label="swifteducation (opens in a new tab)" href="https://swifteducation.github.io/assets/pdfs/XcodeKeyboardShortcuts.pdf" target="_blank">swifteducation</a></li></ul>



<p></p>
<p>The post <a href="https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/">Xcode Shortcuts the iOS Cheat Sheet</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/xcode-shortcuts-cheat-sheet/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1323</post-id>	</item>
		<item>
		<title>Swift Enum Hub</title>
		<link>https://mobidevtalk.com/swift-enum-hub/</link>
					<comments>https://mobidevtalk.com/swift-enum-hub/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Sat, 13 Jul 2019 02:07:36 +0000</pubDate>
				<category><![CDATA[Hub]]></category>
		<category><![CDATA[enum]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1289</guid>

					<description><![CDATA[<p>Enum on Swift is a cool dude. In a single blog the coolness of Enum can...</p>
<p><a href="https://mobidevtalk.com/swift-enum-hub/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Enum Hub</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-enum-hub/">Swift Enum Hub</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Enum on Swift is a cool dude. In a single blog the coolness of Enum can not be expressed. As a result we have a total of four blog post including this one dedicated to enum on Swift. This blog post will act as a hub page for enum to ease the navigation in the realm on enum. We can consider this blog post as the index for Swift&#8217;s enum tutorial. Though the blog posts on this site are not written as typical tutorial containing the long setup and line by line of how to. This blog always consider you as a smart person who already knows the stuff. We are here to sharpen our crafts. Now let us shift our focus on enum again.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#At-a-glance">At a glance</a></li><li><a href="#Love-for-Enum">Love for Enum</a></li><li><a href="#Love-for-Enum,-continuing…">Love for Enum, continuing…</a></li><li><a href="#Tic-tac-toe">enum case study: Tic tac toe, through enum</a></li><li><a href="#mutating-enum-struct-on-Swift">mutating enum struct on Swift</a></li><li><a href="#End-talk">End talk</a></li></ul>



<h2 class="wp-block-heading" id="At-a-glance">At a glance</h2>



<p>Below is the related post on enum on this blog.</p>





<p>Let us review all of them in short one by one.</p>



<h2 class="wp-block-heading" id="Love-for-Enum"><a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-enum-basic-introduction/" target="_blank">Love for Enum</a></h2>



<p>On our very first blog over enum, <a rel="noreferrer noopener" aria-label="Love for Enum (opens in a new tab)" href="https://mobidevtalk.com/swift-enum-basic-introduction/" target="_blank">Love for Enum</a>, we have the basic introduction with enum. So topic like rawValue, hashValue, associated value were discussed there. More importantly we discussed about the use case for each of those bases concepts of enum. And finally we answered one of the most commonly asked question: Why we can&#8217;t use associated value with hashValue together on enum. Even if you posses the basic knowledge about enum on Swift, though I will request you to visit that blog post at least once. Because those topic/concepts may seems very trivial on an overwatch position they are not. They are the building block of enum.</p>



<h2 class="wp-block-heading" id="Love-for-Enum,-continuing…"><a rel="noreferrer noopener" aria-label="Love for Enum, continuing… (opens in a new tab)" href="https://mobidevtalk.com/swift-enum-advance/" target="_blank">Love for Enum, continuing…</a></h2>



<p>On our second blog post over enum, <a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-enum-advance/" target="_blank">Love for Enum, continuing…</a>, we moved on a bit more advanced topic. Such as generic usage on enum, Error definition through enum, why not to mutate enum, recursiveness of enum. Also the <code>allCases</code> and the frozenness of enum. This blog post moves us into a bit more advance level as we will start for a big jump on our next blog post on enum. A blog post about the case study on enum.</p>



<h2 class="wp-block-heading" id="Tic-tac-toe">enum case study: <a rel="noreferrer noopener" aria-label="Tic tac toe, through enum (opens in a new tab)" href="https://mobidevtalk.com/swift-enum-case-study-example/" target="_blank">Tic tac toe, through enum</a></h2>



<p>Here comes the big part. Now we will implement the learned knowledge from the previous two blog post. We will build a case study which suits the enum nearly perfectly. On the building of Tic tac toe through enum we will get an insight of enum usage on real life. We briefly explain the cause of choosing different features of enum. Here we will get the fun of using Swift switch in action. Also the different version of Swift enum init. On the <a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-enum-case-study-example/" target="_blank">Tic tac toe, through enum</a> blog post most of time we choose enum as our primary data container.</p>



<p>To develop this blog post we use the TDD approach. So when we have the source code, which is hosted publicly on GitHub, we will see a lot of test cases. On some future time we will cover the TDD.</p>



<h2 class="wp-block-heading" id="mutating-enum-struct-on-Swift"><a rel="noreferrer noopener" aria-label="mutating enum struct on Swift (opens in a new tab)" href="https://mobidevtalk.com/mutating-enum-struct-on-swift/" target="_blank">mutating enum struct on Swift</a></h2>



<p>This blog post is not directly connected to enum, rather it is more connect with the value type. Here on this blog post we will learn how we can mutate the value type. Even more is it ok do such <a rel="noreferrer noopener" aria-label="mutation for value type (opens in a new tab)" href="https://mobidevtalk.com/mutating-enum-struct-on-swift/" target="_blank">mutation for value type</a>. Whats the stand view of value type on this type of mutation.</p>



<h2 class="wp-block-heading" id="End-talk">End talk</h2>



<p>There are some topics those are not discussed on the enum blog post series. Topic such as Swift enum codable and Swift struct &amp; enum relation are not touched. May be on some future time we will.</p>



<p>The official <a rel="noreferrer noopener" aria-label="Swift doc (opens in a new tab)" href="https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html" target="_blank">Swift doc</a> largely covers the topics of enum on Swift. But to cover some real life implementation of enum we talked a lot on this blog. Proper usage of enum can drastically change our capability on Swift. So keep digging for more enum treasure. Take care.</p>
<p>The post <a href="https://mobidevtalk.com/swift-enum-hub/">Swift Enum Hub</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-enum-hub/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1289</post-id>	</item>
		<item>
		<title>Dependency Injection in Swift</title>
		<link>https://mobidevtalk.com/swift-dependency-injection-through-protocol/</link>
					<comments>https://mobidevtalk.com/swift-dependency-injection-through-protocol/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Sun, 07 Jul 2019 11:04:35 +0000</pubDate>
				<category><![CDATA[Pragmatic]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Dependency Inversion Principle]]></category>
		<category><![CDATA[protocol]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1245</guid>

					<description><![CDATA[<p>Dependency Injection may seems like a fancy term. But the term is very accurate to describe...</p>
<p><a href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Dependency Injection in Swift</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/">Dependency Injection in Swift</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Dependency Injection may seems like a fancy term. But the term is very accurate to describe its functionality. The reason we hold DI (Dependency Injection) as a fancy term is because we mix it up with the DIP (Dependency Inversion Principle). These two DI and DIP seems like almost same. But on reality they are miles apart. One is the principle and the other is the way of using that principle. Though both provide the same goal, decoupled code. Here on this blog post we will talk about Dependency Injection in Swift, the hows and why. After that definitely we will clear the confusion about DIP and DI. Later on we will build a case study where we will learn on achieving Dependency Injection in Swift through protocol. Finally we will talk about the benefits, drawback and best practices of Dependency Injection on Swift.</p>



<p>We are going with the protocol feast. Our last five blog post is all about protocol; what we can achieve through protocol on Swift. But on the <a rel="noreferrer noopener" aria-label="last blog (opens in a new tab)" href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" target="_blank">last blog</a> post we have a detail talk on Dependency Inversion Principle, DIP, on Swift. It is a good starting point if we need some solid ground to start from. The <a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-protocol-hub/" target="_blank">Swift Protocol Hub</a> contains all the related posts with protocol. Be sure to check that out.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#Intro">What is Dependency Injection</a></li><li><a href="#Fundamental-Difference">Fundamental Difference between Dependency Injection &amp; Dependency Inversion</a></li><li><a href="#Types">Types of Dependency Injection</a></li><li><a href="#Protocol-usage-on-Dependency-Injection">Protocol usage on Dependency Injection</a></li><li><a href="#Discussion-on-Dependency-Injection">Discussion on Dependency Injection</a></li><li><a href="#Benefit">Benefit</a></li><li><a href="#Drawback">Drawback</a></li><li><a href="#Tricks-and-tips">Tricks and tips</a></li></ul>



<h2 class="wp-block-heading" id="Intro">Dependency Injection</h2>



<p>First let us have some idea about Dependency Injection. Then we will move to Dependency Injection on Swift realm. To be honest Dependency Injection is a pretty simple concept. But the lack of knowledge makes it align to us. </p>



<p>We can think Dependency Injection as the process of suppling a property of an Instance outside of its scope. In other words, setting a property of a class/struct/enum from outside. Let see through an example.</p>



<pre class="wp-block-code"><code>struct SuperHero{
    var superPower: String?
}</code></pre>



<p>On the above <code>SuperHero</code> has a dependency on <code>superPower</code>. Now we will inject this dependency from outside scope of <code>SuperHero</code>, like following:</p>



<pre class="wp-block-code"><code>var hero = SuperHero()
hero.superPower = "N/A"</code></pre>



<p>As we can see we are injecting the property value outside of <code>SuperHero</code> scope. Now you must be frustrating saying, What!!! for this easy-peasy concept we are going through a blog post.</p>



<p>And you are not so wrong. It is definitely a very easy concept. But proper usage of Dependency Injection will make your code decoupled. Which ultimately makes life easier when changes arrive. So stay tunes. We have some talks to talk.</p>



<h2 class="wp-block-heading" id="Fundamental-Difference">Fundamental Difference between Dependency Injection &amp; Dependency Inversion</h2>



<p>Whenever we talk about Dependency Injection we often talk about Dependency Inversion, but this two are fundamentally two different concept.</p>



<p>Dependency Inversion is the alteration of <strong>Compile Time Dependency</strong> or <strong>Source Code Dependency</strong> against the <strong>Run Time Dependency</strong>. For more info we can always visit the <a rel="noreferrer noopener" aria-label="introductory blog post (opens in a new tab)" href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/" target="_blank">introductory blog post</a> about Dependency Inversion on Swift.</p>



<p>So basically Dependency Inversion is the way of achieving the following statement.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p><em>High level policies should not depend on low level details. They both should depend on abstraction.</em></p><cite>&#8211; Generic term</cite></blockquote>



<p>On Swift we use <a rel="noreferrer noopener" aria-label="protocol to achieve that abstraction (opens in a new tab)" href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" target="_blank">protocol to achieve that abstraction</a>. And thats where the confusion occurs among Dependency Inversion and Dependency Injection. Because, as we will learn shortly that, protocol is also used for achieving Dependency Injection on Swift.</p>



<p>Now Dependency Injection is like setting a property of class/enum/struct on its simplest term. But it is not like setting each and every property with Injection. There need to be some criteria about when to set those property from outside, we will talk about those on this blog post also. </p>



<p>So on a conclusion it should clear by now that, Dependency Inversion and Dependency Injection are always two different concept, they share the only two thing in common, the <code>Dependency</code> keyword and the use of protocol. Thats it.</p>



<h2 class="wp-block-heading" id="Types">Types of Dependency Injection</h2>



<p>There are basically three types of Dependency Injection.</p>



<ul class="wp-block-list"><li>Construction injection</li><li>Property injection</li><li>Method injection</li></ul>



<h3 class="wp-block-heading">Construction Injection</h3>



<p>When Injection of a property is done on <code>init</code> time.</p>



<pre class="wp-block-code"><code>SuperHero(superPower: "Speed")</code></pre>



<p>On the above example the property <code>superPower</code> of <code>SuperHero</code> is being initialized on the struct&#8217;s construction/init time. As we are injecting the value of the <code>superPower</code> property on construction time, that&#8217;s why it is called Construction injection. The term Construction is used as the similar term of initialization.</p>



<h3 class="wp-block-heading">Property Injection</h3>



<p>This type of injection is very common. When we assign a property value after the instance has been initialized. So it is like assigning <code>internal</code> property.</p>



<pre class="wp-block-code"><code>var hero = SuperHero()
hero.superPower = "N/A"</code></pre>



<h2 class="wp-block-heading">Method Injection</h2>



<p>On method injection we will inject the methods from outside. Now how thats possible? Remember the protocol? When we have the implementation of a protocol on our class/struct/enum, we can mock or fake that implementation through another implementation of that protocol.</p>



<p>We are more concern about this type of Injection on our current blog. Let us have some details talk over this topic.</p>



<h2 class="wp-block-heading" id="Protocol-usage-on-Dependency-Injection">Protocol usage on Dependency Injection</h2>



<p>Let us consider a superstitious situation. Say <a href="https://www.marvel.com/movies/iron-man" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">Iron Man</a> is preparing for some new job. For this regard he need to build up his resume. As he is very busy with his current job, he is thinking about some third party solution on building his resume. </p>



<p>Iron Man will provide the necessary infos for the resume and the third party will provide him the resume format. Now the info-gathering and the resume-format is now a dependency for Iron Man. </p>



<p>On the current section we will inject this two dependency through protocol.</p>



<h3 class="wp-block-heading">Building the capability model</h3>



<p>So first we will build some models by which the capability can be represented.</p>



<pre class="wp-block-code"><code>enum Scale: String{
    case noob = "Below basic"
    case basic = "Basic"
    case intermediate = "Skillful"
    case advance = "Very Skillful"
    case superAdvance = "Super Skillful"
}

enum Capability: CustomStringConvertible{
    case strength(Scale)
    case speed(Scale)
    case fly(Scale)
    
    var description: String{
        switch self {
        case .strength(let scale):
            return "\(scale.rawValue) level of Strength"
        case .speed(let scale):
            return "\(scale.rawValue) level of Speed"
        case .fly(let scale):
            return "\(scale.rawValue) level of Flying"
        }
    }
}</code></pre>



<p><code>Scale</code> is a model which represent the skill level. <code>Scale</code> has <code>String</code> as <a rel="noreferrer noopener" aria-label="rawValue (opens in a new tab)" href="https://mobidevtalk.com/swift-enum-basic-introduction/#rawValue" target="_blank">rawValue</a>. Then the <code>Capability</code> is a enum reprinting different capabilities. It takes <code>Scale</code> as <a href="https://mobidevtalk.com/swift-enum-basic-introduction/#associated-Values" target="_blank" rel="noreferrer noopener" aria-label="associated value (opens in a new tab)">associated value</a>.</p>



<h3 class="wp-block-heading">Defining Recruiter protocol </h3>



<p>Now if we define the info-submission and resume-formatting inside the IronMan model, then we will couple the code with two separated concern. Moreover we will not be able to update the resume-formatting if we want to choose another type of formatting. The best option here is to put those two in a protocol. So that we can have polymorphism later down the road.</p>



<pre class="wp-block-code"><code>protocol Recruiter{
    func submitInfo(name: String, superHeroName: String, capabilities: [Capability])
    func formattedInfo() -> String?
}</code></pre>



<p>The <code>submitInfo</code> stands for the info-submission and the <code>formattedInfo</code> stands for the resume-formatting.</p>



<h3 class="wp-block-heading">IronMan</h3>



<p>Now let us declare the man of the show, <code>IronMan</code>.</p>



<pre class="wp-block-code"><code>struct IronMan{
    private let name = "Tony Stark"
    private let aka = "Iron Man"
    private let capabilities: [Capability] = [.strength(.advance), .fly(.superAdvance)]
    
    let recruiter: Recruiter
    
    func submitResume(){
        recruiter.submitInfo(name: name, superHeroName: aka, capabilities: capabilities)
    }
    
    func resume() -> String{
        return recruiter.formattedInfo() ?? ""
    }
}</code></pre>



<p>The <code>submitResume()</code> method will submit the infos to the <code>Recruiter</code> and then the <code>resume()</code> will get the formatted resume from the <code>Recruiter</code>.</p>



<h3 class="wp-block-heading">Recruiter implementation</h3>



<p>Let us define a recruiting agent.</p>



<pre class="wp-block-code"><code>class Agent: Recruiter{
    private var resume: String?
    
    func submitInfo(name: String, superHeroName: String, capabilities: [Capability]) {
        let capabilityString = capabilities.reduce(into: "Capabilities includes:", { $0 += " " + $1.description + "," })
        resume = "Name: \(name)\nAKA: \(superHeroName)\n\(capabilityString)"
    }
    
    func formattedInfo() -> String? {
        return resume
    }
}</code></pre>



<p>So the <code>Agent</code> can build a simple resume and can return it back. Now if <code>IronMan</code> want to use his service then following code will do just that.</p>



<pre class="wp-block-code"><code>let ironManThroughAgent = IronMan(recruiter : Agent())
ironManThroughAgent.submitResume()
print(ironManThroughAgent.resume())</code></pre>



<p>Through the <code>Agent</code> the resume is like following.</p>



<pre class="wp-block-code"><code>Name: Tony Stark
AKA: Iron Man
Capabilities includes: Very Skillful level of Strength, Super Skillful level of Flying,</code></pre>



<p>Thats ok but not good enough to convince <code>IronMan</code>. So the <code>IronMan</code> search for another implementation of <code>Recruiter</code>. This time an <code>Agency</code>.</p>



<h3 class="wp-block-heading">Agency of Recruiter</h3>



<p> Let us define an <code>Agency</code> for <code>Recruiter</code>.</p>



<pre class="wp-block-code"><code>class Agency: Recruiter{
    private var resume: String?
    
    func submitInfo(name: String, superHeroName: String, capabilities: [Capability]) {
        let splittedName = name.split(separator: " ")

        let fullName = "First name: " + (splittedName.first ?? "") + (splittedName.count > 1 ? "\(splittedName.dropFirst(1).reduce(into: "\nLast name", { $0 += " " + $1 }))" : "")
        
        let capabilityString = capabilities.reduce(into: "Capabilities:", { $0 += "\n" + $1.description })
        
        resume = "Commonly Know as: \(superHeroName)\n\(fullName)\n\(capabilityString)"
    }
    
    func formattedInfo() -> String? {
        return resume
    }
}</code></pre>



<p>Now <code>IronMan</code> can have his resume as follows.</p>



<pre class="wp-block-code"><code>let ironManThroughAgency = IronMan(recruiter : Agency())
ironManThroughAgency.submitResume()
print(ironManThroughAgency.resume())</code></pre>



<p>Which results in the following way.</p>



<pre class="wp-block-code"><code>Commonly Know as: Iron Man
First name: Tony
Last name Stark
Capabilities:
Very Skillful level of Strength
Super Skillful level of Flying</code></pre>



<p>Now that is a ok version of resume for <code>IronMan</code>. Let us move to the discussion on hows and whys of Dependency Injection through this case study.</p>



<h2 class="wp-block-heading" id="Discussion-on-Dependency-Injection">Discussion on Dependency Injection</h2>



<p>On the above case study we had two dependencies, one is the info-submit and the other resume-formatting.  We inject those two dependencies through a <code>protocol</code>. First we use the <code>Agent</code> class. Then we inject another implementation of <code>Recruiter</code> when we use <code>Agency</code>. If we had not use the <code>protocol</code> then we would not be able to use two different implementation, in other words different dependencies.</p>



<p>This type of protocol based dependency injection comes really really handy when we want to mock some implementation on Test. The protocol based dependency injection is a must for TDD, Test Driven Development. On future we will have details talk on TDD, there we will cover the protocol based dependency injection for TDD.</p>



<h2 class="wp-block-heading" id="Benefit">Benefit</h2>



<p>What benefit does Dependency Injection gives us? Followings.</p>



<ul class="wp-block-list"><li>Decoupled code</li><li>Mocking on TDD</li><li>Multiple implementation or polymorphism</li><li>Elimination of Singletons</li></ul>



<h2 class="wp-block-heading" id="Drawback">Drawback</h2>



<p>If we overuse the Dependency Injection then it will result in a fuzzy code. Sometimes improper naming causes huge confusion when Dependency Injection is in place. </p>



<h2 class="wp-block-heading" id="Tricks-and-tips">Tricks and tips for Dependency Injection</h2>



<p>We are at the end of this blog post. Before finishing I want share some insights about Dependency Injection. As always the balance of doing or not doing is the most important thing. It is not always possible to predict the changes. So when you find a change area try to think if Dependency Injection can help you on that case. </p>



<p>One another thing, we can use the default value on construction time when we want the default value always but sometimes the injected value. Say we want to have the <code>Agency</code> as default <code>Recruiter</code> then we can write the <code>init</code> of <code>IronMan</code> as following.</p>



<pre class="wp-block-code"><code>init(recruiter: Recruiter = Agency()) {
        self.recruiter = recruiter
    }</code></pre>



<p>So now the <code>IronMan()</code> will init the instance with <code>Agency</code> as the <code>Recruiter</code>.</p>



<h2 class="wp-block-heading">End Talk</h2>



<p>Dependency Injection talk can not be finished without showing the implementation of Dependency Injection on test. On Swift <code>protocol</code> is a huge benefit when we can implement the Dependency Injection on the realm of TDD. Stay tunes we will load the TDD talk soon.</p>



<h2 class="wp-block-heading">Resources</h2>



<ul class="wp-block-list"><li>Source code for this blog post is hosted on <a href="https://github.com/mobidevtalk/protocol/blob/master/Protocol.playground/Pages/DependencyInjection.xcplaygroundpage/Contents.swift">GitHub</a></li><li><a href="http://ilya.puchka.me/dependency-injection-in-swift/">DI in details</a></li><li>DI <a rel="noreferrer noopener" aria-label="with Protocols (opens in a new tab)" href="https://mecid.github.io/2019/03/06/dependency-injection-in-swift-with-protocols/?utm_source=The.Swift.Dev.&amp;utm_campaign=b107886c85-theswiftdev-march-2019&amp;utm_medium=email&amp;utm_term=0_74ddbfe94a-b107886c85-4192691" target="_blank">with Protocols</a></li><li><a rel="noreferrer noopener" aria-label="Nuts and Bolts (opens in a new tab)" href="https://cocoacasts.com/nuts-and-bolts-of-dependency-injection-in-swift" target="_blank">Nuts and Bolts</a> of DI</li><li>DI <a rel="noreferrer noopener" href="https://lostechies.com/derickbailey/2011/09/22/dependency-injection-is-not-the-same-as-the-dependency-inversion-principle/" target="_blank">Is NOT The Same</a> As The DIP</li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.marvel.com/movies/iron-man" target="_blank">Iron Man of Marvel</a></li></ul>



<p></p>
<p>The post <a href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/">Dependency Injection in Swift</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-dependency-injection-through-protocol/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1245</post-id>	</item>
		<item>
		<title>Swift Dependency Inversion through Protocol</title>
		<link>https://mobidevtalk.com/swift-dependency-inversion-through-protocol/</link>
					<comments>https://mobidevtalk.com/swift-dependency-inversion-through-protocol/#comments</comments>
		
		<dc:creator><![CDATA[Rayhan]]></dc:creator>
		<pubDate>Tue, 28 May 2019 21:00:44 +0000</pubDate>
				<category><![CDATA[Pragmatic]]></category>
		<category><![CDATA[Dependency Inversion]]></category>
		<category><![CDATA[Dependency Inversion Principle]]></category>
		<category><![CDATA[DIP]]></category>
		<category><![CDATA[protocol]]></category>
		<guid isPermaLink="false">https://mobidevtalk.com/?p=1116</guid>

					<description><![CDATA[<p>Here we are, finally we have the Dependency Inversion on Swift through Protocol talk. On our...</p>
<p><a href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/" class="more-link btn btn-primary">more...<span class="screen-reader-text">Swift Dependency Inversion through Protocol</span></a></p>
<p>The post <a href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/">Swift Dependency Inversion through Protocol</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Here we are, finally we have the Dependency Inversion on Swift through Protocol talk. On our last blog post of <a rel="noreferrer noopener" aria-label="Introduction of Dependency Inversion on Swift (opens in a new tab)" href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/" target="_blank">Introduction of Dependency Inversion on Swift</a> we were introduced with the two type of dependencies, run time dependency and source code or compile time dependency. On this blog post we will talk about how to achieve Dependency Inversion on Swift by using protocol. So that we can alter the dependency direction between compile and run time. We will also talk about on when to smell for dependency inversion and what are the best doings for inverting the dependencies.</p>



<p>The <a rel="noreferrer noopener" href="https://mobidevtalk.com/swift-protocol-hub/" target="_blank">Swift Protocol Hub</a> contains all the related posts with protocol. Be sure to check that out.</p>



<h2 class="wp-block-heading">Background</h2>



<ul class="wp-block-list"><li><a href="#Dependency-Inversion">What is Dependency Inversion</a></li><li><a href="#Why-we-need-the-Dependency-Inversion">Why we need the Dependency Inversion</a></li><li><a href="#Generic-process-for-achieving-Dependency-Inversion-through-protocol">Generic process for achieving Dependency Inversion through protocol</a> </li><li><a href="#Explanation-of-DIP-on-UITableViewDataSource">Explanation of DIP on </a><code><a href="#Explanation-of-DIP-on-UITableViewDataSource">UITableViewDataSource</a></code></li><li><a href="#A-case-study-on-Dependency-Inversion-Principle">A case study on Dependency Inversion principle</a></li><li><a href="#How-and-where-to-smell-for-implementing-DIP-On-Swift">How and where to smell for implementing DIP On Swift</a></li><li><a href="#Best-practices-on-Swift-for-DIP-through-protocol">Best practices on Swift for DIP through protocol</a></li><li><a href="#Resources">Resources</a></li></ul>



<h2 class="wp-block-heading" id="Dependency-Inversion">Dependency Inversion</h2>



<p>As we said on our last blog post that, the process of reversing the run time dependency with respect to the compile time dependency is called the Dependency Inversion.</p>



<p>Say we have two different module, <code>A</code> and <code>B</code>. <code>A</code> is dependent on <code>f()</code> which is defined in <code>B</code>. So for <code>A</code>, <code>A</code> is dependent on <code>B</code> both on run and compile time. <br>Now consider, if we introduce a protocol <code>p</code> which will hold the declaration of <code>f()</code>. And <code>B</code> implements that protocol thus defining the <code>f()</code>. On this time if <code>A</code> uses the <code>p.f()</code>, then the dependency is inverted and Dependency inversion is achieve. Because on compile time <code>A</code> is dependent on <code>P</code>, which is reverse of the run time dependency to <code>B</code>.</p>



<p>In case of a confusion we can alway visit our last blog post and review the <a href="https://mobidevtalk.com/introduction-of-dependency-inversion-on-swift/#Build-Link-Run" target="_blank" rel="noreferrer noopener" aria-label="explanation of run and compile time decencies (opens in a new tab)">explanation of run and compile time decencies</a>.</p>



<h2 class="wp-block-heading" id="Why-we-need-the-Dependency-Inversion">Why we need the Dependency Inversion</h2>



<p>The basic question has not been answered yet. Why do we need dependency Inversion? </p>



<p>The reason is to achieve loosely coupled code base. And we understand that, the loosely coupled code is far more flexible to requirement changes.</p>



<p>That leads to another question. How Dependency Inversion makes the flexible code? </p>



<p>By implementing dependency inversion principle we create an abstraction between two interacting module. Both of those two interacting module depends on the abstraction. In Swift we achieve  the abstraction through protocol. <br>Now the individual module can evolved separately based on the requirement changes without affecting the counterpart module. The reason is both module only knows the protocol not the other part. So one module is unaware of the adding, updating or even removing of other module. Thats how Dependency inversion makes the code more flexible with requirement change.</p>



<h2 class="wp-block-heading" id="Generic-process-for-achieving-Dependency-Inversion-through-protocol">Generic process for achieving Dependency Inversion through protocol</h2>



<p>Ok so now we know dependency inversion is a necessity for agile code. We already have a clue on how to achieve that dependency inversion through abstraction. More specifically on Swift, protocol is the key for dependency inversion. </p>



<p>On general we hide the implementation details through abstraction to gain loosely coupled code.  There is a common term used regularly to describe the dependency inversion principle:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>High level policies should not depend on low level details. They both should depend on abstraction.</p><cite>-Generic term</cite></blockquote>



<p>We need an explanation for the above statement. Usually <strong>high level policies</strong> means the logic part of a module and the <strong>low level details</strong> means the implementation part of that module. Now an example will clarify the issue.</p>



<p>We will pick one from the UIKit itself. Perhaps we use this specific <strong>dependency inversion</strong> most often without knowing its existence. Well, it is none other than the <code>UITableViewDataSource</code>. Amazing right? On reality every delegation is a case of DIP. We use the <strong>Dependency Inversion principle</strong> on Swift whenever we are initiating and implementing the protocol, may be without understanding. That blur part is the target of this blog post. We want to focus on the usage the <strong>Dependency Inversion Principle</strong> on Swift through protocol on a concern mind on this blog post. Hopefully after this blog post we will be able to use the protocol effectively to achieving Dependency Inversion Principle to the proper way.</p>



<h2 class="wp-block-heading" id="Explanation-of-DIP-on-UITableViewDataSource">Explanation of DIP on <code>UITableViewDataSource</code></h2>



<p>Now let us concentrate our discussion on the hows and whys of <code>UITableViewDataSource</code>. So what happens by conforming the <code>UITableViewDataSource</code> delegate. We have to implement two methods <code><code>tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int</code></code> and <code><code>tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell</code></code>. Both of this two method are actually asking us about the higher level logic like what will be the total number of rows and how the cell will be defined.</p>



<p>See how the Dependency inversion principle is operational on <code>UITableView</code>. All the implementation details, like rendering or like gesture handling, are kept hidden from the higher level logic. Based on the higher level logic, that we defined on those two methods, the lower level implementation will be laid out.  But interestingly they both are dependent on the abstraction or on the protocol. In other words, both the higher level logic and the lower level details are dependent on the abstraction/ protocol. Let us have a diagram of this specific dependency implementation.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="640" height="433" src="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?resize=640%2C433&#038;ssl=1" alt="Dependency Inversion Principle through protocol, UITableViewDataSource, on Swift" class="wp-image-1180 img-fluid" srcset="https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?w=723&amp;ssl=1 723w, https://i0.wp.com/mobidevtalk.com/wp-content/uploads/2019/05/DipOnUITableDataSource.png?resize=300%2C203&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption>Dependency Inversion Principle through UITableViewDataSource</figcaption></figure></div>



<p>As we can see the the Higher level logic[Code base] has a run time dependency on <code>UIKit</code> but it has no compile time dependency on <code>UIKit</code>. Rather the Higher level logic[Code base] has a compile time dependency over a protocol, <code>UITableViewDataSource</code>.</p>



<p>Now let us have a small talk over the benefit of this type on dependency inversion principle. Let say the latest release of the iOS has some different rendering mechanism than the previous one. Guess what? We do not need to think about it. Even the C++ lib that is doing the render may be thrown away by apple, but we are still good. 🤓</p>



<p>Amazing right.</p>



<p>Now let us build one case study for ourself to implement the Dependency Inversion principle from scratch. 💪</p>



<h2 class="wp-block-heading" id="A-case-study-on-Dependency-Inversion-Principle">A case study on Dependency Inversion Principle</h2>



<p>Let say we are building a profiling module for a game. For the profiling module let us have some use cases:</p>



<ul class="wp-block-list"><li>We need to profile the different characters with their basic infos and also their capabilities</li><li>Now talk about their capabilities, they will definitely differ among those characters</li><li>Also the basic infos will differ</li><li>Moreover there is the possibility of adding more character on the game on some future time</li></ul>



<p>We want to build our profiling module so that it can handles all the above scenario.</p>



<p>Now let us consider, which part is dependent on which part. Say we will display the Characters profile on <code>ProfileScene</code>. So <code>ProfileScene</code> should have the instances of those characters. But if we do that then <code>ProfileScene</code> has the run and compile time dependency on those Characters. A better approach will be to break that dependency by introducing an abstraction, protocol. Say we named that protocol <code>Profilable</code>. So now if we store the <code>Profilable</code> instances on our <code>ProfileScene</code> rather than the concrete type, then the compile time dependency of <code>ProfileScene</code> is inverted than its run time dependency. Thus giving us the benefit of updating the concrete type or even the <code>ProfileScene</code>. Moreover we can add other character once they confirm the <code>Profilable</code> protocol. Let us have some code now.</p>



<h3 class="wp-block-heading">Profilable model</h3>



<p>Let us define the <code>Profilable</code> protocol.</p>



<pre class="wp-block-code"><code>struct BasicInfo{
    enum Gender: String {
        case Male
        case Female
    }
    
    let fullName: String
    let gender: Gender
}

enum Species{
    case God
    case Mutated
    case Human
}

protocol Profilable{
    var infos: BasicInfo { get }
    var Species: Species { get }
    
    func remarks() -> String
}</code></pre>



<p>The <code>BasicInfo</code> and the <code>Species</code> are the helper data structure. By the way if we need any help regarding enum we cal always visit the <a rel="noreferrer noopener" aria-label="enum talk (opens in a new tab)" href="https://mobidevtalk.com/love-for-enum/" target="_blank">enum talk</a> for more details.</p>



<h3 class="wp-block-heading">DC comics character</h3>



<p>Let add some <a rel="noreferrer noopener" aria-label="DC comic character (opens in a new tab)" href="https://www.dccomics.com/characters" target="_blank">DC comic character</a>. These characters are already been added on our <a rel="noreferrer noopener" aria-label="inheritance talk (opens in a new tab)" href="https://mobidevtalk.com/inheritance-initiator-of-coupling/" target="_blank">inheritance talk</a>. For this talk will extend those types to confirm the <code>Profilable</code> protocol.</p>



<pre class="wp-block-code"><code>extension Batman: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "\(originalName) aka: \(name)", gender: .Male)
    }
    
    var Species: Species {
        return .Human
    }
    
    func remarks() -> String {
        return profile ?? speciality()
    }
}

extension WonderWoman: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "\(originalName) aka: \(name)", gender: .Female)
    }
    
    var Species: Species {
        return .God
    }
    
    func remarks() -> String {
        return "Zeus daughter. \(profile ?? speciality())"
    }
}</code></pre>



<p>Pretty simple right? Now <code>Batman</code> and <code>WonderWoman</code> confirming the <code>Profilable</code> protocol and defining the required var and method.</p>



<h3 class="wp-block-heading">Marvel Character</h3>



<p>Now it is time to add some more characters but this time from <a rel="noreferrer noopener" aria-label="Marvel (opens in a new tab)" href="https://www.marvel.com/explore" target="_blank">Marvel</a>. Again we already added those Avengers on our <a rel="noreferrer noopener" aria-label="Protocol, Swift way of thinking (opens in a new tab)" href="https://mobidevtalk.com/protocol-swift-practical-use-case/" target="_blank">Protocol, Swift way of thinking</a> talk. Let us extend those Avengers and confirm to <code>Profilable</code> protocol.</p>



<pre class="wp-block-code"><code>extension IronMan: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "Tony Stark aka: \(name)", gender: .Male)
    }
    
    var Species: Species {
        return .Human
    }
    
    func remarks() -> String {
        return "Founding member of Avengers. \(speciality)"
    }
}

extension CaptainAmerica: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "Steve Rogers aka: \(name)", gender: .Male)
    }
    
    var Species: Species {
        return .Mutated
    }
    
    func remarks() -> String {
        return "True born leader. \(speciality)"
    }
}

extension Hulk: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "Bruce Banner aka: \(name)", gender: .Male)
    }
    
    var Species: Species {
        return .Mutated
    }
    
    func remarks() -> String {
        return speciality
    }
}

extension Thor: Profilable{
    var infos: BasicInfo {
        return BasicInfo(fullName: "Thor Odinson aka: \(name)", gender: .Male)
    }
    
    var Species: Species {
        return .God
    }
    
    func remarks() -> String {
        return speciality
    }
}</code></pre>



<p>Again nothing fancy. Providing the implementation of <code>Profilable</code>. Now let us add up those characters to make the final <code>ProfileScene</code>.</p>



<h3 class="wp-block-heading">ProfileScene</h3>



<p>On our final code section we will have two separated array of <code>Profilable</code>, one for the JusticeLeague and another for the Avengers. And finally we will return a <code>String</code> containing all those character with some minor formation.</p>



<pre class="wp-block-code"><code>struct ProfileScene{
    let justiceLeague: [Profilable] = [Batman(), WonderWoman()]
    let avengers: [Profilable] = [IronMan(), CaptainAmerica(), Hulk(), Thor()]
    
    func profileListing() -> String{
        let justiceLeagueProfile =  justiceLeague.reduce(into: "Justice League:\n") { (initial, profilable) in
            initial += "\nFull name: \(profilable.infos.fullName) \nGender: \(profilable.infos.gender) \nRemarks: \(profilable.remarks())\n"
        }
        
        let avengersProfile =  avengers.reduce(into: "Avengers:\n") { (initial, profilable) in
            initial += "\nFull name: \(profilable.infos.fullName) \nGender: \(profilable.infos.gender) \nRemarks: \(profilable.remarks())\n"
        }
        
        return justiceLeagueProfile + "\n\n" + avengersProfile
    }
}</code></pre>



<p>Now when we run the <code>profileListing()</code> function, <code>print(ProfileScene().profileListing())</code>, we will get an easy locking profiling of all the characters. Oh for the Higher Order Function, HOF, we can look for the <a rel="noreferrer noopener" aria-label="HOF talk (opens in a new tab)" href="https://mobidevtalk.com/drilling-hof-higher-order-function-on-swift/" target="_blank">HOF talk</a>.  Let us take some insights from the above case study.</p>



<h3 class="wp-block-heading">Insights of the code study</h3>



<p>On the above case study we saw how and when to implement the DIP on Swift through Protocol. Here the different characters are the higher level logic. And the <code>profileListing</code> part being the lower level details. These two higher lever logic and lower level details depend on the abstraction. As a result we were able to add more character later down the road. These abstraction gives us the opportunity to develop two part separately. </p>



<h2 class="wp-block-heading" id="How-and-where-to-smell-for-implementing-DIP-On-Swift">How and where to smell for implementing DIP On Swift</h2>



<ul class="wp-block-list"><li>When there is interaction between two separated module. Like Business logic and View.</li><li>The simple code update takes a longer time because of the tightly coupled code.</li><li>A simple change request will impact a lot of code base.</li><li>Two module are integrated with each other in such a way that they cross each other boundary.</li><li>When It is known that one module will have the future changes, then it will be a good idea to access that module through DIP from the initial stage.</li></ul>



<p>But the above statement are nothing but vapor unless we know cons of DIP. So Let us jump on the best practices.</p>



<h2 class="wp-block-heading" id="Best-practices-on-Swift-for-DIP-through-protocol">Best practices on Swift for DIP through protocol</h2>



<ul class="wp-block-list"><li>The very first and perhaps the most important suggestion is to know, if the Dependency Inversion is a YAGNI or not? YAGNI stands for <code>you ain't gonna need it</code>. Overuse of Dependency Inversion will populate the code base with unnecessary abstraction, which will definitely reduce the readability of the code.</li><li>Start with a concrete type rather than a <code>Protocol</code> when you are uncertain about the future change request.</li><li>Initiate the Dependency Inversion through <code>Protocol</code> when you can see or certainly predict the area of change request. </li><li>The default mode should be YAGNI.</li><li>When working with View interaction it is always helpful to work with Dependency Inversion, because View get modified so ofter.</li><li>When working with Business logic, not tiny business logic, it can also be helpful to use the Dependency Inversion. But again remember the YAGNI.</li><li>Any inclusion of third party lib can be introduce to the code through Dependency Inversion, the reason is that third party lib can be thrown away and also we can mock that third party lib on testing time.</li></ul>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Again there is no Silver bullet. The best we can do, is to educate ourself on the different solutions that are available for us on our specific problem. We need to knows the pros and cons for each of them. Dependency Inversion Principle also fall on this category. We have to balance the YAGNI and DIP. I believe this blog post will give you the solid ground to perambulate further more on this topic.</p>



<p>One other topic regularly comes up with Dependency Inversion Principle is Dependency Injection. Oh boy there are some real confusion among them. We just published a <a href="https://mobidevtalk.com/swift-dependency-injection-through-protocol/">blog post on Dependency Injection</a>. Let us have a look.</p>



<p>See you around.</p>



<h2 class="wp-block-heading" id="Resources">Resources</h2>



<ul class="wp-block-list"><li>Swift Dependency Inversion through Protocol <a href="https://github.com/mobidevtalk/protocol/blob/master/Protocol.playground/Pages/DIPthroughProtocol.xcplaygroundpage/Contents.swift">source code</a></li><li><a rel="noreferrer noopener" href="https://cleancoders.com/episode/clean-code-episode-13/show" target="_blank">DIP by Uncle Bob</a></li><li><a rel="noopener noreferrer" href="https://swift.org/compiler-stdlib/#standard-library-design" target="_blank">Swift compiler and standard library design</a></li><li>The sequence is drawn on&nbsp;<a href="https://sequencediagram.org/">sequencediagram</a></li></ul>
<p>The post <a href="https://mobidevtalk.com/swift-dependency-inversion-through-protocol/">Swift Dependency Inversion through Protocol</a> appeared first on <a href="https://mobidevtalk.com">mobidevtalk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mobidevtalk.com/swift-dependency-inversion-through-protocol/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1116</post-id>	</item>
	</channel>
</rss>
