<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thiago Centurion on Medium]]></title>
        <description><![CDATA[Stories by Thiago Centurion on Medium]]></description>
        <link>https://medium.com/@thiagorodriguescenturion?source=rss-58faee355db7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZEilgU0E7kF3MSKTE6kN6Q.png</url>
            <title>Stories by Thiago Centurion on Medium</title>
            <link>https://medium.com/@thiagorodriguescenturion?source=rss-58faee355db7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:02:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thiagorodriguescenturion/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I use PreferenceKey and CoordinateSpace in SwiftUI]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/how-i-use-preferencekey-and-coordinatespace-in-swiftui-772d32f5cc6b?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/772d32f5cc6b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 13:32:23 GMT</pubDate>
            <atom:updated>2025-04-15T13:32:23.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*KXVDkSI72RqmutluX_RLCA.png" /></figure><p>In modern iOS development with SwiftUI, building complex UI often requires solutions beyond the basic view modifiers. Two powerful yet underutilized tools are PreferenceKey and CoordinateSpace. Together, they solve problems that would otherwise require complex workarounds or third-party libraries.</p><p>This article explores some practical use cases that demonstrate how these mechanisms can significantly improve your SwiftUI development experience.</p><h3>PreferenceKey</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*IUgnOea_h9vd3EbZriHOcA.png" /><figcaption><a href="https://developer.apple.com/documentation/swiftui/preferencekey">https://developer.apple.com/documentation/swiftui/preferencekey</a></figcaption></figure><p>PreferenceKey allows child views to pass data upward through the view hierarchy. Think of it as a communication channel that works in the opposite direction of the normal data flow. It&#39;s especially useful when a child needs to report:</p><ul><li>its <strong>frame</strong> or <strong>position</strong></li><li>its <strong>current state</strong> or interaction</li><li>or any other data to <strong>react to from a parent view</strong></li></ul><p>A PreferenceKey is a protocol you conform to:</p><pre>protocol PreferenceKey {<br>    associatedtype Value<br>    static var defaultValue: Value { get }<br>    static func reduce(value: inout Value, nextValue: () -&gt; Value)<br>}</pre><ul><li>defaultValue: The initial value when no preference is set</li><li>reduce: A method that combines values when multiple children set the same preference.</li></ul><h4>preference(key:value:)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-_n816DsB52szieALe9klA.png" /><figcaption><a href="https://developer.apple.com/documentation/swiftui/view/preference(key:value:)">https://developer.apple.com/documentation/swiftui/view/preference(key:value:)</a></figcaption></figure><p>preference(key:value:) is how a <strong>child view sets</strong> a value using a PreferenceKey as the key. Internally, SwiftUI will bubble it up to a parent that is listening using a specific method.</p><pre>Color.clear<br>  .preference(key: MyPreferenceKey.self, value: someValue)</pre><p>It&#39;s usual to set this value on these alternatives:</p><pre>// 1 - background<br>Text(&quot;Some text&quot;)<br>    .background(<br>        Color.clear<br>            .preference(key: MyPreferenceKey.self, value: someValue)<br>    )<br><br>// 2 - overlay<br>Text(&quot;Some text&quot;)<br>    .overlay(<br>        Color.clear<br>            .preference(key: MyPreferenceKey.self, value: someValue)<br>    )<br><br>// 3 - ZStack<br>ZStack {<br>    Text(&quot;Some text&quot;)<br>    Color.clear<br>        .preference(key: MyPreferenceKey.self, value: someValue)<br>}</pre><p>Using Color.clear as way for a non-visible layer, but it&#39;s not a constraint. It&#39;s often to be used with GeometryReader:</p><pre>GeometryReader { geo in<br>    Color.clear<br>        .preference(key: MyPreferenceKey.self, value: geo.size) // or whatever is needed<br>}</pre><h4>onPreferenceChange(_:perform:)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VtydRLExDU3kM1t1tkLYSQ.png" /><figcaption><a href="https://developer.apple.com/documentation/swiftui/view/onpreferencechange(_:perform:)">https://developer.apple.com/documentation/swiftui/view/onpreferencechange(_:perform:)</a></figcaption></figure><p>onPreferenceChange(_:perform:) is how a <strong>parent view</strong> <strong>observes</strong> the preference set by its descendants.</p><pre>.onPreferenceChange(MyPreferenceKey.self) { value in<br>    // React to the value set by a child<br>}</pre><p>These two work <strong>in tandem</strong>. This two-way collaboration is at the heart of all cases we’ll explore.</p><p>Let&#39;s start with a practical example where PreferenceKey works perfectly:</p><p>Imagine you&#39;re building a dynamic card and you need to make layout decisions based on the intrinsic size of child content, like showing a &quot;Read more&quot; button in case the height content is bigger than 50pt:</p><h4>Step 1: Create a SizePreferenceKey</h4><pre>struct SizePreferenceKey: PreferenceKey {<br>    static var defaultValue: CGSize = .zero<br><br>    static func reduce(value: inout CGSize, nextValue: () -&gt; CGSize) {<br>        value = nextValue()<br>    }<br>}</pre><h4>Step 2: Parent view uses the size preference</h4><pre>struct DynamicCardView: View {<br>    @State private var contentSize: CGSize = .zero<br>    @State private var showFullContent = false<br>    <br>    var body: some View {<br>        VStack {<br>            // Parent view that adapts based on child size<br>            VStack {<br>                Text(&quot;Dynamic Card&quot;)<br>                    .font(.headline)<br>                <br>                // Child content whose size we want to measure<br>                VStack {<br>                    Text(&quot;This is some content that might be quite long and we want to adapt our container based on its natural size.&quot;)<br>                        .lineLimit(showFullContent ? nil : 2)<br>                    <br>                    if !showFullContent &amp;&amp; contentSize.height &gt; 50 {<br>                        Button(&quot;Read more&quot;) {<br>                            withAnimation {<br>                                showFullContent = true<br>                            }<br>                        }<br>                        .padding(.top, 4)<br>                    }<br>                }<br>                .padding()<br>                // 1 - here we set the size<br>                .background(<br>                    GeometryReader { geo in<br>                        Color.clear<br>                            .preference(<br>                                key: SizePreferenceKey.self, <br>                                value: geo.size<br>                            )<br>                    }<br>                )<br>                // 2 - here we get the size<br>                .onPreferenceChange(SizePreferenceKey.self) { size in<br>                    contentSize = size<br>                }<br>            }<br>            .frame(width: 300)<br>            .background(<br>                RoundedRectangle(cornerRadius: 12)<br>                    .fill(Color.white)<br>                    .shadow(radius: 4)<br>            )<br>            .padding()<br>            <br>            // Debug info to show the measured size<br>            Text(&quot;Content height: \(Int(contentSize.height))&quot;)<br>                .font(.caption)<br>        }<br>    }<br>}</pre><p>What did we achieve?</p><ul><li>We create a SizePreferenceKey to store and communicate size information up the view hierarchy.</li><li>We use GeometryReader to capture the size of any view it&#39;s applied to.</li><li>In our DynamicCardView, we apply this to a child view and listen for size changes.</li><li>When the size changes, we update our @State variable and use that information to make layout decisions (showing a &quot;Read more&quot; button if the content exceeds a certain height).</li></ul><p>This pattern is particularly useful for cases like we want to implement custom drop-down menus where the container needs to know the size of the dropdown content, or create expanding/collapsing views that aniamte smoothly between states. Another case is when we want to dynamically change the navigation toolbar based on the position of a content into a ScrollView.</p><h4>Could we improve this logic?</h4><p>Yes, we could — simply encapsulating that into a generic ViewModifier providing a simple closure (or bindable variable if preferred).</p><pre>struct SizeModifier: ViewModifier {<br>    let size: (CGSize) -&gt; Void<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .background(<br>                GeometryReader { geo in<br>                    Color.clear<br>                        .preference(key: SizePreferenceKey.self, value: geo.size)<br>                }<br>            )<br>            .onPreferenceChange(SizePreferenceKey.self) { size in<br>                self.size(size)<br>            }<br>    }<br>}<br><br>extension View {<br>    func onSizeChange(closure: @escaping (CGSize) -&gt; Void) {<br>        viewModifier(SizeModifier(size: closure))<br>    }<br>}</pre><p>Then, in DynamicCardView, just change it to:</p><pre>struct DynamicCardView: View {<br>    @State private var contentSize: CGSize = .zero<br>    @State private var showFullContent = false<br>    <br>    var body: some View {<br>        VStack {<br>            VStack {<br>                Text(&quot;Dynamic Card&quot;)<br>                    .font(.headline)<br>                <br>                VStack(alignment: .leading) {<br><br>                    ...<br><br>                }<br>                // Change `preference(key:value:)` and `onPreferenceChange(_:perform:)` by ` onSizeChange(closure:)`<br>                .onSizeChange { size in<br>                    contentSize = size<br>                }<br>            }<br><br>            ...<br> <br>        }<br>    }<br>}</pre><h4>ScrollView</h4><p>Let&#39;s say we want to track the scroll offset of a ScrollView for a toolbar visibility.</p><p>Our intention:</p><ul><li>Place a GeometryReader at the top of the scroll content.</li><li>Use preference(key:value:) to report its position.</li><li>Update toolbar visibility based on scroll direction.</li></ul><pre>NavigationStack<br> └── ScrollView<br>      └── GeometryReader (← Measures position)<br>           └── List of items</pre><p>Let&#39;s try by the same way, but using CGRect now in order to get the Y position of it (i.e. frame.minY):</p><pre>// 1 - Create the PreferenceKey<br>struct FramePreferenceKey: PreferenceKey {<br>    static var defaultValue: CGRect = .zero<br><br>    static func reduce(value: inout CGRect, nextValue: () -&gt; CGRect) {<br>        value = nextValue()<br>    }<br>}<br><br>// 2 - Create the ViewModifier<br>struct FrameModifier: ViewModifier {<br>    let frame: (CGRect) -&gt; Void<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .background(<br>                GeometryReader { geo in<br>                    Color.clear<br>                        .preference(key: FramePreferenceKey.self, value: geo.frame(in: .global))<br>                }<br>            )<br>            .onPreferenceChange(FramePreferenceKey.self) { frame in<br>                self.frame(frame)<br>            }<br>    }<br>}<br><br>extension View {<br>    func onFrameChange(closure: @escaping (CGRect) -&gt; Void) {<br>        viewModifier(FrameModifier(size: closure))<br>    }<br>}<br><br>// 3 - Usage<br>struct DynamicToolbarView: View {<br><br>    ...<br><br>    @State var offset: CGFloat = 0<br><br>    ...<br><br>    var body: some View {<br>        NavigationStack {<br>            ScrollView {<br>                LazyVStack {<br>                    ForEach(0...10, id: \.self) { index in<br>                        Text(&quot;Row \(index)&quot;)<br>                            .frame(height: 50)<br>                        Divider()<br>                    }<br>                }<br>                .onFrameChange { frame in<br>                    offset = frame.minY<br>                }<br>            }<br>        }<br>        .onChange(of: offset) { offset in<br>            if offset &lt; 0 {<br>                // did scroll to down<br>            } else {<br>                // did return to the top<br>            }<br>        }<br>    }<br>}</pre><p>Seems good, right?</p><p>This approach seems like it works at first, but then:</p><ul><li>On devices with dynamic safe areas (e.g., iPhones with notches), the value fluctuates unexpectedly.</li><li>Inside modals or when embedded in tab views, it returns wildly inconsistent values.</li><li>It becomes fragile and unreliable when you reuse the view.</li></ul><p>You might see values like -146.0, -44.0, or even +0.0, depending on where your view is placed — which is not a trustworthy measurement of &quot;how far have I scrolled?&quot;.</p><h4>Why it fails?</h4><p>In FrameModifier note that we had to provide a parameter to geo.frame(in:) where it&#39;s measuring using .global :</p><pre>.background(<br>    GeometryReader { geo in<br>        Color.clear<br>            .preference(<br>                key: FramePreferenceKey.self, <br>                value: geo.frame(in: .global) // here we measure in .global<br>            )<br>    }<br>)</pre><p>.global references the <strong>entire screen</strong>. So if your view is embedded deep in a navigation stack, or there&#39;s a toolbar, or padding from a parent, those all affect the reported value. Your scroll tracking breaks because the geometry you&#39;re observing isn&#39;t anchored to your <strong>scroll view</strong>, but to the <strong>screen</strong> — which can vary.</p><pre>Device Screen (global)<br>  └── SafeArea<br>       └── NavigationStack<br>            └── ScrollView<br>                 └── GeometryReader</pre><p>If you&#39;re measuring in .global, you&#39;re measuring from <strong>the root</strong> of the tree, being affected by safe areas, tab bars, modal padding, etc.</p><p>Instead of this:</p><pre>geo.frame(in: .global)</pre><p>Do this:</p><pre>geo.frame(in: .named(&quot;scroll&quot;))</pre><p>and attach .coordinateSpace(name: &quot;scroll&quot;) to your ScrollView as well as providing the CoordinateSpace name into FrameModifier.</p><pre>struct FrameModifier: ViewModifier {<br>    let coordinateSpace: CoordinateSpace<br>    let frame: (CGRect) -&gt; Void<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .background(<br>                GeometryReader { geo in<br>                    Color.clear<br>                        .preference(key: FramePreferenceKey.self, value: geo.frame(in: coordinateSpace))<br>                }<br>            )<br>            .onPreferenceChange(FramePreferenceKey.self) { frame in<br>                self.frame(frame)<br>            }<br>    }<br>}<br><br>extension View {<br>    func onFrameChange(coordinateSpace: CoordinateSpace = .global, closure: @escaping (CGRect) -&gt; Void) {<br>        viewModifier(FrameModifier(coordinateSpace: coordinateSpace, size: closure))<br>    }<br>}</pre><pre>ScrollView {<br>    LazyVStack {<br><br>        // Your scroll content...<br>    }<br>    .onFrameChanged(coordinateSpace: .named(&quot;scroll&quot;)) { frame in<br>        offset = frame.minY<br>    }<br>}<br>.coordinateSpace(name: &quot;scroll&quot;)</pre><p>In SwiftUI, every view is rendered within a certain <strong>coordinate space</strong>, which determines the reference point for measuring its size or position.</p><p>By default, SwiftUI uses three main coordinate spaces:</p><p>• <strong>Local</strong>: Relative to the view itself.</p><p>• <strong>Global</strong>: Relative to the whole screen (device screen coordinates).</p><p>• <strong>Named (custom)</strong>: Relative to a user-defined coordinate space.</p><pre>// You explicity set this custom space by doing something like:<br>.coordinateSpace(name: &quot;myCustomSpace&quot;)</pre><p>By setting .coordinateSpace(name: &quot;scroll&quot;) explicitly on the parent view ScrollView, you guarantee a stable, consistent reference.</p><ul><li>Every measurement now occurs <strong>relative to the top-left corner of the ScrollView itself</strong>, not the entire screen.</li></ul><pre>Device Screen (global)<br>  └── SafeArea<br>       └── NavigationStack<br>            └── ScrollView (&quot;scroll&quot;)<br>                 └── GeometryReader</pre><p>Thus, even across multiple devices or complex layouts, you’ll always get consistent scroll positions.</p><p>You should explicitly define and use a custom coordinateSpace whenever you:</p><p>• Track scroll offset or scroll position changes in a ScrollView.</p><p>• Measure positions of child views relative to their containers.</p><p>• Need stable and predictable layouts independent of safe areas, status bars, navigation bars, or screen size.</p><p>I hope this article helped you understand how and when to use PreferenceKey and CoordinateSpace in real SwiftUI projects. If you found it useful, feel free to leave a <strong>clap</strong> or follow me here on Medium to catch future articles.</p><p>You&#39;re also welcome to connect with me on <a href="http://www.linkedin.com/in/thiago-centurion">LinkedIn</a> — I’m always up for a good SwiftUI conversation, sharing ideas, or helping with any questions you might have.</p><p>Stay tuned for the next article, where we’ll dive even deeper into advanced SwiftUI techniques.</p><p>Until then, happy coding!</p><h4>Recent posts</h4><ul><li><a href="https://medium.com/@thiagorodriguescenturion/3-ways-to-optimize-performance-in-swiftui-apps-5a54b72b4041">3 Ways to Optimize Performance in SwiftUI</a></li><li><a href="https://medium.com/@thiagorodriguescenturion/stop-using-progressview-custom-skeleton-loading-in-swiftui-83682ca7a13e">Custom Skeleton loading in SwiftUI: Beyond ProgressView</a></li><li><a href="https://medium.com/@thiagorodriguescenturion/mastering-multi-project-git-workflows-a-comprehensive-guide-for-software-engineers-033a5f33fed9">Mastering Multi-Project Git Workflows</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772d32f5cc6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to Optimize Performance in SwiftUI Apps]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/3-ways-to-optimize-performance-in-swiftui-apps-5a54b72b4041?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a54b72b4041</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 16:53:00 GMT</pubDate>
            <atom:updated>2024-09-07T16:53:00.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*SUtkESK0DRUTPkbDg0wCMg.png" /></figure><p>SwiftUI has revolutionized iOS development with its declarative syntax and powerful features. However, as your app grows in complexity, you might face performance challenges. In this article, we’ll explore three key techniques to optimize performance in SwiftUI apps: efficient view hierarchy management, reducing state updates, and leveraging the power of Combine.</p><h3>1. Efficient View Hierarchy Management</h3><p>One of the most common performance bottlenecks in SwiftUI is an overly complex view hierarchy. SwiftUI recalculates the entire body of a view when any of its dependencies change. Therefore, keeping your view hierarchy lean and modular is crucial.</p><h4>Example: Optimizing a Complex List with Custom Cells</h4><p>Let’s consider a complex scenario where we have a list of items, each with multiple properties and interactive elements. In this case, efficient view hierarchy management becomes crucial for maintaining smooth scrolling and responsiveness.</p><pre>struct Item: Identifiable {<br>    let id = UUID()<br>    let title: String<br>    let description: String<br>    let price: Double<br>    var isFavorite: Bool<br>}<br><br>class ItemsViewModel: ObservableObject {<br>    @Published var items: [Item] = [<br>        Item(title: &quot;Product 1&quot;, description: &quot;Description 1&quot;, price: 19.99, isFavorite: false),<br>        Item(title: &quot;Product 2&quot;, description: &quot;Description 2&quot;, price: 29.99, isFavorite: true),<br>        // ... more items ...<br>    ]<br>    <br>    func toggleFavorite(for item: Item) {<br>        if let index = items.firstIndex(where: { $0.id == item.id }) {<br>            items[index].isFavorite.toggle()<br>        }<br>    }<br>}</pre><h4>Inefficient Approach</h4><pre>struct IneffientItemsListView: View {<br>    @StateObject private var viewModel = ItemsViewModel()<br>    <br>    var body: some View {<br>        List(viewModel.items) { item in<br>            VStack(alignment: .leading) {<br>                Text(item.title)<br>                    .font(.headline)<br>                Text(item.description)<br>                    .font(.subheadline)<br>                    .foregroundColor(.gray)<br>                HStack {<br>                    Text(&quot;$\(item.price, specifier: &quot;%.2f&quot;)&quot;)<br>                        .font(.callout)<br>                        .foregroundColor(.blue)<br>                    Spacer()<br>                    Button(action: {<br>                        viewModel.toggleFavorite(for: item)<br>                    }) {<br>                        Image(systemName: item.isFavorite ? &quot;heart.fill&quot; : &quot;heart&quot;)<br>                            .foregroundColor(item.isFavorite ? .red : .gray)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Optimized Approach</h4><pre>struct EfficientItemsListView: View {<br>    @StateObject private var viewModel = ItemsViewModel()<br>    <br>    var body: some View {<br>        List(viewModel.items) { item in<br>            ItemCell(item: item, onFavoriteToggle: {<br>                viewModel.toggleFavorite(for: item)<br>            })<br>        }<br>    }<br>}<br><br>struct ItemCell: View {<br>    let item: Item<br>    let onFavoriteToggle: () -&gt; Void<br>    <br>    var body: some View {<br>        VStack(alignment: .leading) {<br>            Text(item.title)<br>                .font(.headline)<br>            Text(item.description)<br>                .font(.subheadline)<br>                .foregroundColor(.gray)<br>            HStack {<br>                PriceView(price: item.price)<br>                Spacer()<br>                FavoriteButton(isFavorite: item.isFavorite, onToggle: onFavoriteToggle)<br>            }<br>        }<br>    }<br>}<br><br>struct PriceView: View {<br>    let price: Double<br>    <br>    var body: some View {<br>        Text(&quot;$\(price, specifier: &quot;%.2f&quot;)&quot;)<br>            .font(.callout)<br>            .foregroundColor(.blue)<br>    }<br>}<br><br>struct FavoriteButton: View {<br>    let isFavorite: Bool<br>    let onToggle: () -&gt; Void<br>    <br>    var body: some View {<br>        Button(action: onToggle) {<br>            Image(systemName: isFavorite ? &quot;heart.fill&quot; : &quot;heart&quot;)<br>                .foregroundColor(isFavorite ? .red : .gray)<br>        }<br>    }<br>}</pre><p>In this example, we’ve demonstrated two approaches to creating a list of items:</p><ol><li><strong>Inefficient Approach (</strong><strong>IneffientItemsListView)</strong>: This view defines the entire cell structure within the List. While this might seem straightforward, it can lead to performance issues as the list grows. Every time any item in the viewModel.items array changes, SwiftUI will potentially recalculate and redraw the entire list.</li><li><strong>Optimized Approach (</strong><strong>EfficientItemsListView)</strong>: This view uses a separate ItemCell component, which is further broken down into PriceView and FavoriteButton subcomponents. This structure offers several benefits:</li></ol><ul><li><strong>Modularity</strong>: Each component is responsible for rendering a specific part of the cell, making the code more maintainable and reusable.</li><li><strong>Improved Performance</strong>: By isolating the FavoriteButton, we ensure that toggling the favorite status only redraws that specific button, not the entire cell or list.</li><li><strong>Better State Management</strong>: The onFavoriteToggle closure is passed down to the FavoriteButton, allowing the parent view to manage state changes without unnecessary redraws.</li></ul><p>In the optimized approach, if an item’s favorite status changes, SwiftUI only needs to redraw the FavoriteButton for that specific item, rather than recalculating the entire cell or list. This can lead to significant performance improvements, especially for long lists or complex cell structures.</p><p>Additionally, this structure makes it easier to apply optimizations like @ViewBuilder for conditional content within each subcomponent, or to use equatable() modifier on the ItemCell to prevent unnecessary redraws when item properties that don&#39;t affect the view haven&#39;t changed.</p><h3>2. Reducing State Updates</h3><p>Unnecessary state updates can cause SwiftUI to recalculate and redraw views more often than needed. By carefully managing your state and using appropriate property wrappers, you can significantly improve your app’s performance.</p><h4>Using @StateObject vs. @ObservedObject</h4><p>When dealing with reference types that conform to ObservableObject, use @StateObject for the view that creates the object and @ObservedObject for views that receive it as a parameter.</p><pre>class UserViewModel: ObservableObject {<br>    @Published var username: String = &quot;&quot;<br>    @Published var isLoggedIn: Bool = false<br>    <br>    func login() {<br>        // Simulating login process<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>            self.isLoggedIn = true<br>            self.username = &quot;JohnDoe&quot;<br>        }<br>    }<br>}<br><br>struct LoginView: View {<br>    @StateObject private var viewModel = UserViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            if viewModel.isLoggedIn {<br>                Text(&quot;Welcome, \(viewModel.username)!&quot;)<br>            } else {<br>                Button(&quot;Login&quot;) {<br>                    viewModel.login()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct ProfileView: View {<br>    @ObservedObject var viewModel: UserViewModel<br>    <br>    var body: some View {<br>        Text(&quot;Profile for \(viewModel.username)&quot;)<br>    }<br>}</pre><p>In this example, LoginView uses @StateObject because it creates the UserViewModel. If we were to pass this view model to a child view, we would use @ObservedObject in that child view, as demonstrated in ProfileView.</p><h4>Custom Property Wrappers</h4><p>A highly advanced technique for reducing state updates involves creating custom <strong>property wrappers</strong> that allow for partial updates of complex state objects. This approach can significantly improve performance in scenarios where you have large, nested state structures but only need to update small portions of them.</p><h4>Example:</h4><p>Create a custom property wrapper that tracks changes to individual properties of a complex state object. This wrapper will only trigger view updates when the specific properties used by a view are modified, rather than when any part of the state changes.</p><pre>@propertyWrapper<br>struct PartialState&lt;Value: Equatable&gt; {<br>    private class Storage: ObservableObject {<br>        var value: Value {<br>            didSet {<br>                if oldValue != value {<br>                    objectWillChange.send()<br>                }<br>            }<br>        }<br>        <br>        init(value: Value) {<br>            self.value = value<br>        }<br>    }<br>    <br>    @StateObject private var storage: Storage<br>    <br>    var wrappedValue: Value {<br>        get { storage.value }<br>        nonmutating set { storage.value = newValue }<br>    }<br>    <br>    var projectedValue: Binding&lt;Value&gt; {<br>        Binding(<br>            get: { storage.value },<br>            set: { storage.value = $0 }<br>        )<br>    }<br>    <br>    init(wrappedValue: Value) {<br>        _storage = StateObject(wrappedValue: Storage(value: wrappedValue))<br>    }<br>    <br>    struct Key: Hashable {<br>        let id: ObjectIdentifier<br>        let keyPath: AnyKeyPath<br>    }<br>}<br><br>extension View {<br>    func onPartialChange&lt;Value: Equatable&gt;(<br>        of state: PartialState&lt;Value&gt;,<br>        at keyPath: KeyPath&lt;Value, some Equatable&gt;,<br>        perform action: @escaping (Value) -&gt; Void<br>    ) -&gt; some View {<br>        let key = PartialState&lt;Value&gt;.Key(id: ObjectIdentifier(state.storage), keyPath: keyPath)<br>        return onChange(of: state.wrappedValue[keyPath: keyPath]) { _ in<br>            action(state.wrappedValue)<br>        }<br>        .id(key)<br>    }<br>}</pre><h4>Usage:</h4><p>To better understand how @PartialState prevents unnecessary redraws compared to @State, let&#39;s examine our ComplexView example:</p><pre>struct ComplexState: Equatable {<br>    var name: String<br>    var age: Int<br>    var address: Address<br>}<br><br>struct Address: Equatable {<br>    var street: String<br>    var city: String<br>    var country: String<br>}<br><br>struct ComplexView: View {<br>    @PartialState var state: ComplexState<br><br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Name&quot;, text: $state.name)<br>                .onPartialChange(of: _state, at: \.name) { newState in<br>                    print(&quot;Name changed to: \(newState.name)&quot;)<br>                }<br>            <br>            TextField(&quot;Age&quot;, value: $state.age, formatter: NumberFormatter())<br>                .onPartialChange(of: _state, at: \.age) { newState in<br>                    print(&quot;Age changed to: \(newState.age)&quot;)<br>                }<br>            <br>            TextField(&quot;Street&quot;, text: $state.address.street)<br>                .onPartialChange(of: _state, at: \.address.street) { newState in<br>                    print(&quot;Street changed to: \(newState.address.street)&quot;)<br>                }<br>        }<br>    }<br>}</pre><p>Now, let’s compare the behavior of @PartialState with @State:</p><ol><li><strong>With @State:</strong> If we used @State var state: ComplexState instead of @PartialState, any change to any property of state would cause the entire ComplexView to be redrawn. For example:</li></ol><ul><li>Changing the name would redraw all three TextFields.</li><li>Changing the age would also redraw all three TextFields.</li><li>Changing the street address would again redraw all three TextFields.</li></ul><p><strong>2. With @PartialState:</strong> Our custom @PartialState wrapper, combined with the onPartialChange modifier, allows for more granular updates:</p><ul><li>Changing the name will only redraw the name TextField and execute its onPartialChange closure.</li><li>Changing the age will only redraw the age TextField and execute its onPartialChange closure.</li><li>Changing the street address will only redraw the street TextField and execute its onPartialChange closure.</li></ul><p>The key advantage of @PartialState is that it prevents unnecessary redraws of view components that depend on unchanged parts of the state. This can significantly improve performance in complex views with large state objects, especially when frequent updates occur to specific parts of the state.</p><h3>3. Leveraging the Power of Combine</h3><p>Combine is a powerful framework that can help you manage complex asynchronous operations and data flows. By using Combine effectively, you can reduce unnecessary view updates and improve overall app responsiveness.</p><h4>Custom Combine Operators for Domain-Specific Optimizations</h4><p>While Combine provides a rich set of operators, creating custom operators tailored to your specific domain can lead to more efficient and readable code. But note that SOLID should be always the priority, so it should use generic types while you implement something for a domain-specific API call, like a <strong>stock analysis polling</strong>.</p><p>Developing custom Combine operators that encapsulate complex, domain-specific data transformations. These operators can optimize performance by reducing the number of intermediate publishers and simplifying your data processing pipelines.</p><h4>Example:</h4><p>Let&#39;s create a custom operator for an app that needs to process stock data efficiently with polling. So, for the Combine layer, we build a generic structure:</p><pre>import Combine<br>import Foundation<br><br>extension Publishers {<br>    struct TimeBasedPolling&lt;Upstream: Publisher&gt;: Publisher {<br>        typealias Output = [Upstream.Output]<br>        typealias Failure = Upstream.Failure<br><br>        private let upstream: Upstream<br>        private let interval: TimeInterval<br><br>        init(upstream: Upstream, interval: TimeInterval) {<br>            self.upstream = upstream<br>            self.interval = interval<br>        }<br><br>        func receive&lt;S&gt;(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {<br>            upstream<br>                .collect(.byTime(DispatchQueue.main, .seconds(interval)))<br>                .receive(subscriber: subscriber)<br>        }<br>    }<br>}<br><br>extension Publisher {<br>    func polling(for interval: TimeInterval) -&gt; Publishers.TimeBasedPolling&lt;Self&gt; {<br>        return Publishers.TimeBasedPolling(upstream: self, interval: interval)<br>    }<br>}</pre><p>Usage:</p><pre>class StockViewModel: ObservableObject {<br>    @Published var latestAnalysis: StockAnalysis?<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    init(stockPublisher: AnyPublisher&lt;Stock, Never&gt;) {<br>        stockPublisher<br>            .polling(for: 5) // Polling stocks every 5 seconds<br>            .sink { [weak self] analysis in<br>                self?.latestAnalysis = analysis<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>struct Stock {<br>    let symbol: String<br>    let price: Double<br>}<br><br>struct StockAnalysis {<br>    let averagePrice: Double<br>    let volatility: Double<br>    let trend: String<br>}</pre><p>This generic polling operator provides several advantages:</p><ol><li><strong>Flexibility</strong>: It can be used with any type of publisher, not just specific data models.</li><li><strong>Reduced Processing</strong>: By polling data over time intervals, we can reduce the frequency of downstream processing and UI updates.</li><li><strong>Batched Operations</strong>: This is useful for performing operations on batches of data, such as bulk API requests or aggregated analytics.</li><li><strong>Customizable</strong>: The time interval is parameterized, allowing for easy adjustment based on different use cases.</li></ol><p>This technique is particularly useful in scenarios where you need to process high-frequency data streams efficiently, such as real-time sensors, financial tickers, or user interaction events. It allows you to balance between real-time updates and system performance.</p><h3>Conclusion</h3><p>Optimizing performance in SwiftUI apps requires a multifaceted approach. By efficiently managing your view hierarchy, reducing state updates, and leveraging Combine, you can create responsive and efficient SwiftUI apps. Remember to profile your app using Instruments and always test on real devices to ensure the best possible performance for your users.</p><p>As you continue to work with SwiftUI, keep these optimization techniques in mind, and don’t hesitate to refactor your code as your app grows in complexity. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a54b72b4041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Skeleton loading in SwiftUI: Beyond ProgressView]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/stop-using-progressview-custom-skeleton-loading-in-swiftui-83682ca7a13e?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83682ca7a13e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[thiago-centurion]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 19:20:29 GMT</pubDate>
            <atom:updated>2024-08-19T11:34:16.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uZ5_qMv7QUAeCtaFCHzNKA.gif" /></figure><p>Skeleton loading and shimmering effects enhance user experience in iOS apps by providing visual feedback during content loading. This guide will show you how to create a custom .skeleton(_:isLoading:) modifier in SwiftUI, offering a more flexible alternative to the native .redacted(reason: .placeholder).</p><h4>The Problem with native solutions</h4><p>While SwiftUI’s .redacted(reason: .placeholder) is convenient, it applies inconsistent colors across different view types. Our custom solution ensures uniform shimmering effects for all views and does not require a higher target iOS version.</p><h3>Usage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaqpHA75TJmYjaeJgFSjOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*j250Vn01E9SlgjmwdyETpA.gif" /></figure><p>This Text is wrapped with the .skeleton(isLoading:) modifier, passing the isLoading state. So when tapping the button sets isLoading to false, triggering the transition from the skeleton to the actual content.</p><p>You can see that it&#39;s possible to implement the .skeleton(_:isLoading:) in any view, making a group of different views like .redacted(reason:) does. Below, we have a List of Items with rows with an icon, title and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OrXg5Wt9hfN5FQ13s75ow.png" /></figure><ol><li>By providing a Circle() to the method, the skeleton simply change the normal rectangle shimmering by the given Shape. You can provide whatever Shape you want.</li><li>By calling .skeleton(isLoading:) separately in two different Text , we&#39;ll be able to build a code where the skeleton is applied differently instead of merging the whole Stack with a big rectangle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WMt4b8bnAFwXBiHnqV7KSg.gif" /></figure><h3>1. Creating the Skeleton</h3><h4>Step 1: Creating the Skeleton method</h4><p>Let’s start by creating a basic skeleton overlay that applies a solid color to a view when loading. We’ll define this method as an extension on the View protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97qICzmXbY8MrLx1FBkONw.png" /></figure><p>Here’s how the code works:</p><ol><li>We define a skeleton(isLoading:) function that takes a Bool parameter indicating whether the skeleton effect should be applied.</li><li>If isLoading is false, we return the original view without any modifications.</li><li>If isLoading is true, we hide the original view by setting its opacity to 0 and overlay it with a gray Rectangle.</li></ol><p>At this point, we have a basic skeleton modifier that hides the view and displays a solid gray rectangle when loading. However, we can notice two points:</p><ul><li>There&#39;s no any gradient animation.</li><li>If we have a non-rectangle view (e.g. Circle or Shape &#39;s) this would always be replaced with a Rectangle() .</li></ul><p>So that&#39;s where we&#39;ll implement a Shimmering View Modifier. Before, let&#39;s cover the non-rectangle problem below.</p><h4>Step 2: Adding Custom Shape Support</h4><p>To make our skeleton modifier more flexible, let’s add support for custom shapes. We’ll update the skeleton function to accept an optional Shape parameter.</p><p>If your app targets iOS 16+:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbOUWv6ofokr9xW5HGUpNw.png" /></figure><p>Alternative without AnyShape :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfUW3JNWU3dq4FnmjpMY4w.png" /></figure><ol><li>We provide a generic Shape being able to provide whatever Shape the caller want to use while it&#39;s loading, like a Rectangle , Circle , custom Polygon, etc. nil as Rectangle? is a way to avoid the error <em>&quot;Generic parameter ‘S’ could not be inferred&quot;</em></li><li>When shape exists, we apply it instead of the default Rectangle() as before. We <strong>must</strong> segregated as Shape is a protocol that cannot be inferred. So the code below does not compile, because Shape and Rectangle are not equal.</li></ol><pre>AnyView(<br>    opacity(0)<br>        .overlay(<br>            (shape ?? Rectangle())<br>                .fill(skeletonColor)<br>        )<br>)</pre><h3>2. Creating the Shimmering Effect</h3><p>To create a more visually appealing skeleton loading effect, let’s add a shimmering animation. We’ll create a separate ShimmeringModifier that can be applied to any view. Let’s break down the process into smaller steps.</p><h4>Step 2.1: Defining the ShimmeringModifier</h4><p>First, let’s define the ShimmeringModifier as a ViewModifier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41jZPhQx3zpnFG2cwM_fMw.png" /></figure><p>The phase property represents the current phase or progress of the shimmering animation. It is a value between 0 and 1, where 0 represents the starting point of the animation and 1 represents the endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_W0czZIQoulRyu4SNMVfQ.png" /></figure><p>When the view appears, we start an infinite linear animation that animates the phase value from 0 to 1 over a duration of 2 seconds. This animation will drive the shimmering effect. Feel free to put the duration you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQFPR7Rw2H9rH60HSzEXyg.png" /></figure><p>In the body function, we apply the AnimatedMask modifier (that we&#39;ll see bellow how it works) and pass the phase value to it, so this modifier will be able to change the gradient animation internally.</p><h4>Step 2.2: Implementing the AnimatedMask</h4><p>Next, let’s implement the AnimatedMask modifier. The AnimatedMask modifier uses the phase value to create the animated gradient mask effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umKtQcgusIWvkpKiByZ2_g.png" /></figure><p>The AnimatedMask modifier conforms to the AnimatableModifier protocol, which allows it to participate in animations. The phase property is declared as the animatableData, which is a required property from the protocol, and it means that SwiftUI will automatically interpolate the phase value during the animation (0.0 , 0.1 , 0.2 , … 1.0 ).</p><p>In the body function of AnimatedMask, we apply a mask to the content view using the GradientMask view. The GradientMask takes the phase value as input to determine the position of the gradient stops.</p><p>As the phase value animates from 0 to 1, the gradient mask moves across the view, creating the shimmering effect. The scaleEffect(3) modifier ensures that the gradient mask covers the entire view during the animation.</p><h4>Step 2.3: Creating the GradientMask</h4><p>The GradientMask view is the core component that creates the shimmering effect. It uses a linear gradient with strategically placed color stops to create a moving gradient mask. Let&#39;s dive into each part of the GradientMask view and understand the math and logic behind it.</p><p>We start by defining two colors: centerColor and edgeColor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVYH9PTYvlXS5niBsxYaWQ.png" /></figure><p>The centerColor is a semi-transparent black color with an opacity of 0.5, while the edgeColor is a fully opaque black color. These colors will be used to create the gradient stops. However, as it&#39;s a mask, .opacity(1) represents full transparent to the final shape, where we could see the original fill background color. .opacity(0.5) will be the middle color, representing the lightning for the gradient.</p><h4>Creating the Linear Gradient</h4><p>Inside the body of the GradientMask, we create a LinearGradient with three gradient stops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aq0DW9yCDdIrRo6BeyImeg.png" /></figure><p>The Gradient is initialized with an array of Gradient.Stop instances. Each stop consists of a color and a location.</p><ul><li>The first stop uses the edgeColor and its location is determined by the phase value.</li><li>The second stop uses the centerColor and its location is phase + 0.1.</li><li>The third stop uses the edgeColor again and its location is phase + 0.2.</li></ul><p>The phase value represents the progress of the animation and ranges from 0 to 1.</p><p>By using phase, phase + 0.1, and phase + 0.2 as the locations, we create a moving window of color stops. As the phase value animates from 0 to 1, the color stops will move across the gradient, creating the shimmering effect.</p><p>The startPoint and endPoint of the LinearGradient are set using UnitPoint with coordinates (0, 0.5) and (1, 0.5), respectively. This means the gradient starts from the left edge and ends at the right edge, horizontally centered.</p><h4>Rotating the Gradient</h4><p>To create a diagonal shimmering effect, we apply a rotation effect to the gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhyG3y5h3uFDKsZPtgWG6A.png" /></figure><p>By rotating the gradient by -45 degrees, it will appear diagonal, starting from the top-left corner and moving towards the bottom-right corner.</p><h4>Offsetting the Gradient</h4><p>To ensure that the gradient covers the entire view during the animation, we need to offset it. We use a GeometryReader to access the size of the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgoUtwqktq5TxOuh60-pcQ.png" /></figure><p>By offsetting the gradient by the negative width and height of the view, we shift it to start outside the view’s bounds. This ensures that the gradient is always visible during the animation.</p><h4>Scaling the Gradient</h4><p>Finally, we scale the gradient to be larger than the view itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBfVjPmVwi4oap1TybPqVg.png" /></figure><p>By multiplying the width and height of the view by 3, we create a gradient that is three times larger than the view. This allows the gradient to cover the entire view and provides a smooth shimmering effect as it moves across the view.</p><h4>Step 2.4: Adding the shimmering() Modifier Extension</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3kW091CdYPQcTCaJzn6xQ.png" /></figure><p>With this extension, we can easily apply the shimmering effect to any view by simply calling the shimmering() modifier.</p><p>Now that you finished the .skeleton(_:isLoading:) implementation, you can finally throw away your ProgressView() , like in the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OrXg5Wt9hfN5FQ13s75ow.png" /></figure><h3>Conclusion</h3><p>In this article, we explored how to create the .skeleton(_:isLoading:) modifier in SwiftUI to achieve skeleton loading and shimmering effects. We started with a basic implementation and gradually added complexity, supporting custom shapes and a visually appealing shimmering animation.</p><ul><li>By using the .skeleton(_:isLoading:) modifier, you can enhance the user experience of your SwiftUI apps by providing visual feedback during content loading. The skeleton effect helps to maintain a sense of progress and reduces the perceived loading time.</li><li>Remember to use skeleton loading judiciously and apply it to key content areas where loading times may be noticeable. Overusing skeleton effects can lead to a negative user experience, so strike a balance between providing visual feedback and maintaining a smooth user flow.</li></ul><p>With the power of SwiftUI and the .skeleton(_:isLoading:) modifier, you can create engaging and polished loading experiences in your iOS apps.</p><p>Happy coding, and may your apps shine with stunning skeleton loading and shimmering effects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83682ca7a13e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multi-Project Git Workflows: A Comprehensive Guide for Software Engineers]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/mastering-multi-project-git-workflows-a-comprehensive-guide-for-software-engineers-033a5f33fed9?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/033a5f33fed9</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 00:16:53 GMT</pubDate>
            <atom:updated>2024-11-24T18:08:49.352Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Navigating the Complexity of Multiple SSH Keys and Git Configurations in a Multi-Repository Environment</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPY2AIJL32pUx1XJ5x51Aw.png" /></figure><p>Imagine this: you’re comfortably working on a single project, your Git configurations humming along smoothly. But then, as your career progresses, you’re tasked with managing multiple projects — each with its unique requirements. Suddenly, the Git setup that seemed so straightforward is now a labyrinth of SSH keys and configurations. The internet is awash with quick fixes and hacks, but you’re after a deeper understanding. You want a guide that doesn’t just patch the problem but empowers you with knowledge for any future project. That’s precisely what this article aims to provide: a detailed, step-by-step approach to mastering Git configurations for multiple projects. Let’s dive in.</p><h3>Understanding Basic SSH Configuration</h3><p>Before we delve into complex configurations, let’s level-set with a quick primer on SSH keys in the simplest scenario: a single project. SSH keys are a pair of cryptographic keys that ensure a secure connection to your Git repository. These keys play a pivotal role in managing secure access to your repositories, making them an essential part of any software developer’s toolkit.</p><p>SSH, or Secure Shell, is a protocol used to securely access and manage remote systems. In the context of Git, SSH keys authenticate your identity to Git hosting services like GitHub or GitLab, allowing you to push and pull changes without having to enter your username and password every time. This method is not only more secure than traditional password authentication but also more convenient.</p><h3>Setting Up SSH for a Single Project</h3><p>When managing a single project, SSH key setup is usually straightforward. Here’s how you can set it up:</p><p><strong>1. Generate an SSH Key</strong></p><p>The first step is to generate a new SSH key pair. This is done using the ssh-keygen command, which creates a private and a public key. The private key is kept secret on your machine, while the public key is shared with the Git hosting service.</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;your_email@example.com&quot;</pre><p>This command generates a new SSH key using RSA encryption, with a key size of 4096 bits, and labels the key with your email for easy identification.</p><p><strong>2. Add the Key to SSH Agent</strong></p><p>The SSH agent is a background program that handles keys for SSH. Adding your newly generated SSH key to the agent allows for seamless authentication to remote servers.</p><p>Start the SSH agent:</p><pre>eval &quot;$(ssh-agent -s)&quot;</pre><p>Add your SSH key to the agent:</p><pre>ssh-add ~/.ssh/id_rsa</pre><p><strong>3. Link the Key to Git Hosting Service</strong></p><p>The final step involves linking your public SSH key to your Git hosting service. This is typically done through the service’s user settings.</p><ul><li>Copy the SSH key to your clipboard. You can use pbcopy &lt; ~/.ssh/id_rsa.pub on macOS or install xclip on Linux (sudo apt-get install xclip) and use xclip -sel clip &lt; ~/.ssh/id_rsa.pub.</li><li>Navigate to your GitHub or GitLab account settings and locate the SSH key section.</li><li>Add your new SSH key by pasting the copied public key into the appropriate field.</li></ul><p>This setup is typically sufficient for individual or single-project workflows. It ensures that your commits are securely linked to your identity, and provides a streamlined workflow for pushing and pulling changes to and from the remote repository.</p><h3>Setting Up SSH to the Second Project</h3><p>As you embark on a second project, the need for another SSH key arises. Managing multiple projects often requires distinct SSH keys for each, ensuring secure and separate access. Here’s an extended guide on how to create and manage this new key:</p><h4>1. Navigate to SSH Directory</h4><p>SSH keys are stored in the ~/.ssh/ directory. This central location is crucial for key management:</p><ul><li><strong>Accessing the Directory</strong>: Use cd ~/.ssh/ to navigate to this directory. It&#39;s a repository of all your SSH keys and configurations, making it the starting point for setting up new keys.</li></ul><h4>2. Create a New SSH Key</h4><p>Generating a second SSH key is similar to your first, but with a focus on distinguishing it for your specific project needs. Execute:</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;your_second_email@example.com&quot; -f id_rsa_personal</pre><p>This command creates a new key (id_rsa_personal) with a 4096-bit RSA encryption, labeled with your second email. The -f flag specifies the filename, helping you identify the key&#39;s purpose easily.</p><h4>3. Rename Existing Key</h4><p>If your existing key is generically named (id_rsa), renaming it enhances organization and clarity, especially when you start handling multiple keys.</p><pre>mv id_rsa id_rsa_work<br>mv id_rsa.pub id_rsa_work.pub</pre><p>This renames both your private and public keys, aligning them with your work-related activities.</p><h3>Creating the SSH Config File</h3><p>The SSH config file is a powerful tool that dictates how SSH should behave with each project.</p><h4>1. Check for Existing Config File and create if necessary</h4><p>Use ls ~/.ssh/config to check if the config file already exists. If not, you&#39;re going to create one to manage your multiple SSH keys effectively. Create it using touch ~/.ssh/config. This file will serve as a command center for your SSH configurations.</p><h4>2. Edit the Config File</h4><p>Now, with two keys, you’ll need to instruct SSH when to use each one. This is done through the ~/.ssh/config file. This file controls SSH client behavior. Let&#39;s start with setting up aliases:</p><pre># Account 1 - work <br>Host gitlab-work<br>   Hostname gitlab.com<br>   User git<br><br># Account 2 - home<br>Host gitlab-home<br>   Hostname gitlab.com<br>   User git</pre><p>The Host is an alias — a shortcut that tells SSH which configuration to use. This separation makes handling multiple projects much more manageable. Then, you add the Hostname and User for each one. In my example, I used GitLab for both, but if you are using GitHub just add it normally with Hostname github.com.</p><h4>3. Adding IdentityFile to Each Host</h4><p>In multi-project environments, distinguishing between SSH keys for different hosts becomes essential. This is where specifying an IdentityFile for each host in your SSH config plays a crucial role.</p><p>By specifying an IdentityFile for each Host entry, you instruct SSH to use a particular key for each specific remote server. This is critical when your projects are hosted on the same domain (like gitlab.com) but require different access credentials.</p><pre># Account 1 - work <br>Host gitlab-work<br>   Hostname gitlab.com<br>   User git<br>   IdentityFile ~/.ssh/id_rsa_work<br><br># Account 2 - home<br>Host gitlab-home<br>   Hostname gitlab.com<br>   User git<br>   IdentityFile ~/.ssh/id_rsa_personal</pre><p>In this configuration, gitlab-work and gitlab-home are aliases that refer to different project settings. The IdentityFile directive ensures that SSH uses id_rsa_work for your work-related projects and id_rsa_personal for personal projects.</p><h3>Managing SSH Keys with ssh-add</h3><p>As mentioned before, The SSH agent is a background program that handles keys for SSH, allowing authentication to remote servers. The ssh-add command is an integral part of SSH key management. It adds your keys to the SSH agent, which in turn handles key storage and usage.</p><p>This command simplifies the process of using SSH keys. Instead of specifying which private key to use for each SSH connection, the SSH agent automatically selects the appropriate key based on your configuration.</p><p>As you have configured the SSH Agent with the old id_rsa name, clearing the agent’s cache can be a necessary step, because you have renamed it to id_rsa_work in addition to the fact we created an id_rsa_personal. Use ssh-add -D to clear all stored keys from the agent, then re-add them:</p><pre>ssh-add -D<br>ssh-add ~/.ssh/id_rsa_work<br>ssh-add ~/.ssh/id_rsa_personal</pre><p>This process ensures that your SSH agent is always up-to-date with the current keys you intend to use.</p><h3>Adding Keys Automatically on Startup</h3><p>For an even smoother experience, particularly for macOS users with access to Keychain, automating the addition of keys to the SSH agent might be helpful. But before that, you should know that always you reboot your computer, adding the ssh by ssh-add again will be needed. You can avoid this kind of problem by adding a great parameter to the ~/.ssh/config file.</p><h4>1. Automated Key Management</h4><p>Adding AddKeysToAgent yes to your SSH config enables the automatic addition of the specified keys to the SSH agent upon their first use.</p><h4>2. Integration with macOS Keychain</h4><p>The UseKeychain yes directive is particularly beneficial for macOS users. It allows the SSH agent to store and retrieve key passphrases in the macOS Keychain, providing a secure and convenient way to manage key access.</p><pre># Account 1 - work <br>Host gitlab-work<br>   ...<br>   AddKeysToAgent yes<br>   UseKeychain yes<br><br># Account 2 - home<br>Host gitlab-home<br>   ...<br>   AddKeysToAgent yes<br>   UseKeychain yes</pre><p>With these settings, each time you start a new session or reboot your system, your SSH keys are automatically loaded, and their passphrases are securely handled by the Keychain. This setup not only streamlines your workflow but also maintains a high level of security for your SSH keys.</p><h3>Understanding .gitconfig</h3><p>The .gitconfig file is a pivotal element in any Git setup, particularly when managing individual projects. It serves as a centralized configuration file where you can define user-specific settings like name, email, and more.</p><h4>.gitconfig in Single Project Scenarios</h4><p>In a single-project scenario, the .gitconfig file typically includes basic user information and preferences. Here&#39;s an example of what this file might look like:</p><pre>[user]<br>    name = John Doe<br>    email = johndoe@example.com<br><br>[alias]<br>    co = checkout<br>    br = branch<br>    ci = commit<br>    st = status<br><br>[color]<br>    ui = auto</pre><p>This configuration sets the user’s name and email, which are used in commit messages. It also includes some handy aliases for common Git commands and enables colored output in the Git interface.</p><h4>Transitioning to Multi-Project Management</h4><p>When you start working on multiple projects, particularly those that require different user profiles (like personal and work projects), it becomes necessary to create separate configuration files for each context. This is where .gitconfig-work and .gitconfig-home come into play.</p><h4>Creating .gitconfig-work and .gitconfig-home</h4><p>These files will contain configuration specific to your work and personal projects, respectively. Here’s how to create and set up these files:</p><ul><li>Navigate to your home directory (cd ~) and create a new file named .gitconfig-work.</li><li>Open this file in a text editor. For example, you can use nano ~/.gitconfig-work.</li><li>Add the following content, replacing the placeholders with your work-related information:</li></ul><pre>[user]<br>    name = Your Work Name<br>    email = your_work_email@example.com<br>    signingkey = ssh-rsa AAAAB3Nza...<br>[remote &quot;origin&quot;]<br>    url = gitlab-work:work_username/work_repository.git</pre><p>This configuration sets your work name and email, along with a signing key for secure commits — signingkey is your public key, that you can get by going inside ~/.ssh/id_rsa_work.pub. The remote &quot;origin&quot; section specifies the URL for your primary work repository.</p><ul><li>Similarly, create a file named .gitconfig-home and edit the file (nano ~/.gitconfig-home) with your personal project settings:</li></ul><pre>[user]<br>    name = Your Personal Name<br>    email = your_personal_email@example.com<br>    signingkey = ssh-rsa AAAAB3Nza...<br>[remote &quot;origin&quot;]<br>    url = gitlab-home:personal_username/personal_repository.git</pre><p>This file mirrors the structure of .gitconfig-work but with your personal details and the URL of your main personal Git repository.</p><h4>Why Separate Config Files?</h4><p>Having separate config files for different projects is crucial for several reasons:</p><ul><li><strong>Identity Separation</strong>: These files ensure that your identity (name and email) is correctly set for commits in each project. This is particularly important for professional developers who need to maintain a clear distinction between work and personal contributions.</li><li><strong>Signing Key</strong>: The signingkey setting is crucial if you use GPG or SSH keys for signing your commits. It adds an extra layer of security and authenticity to your contributions.</li><li><strong>Repository-specific Configurations</strong>: The remote &quot;origin&quot; setting is particularly useful if you often work with a specific repository. It pre-defines the URL for the &#39;origin&#39; remote, streamlining your Git operations for that particular project.</li></ul><h3>Introducing includeIf in git</h3><p>The includeIf directive in your main .gitconfig file is a game-changer for managing multiple project environments. It smartly enables Git to apply different configurations based on the directory you&#39;re working in.</p><h4>How includeIf Works</h4><p>Git&#39;s includeIf feature allows you to conditionally apply different configuration files based on your current working directory. This is particularly useful when you have distinct settings for various projects, such as work and personal projects. Here&#39;s a deeper dive into how it operates:</p><ul><li><strong>Directory-Based Configuration</strong>: When you navigate to a directory in your terminal and run a Git command, Git checks the path against patterns specified in the includeIf conditions of your .gitconfig file. If you make any git commit, git push, etc, git will relly on this specific git configuration file, making sure you for example write a commit with the correct username and SSH key. Have you imagined if you commit to your work repository with the personal email?</li><li><strong>Conditional Application</strong>: If the current directory matches the specified pattern in an includeIf condition, Git automatically applies the settings from the corresponding configuration file. This switch happens seamlessly in the background.</li></ul><h4>Setting Up includeIf in .gitconfig</h4><p>Let’s enhance your main .gitconfig to leverage the power of includeIf:</p><pre># Main user information - This could be your default or most common identity<br>[user]<br>    name = Default Name<br>    email = defaultemail@example.com<br><br># Include work config when in any directory under &#39;~/Work&#39;<br>[includeIf &quot;gitdir:~/Work/&quot;]<br>    path = ~/.gitconfig-work<br><br># Include home config when in any directory under &#39;~/Personal&#39;<br>[includeIf &quot;gitdir:~/Personal/&quot;]<br>    path = ~/.gitconfig-home</pre><p>In this setup:</p><ul><li><strong>Work Configuration</strong>: When you’re working within any subdirectory of ~/Work/, Git automatically uses the configurations from .gitconfig-work. This might include your work email, specific Git aliases, or any other work-related settings.</li><li><strong>Personal Configuration</strong>: Conversely, when you’re inside any subdirectory of ~/Personal/, Git switches to the settings defined in .gitconfig-home. This is ideal for keeping your personal projects separate, with their configurations and identity.</li><li><strong>Default Settings</strong>: For directories outside these specified paths, Git falls back to the default settings defined at the beginning of the .gitconfig. This ensures that you always have a baseline configuration, regardless of the project.</li></ul><h3>Final Configurations and Testing</h3><p>After setting up your Git and SSH configurations for handling multiple projects, it’s crucial to verify that everything is functioning as expected. This final step ensures that your environment is correctly configured and ready for a seamless development experience.</p><h4>Testing Your SSH Connections</h4><p>Testing each SSH connection validates that Git is using the correct SSH key for each project. Here’s how to conduct these tests:</p><ul><li><strong>Testing the Work Configuration:</strong></li></ul><p>Navigate to your work project directory with cd ~/Documents/Work/work-repository and test the SSH connection for your work configuration:</p><pre>ssh -T gitlab-work</pre><p>If configured correctly, this should establish a connection using your gitlab-work settings, confirming the use of the work SSH key and the corresponding Git configurations. This will also print an output for you like Welcome to GitLab, @your_work_username! .</p><ul><li><strong>Testing the Personal Configuration:</strong></li></ul><p>Similarly, check your personal configuration by going to your personal project directory with cd ~/Documents/Home/home-repository and test the SSH connection for your personal setup:</p><pre>ssh -T gitlab-home</pre><p>The SSH command should authenticate successfully, indicating that the correct SSH key is being used. Pay attention to the username acknowledged by GitLab or GitHub. It should match the user identity associated with the SSH key used.</p><h4>Important to know</h4><p>Always that you need to switch between projects and make fetch or push , remember that you need to set again the SSH Connection ssh -T , otherwise you could see this kind of error when trying any git remote command:</p><pre>remote:<br>remote: ========================================================================<br>remote:<br>remote: ERROR: The project you were looking for could not be found or you don&#39;t have permission to view it.<br><br>remote:<br>remote: ========================================================================<br>remote:<br>fatal: Could not read from remote repository.<br><br>Please make sure you have the correct access rights<br>and the repository exists.</pre><p>First, delete all identities SSH keys and register again:</p><pre>ssh-add -D<br>ssh-add ~/.ssh/id_rsa_work<br>ssh-add ~/.ssh/id_rsa_personal</pre><h4>Troubleshooting</h4><p>If you encounter issues:</p><ul><li><strong>Check SSH Configurations</strong>: Ensure that your ~/.ssh/config file has the correct paths to your SSH keys and the right Hostname and User entries.</li><li><strong>Verify SSH Key Addition</strong>: Use ssh-add -l to list the SSH keys currently added to the SSH agent. Make sure the correct keys are listed.</li><li><strong>Review Git Configurations</strong>: Double-check your .gitconfig, .gitconfig-work, and .gitconfig-home files for any misconfigurations.</li><li><strong>Set again the remote repository:</strong> Sometimes the remote repository can get lost. To fix this issue, it&#39;s just to set again the remote repository by the following pattern for each repo:</li></ul><pre>git remote set-url origin &lt;host&gt;:&lt;workplace&gt;/&lt;repo&gt;.git</pre><p>Where host is the specific host given from the <strong>~/.ssh/config</strong> file. For example, if you set this host:</p><pre>...<br><br># Account 2 - home<br>Host gitlab-home<br>   Hostname gitlab.com<br>   User git<br>   IdentityFile ~/.ssh/id_rsa_personal</pre><p>and the repository is git@gitlab.com:personal_username/personal_repository.git, then the command will be:</p><pre>git remote set-url origin gitlab-home:personal_username/personal_repository.git</pre><h3>Where to go from here?</h3><ul><li>Provide article ideas and suggestions directly to me on LinkedIn <a href="https://www.linkedin.com/in/thiago-centurion/">https://www.linkedin.com/in/thiago-centurion/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033a5f33fed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Your Way Through the Git Jungle: A Guide to Branch Management with Zsh]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/finding-your-way-through-the-git-jungle-a-guide-to-branch-management-with-zsh-16451c8ae69f?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/16451c8ae69f</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 15:22:37 GMT</pubDate>
            <atom:updated>2023-04-04T15:22:37.083Z</atom:updated>
            <content:encoded><![CDATA[<p>Never get lost in your branches again with these simple steps! 🙌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CT8o7qWwVdI7JebmPY8VQ.png" /></figure><h3>Introduction</h3><p>Attention command line aficionados and Git enthusiasts! Are you tired of feeling lost in the wilderness of Git branches? Have you ever wished for an easy way to see which branches you’re working with? Look no further because we’ve got a solution for you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*bBZMhIU0JQCsTHjUoLjwfw.gif" /></figure><p>In this article, we’ll guide you through creating a simple function and alias in your ~/.zshrc file that makes navigating Git branches a breeze. So, let&#39;s dive right in!</p><h3>Step 1: Creating the Function</h3><p>First, let’s add a useful function to your ~/.zshrc file. This function will help you find all recent branches that start with any provided prefix name, such as &quot;thiago/feature/&quot;. To do this, add the following code to your ~/.zshrc file:</p><pre># Functions<br>git_recent_branches_with_prefix() {<br>  git for-each-ref --sort=-committerdate --format=&#39;%(committerdate:relative) %(refname)&#39;</pre><h3>Step 2: Creating an Alias</h3><p>Next, we’re going to make this function more user-friendly with a simple alias. Inside the same ~/.zshrc file, add the following line:</p><pre>alias git-recent-branches=git_recent_branches_with_prefi</pre><p>With this alias in place, you can easily print branches using a command like this:</p><pre>$ git-recent-branches &quot;preffix-here&quot;</pre><p>Example:</p><pre>$ git-recent-branches &quot;user-profile&quot;<br><br>1 hour ago refs/heads/user-profile/form-field-changes<br>2 hours ago refs/heads/user-profile-screen<br>1 day ago refs/heads/user-profile-refactoring<br>3 months ago refs/heads/user-profile/thiago/networking</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*mgIabNcs-qtTnzsf72SO2Q.gif" /></figure><h3>Conclusion</h3><p>No more wandering aimlessly through the Git jungle! With this simple function and alias, you’ll be able to keep track of your branches and impress your colleagues with your Git mastery. So go on, git to it, and happy branching!</p><p>I hope this quirky guide has made your Git experience a little less daunting and a lot more enjoyable. Just remember, whether you’re a seasoned Git pro or a newbie, there’s always more to learn and explore in the world of software engineering. Keep experimenting, and you might just discover the next great Git trick!</p><p>Now, go forth and conquer those branches like the Git ninja you are!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*lW2preVZLXPmleja_S0csg.gif" /></figure><h3>Don’t Stop Now! Keep Expanding Your Git Knowledge 🚀</h3><p>If you enjoyed this article and are eager to learn even more about Git, I have just the thing for you! Check out this other fantastic article written by the same author: <a href="https://medium.com/@thiagorodriguescenturion/how-to-have-multiple-git-accounts-on-the-same-computer-macos-e8921c5a691e">“How to Have Multiple Git Accounts on the Same Computer (macOS)”</a>.</p><p>This guide will walk you through setting up multiple Git accounts on your Mac, allowing you to juggle personal and professional projects with ease. So why wait? Click the link above and continue your journey toward Git mastery!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16451c8ae69f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to have multiple Git accounts on the same computer (MacOS)]]></title>
            <link>https://medium.com/@thiagorodriguescenturion/how-to-have-multiple-git-accounts-on-the-same-computer-macos-e8921c5a691e?source=rss-58faee355db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8921c5a691e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Thiago Centurion]]></dc:creator>
            <pubDate>Wed, 25 Aug 2021 23:54:48 GMT</pubDate>
            <atom:updated>2021-08-26T00:04:28.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9reT-NPzxA5DmL72MoIqiA.png" /><figcaption><a href="https://dzone.com/articles/git-vs-github-demystifying-the-differences">https://dzone.com/articles/git-vs-github-demystifying-the-differences</a></figcaption></figure><p>Are you working on a job project and would like to use the same computer to develop a personal project? Have you ever made commits to the job project with your personal git account or commits to the personal project with your job git account?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FcKKj5Ha18CX6eiORNS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcbc-schitts-creek-cKKj5Ha18CX6eiORNS&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2FcKKj5Ha18CX6eiORNS%2Fgiphy-downsized-large.gif%3Fcid%3D790b7611f3fb6cdeb8d5ca61ed36d51c6bde716b41c48628%26rid%3Dgiphy-downsized-large.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/097e65d672d6c2d4efd0899910fe3915/href">https://medium.com/media/097e65d672d6c2d4efd0899910fe3915/href</a></iframe><p>I was trying to keep developing to my job project (that is in GitLab Enterprise), making commits with my job git account, and have my Github personal account registered on my machine to do some personal projects sometimes. So I noticed that I can do that using SSH for both.</p><h3>Step 1. SSH key for the job account and the personal account</h3><p>I’m presuming that you already at least have a registered ssh key in your ~/.ssh directory for your work. Usually in an enterprise project, it has a specific constraint for creating a ssh key. Sometime it is a rsa 4096 or a ed25519 SSH keygen. So find out this information to create your job SSH key.</p><p>Otherwise, if both of projects doesn’t have this specific approach, you can follow just like below:</p><h4>Generate the SSH key for the first account</h4><pre>$ ssh-keygen -t rsa -C &quot;first.email@gmail.com&quot;</pre><p>When you write this command, a new SSH key will be generated and you are going to see something like that:</p><pre>Generating public/private rsa key pair.</pre><pre>Enter file in which to save the key (/Users/{YOUR_USER}/.ssh/id_rsa):</pre><p>If you already have an SSH key for your job account, so probably you already have a default filename just like id_rsa ou id_ed25519 . Here, don&#39;t worry about the name… usually people just use the default filename for job projects. But if you prefer to handle better your SSH keys, you can add a filename like id_rsa_&lt;project_name_here&gt; . For example, in this case, you just can write as below and press enter:</p><pre>/Users/{YOUR_USER}/.ssh/id_rsa_medium</pre><p>This is a real example, after writing it and pressing enter:</p><pre>Generating public/private rsa key pair.</pre><pre>Enter file in which to save the key (/Users/thiagocenturion/.ssh/id_rsa): /Users/thiagocenturion/.ssh/id_rsa_medium</pre><p>Then you’ll see a message like that:</p><pre>Enter passphrase (empty for no passphrase):</pre><p>Unless you want to add a custom passphrase, you can just press enter twice and your SSH will be correctly created in the directory that you just defined above. In my case, /Users/thiagocenturion/.ssh/id_rsa_medium.</p><pre>The key fingerprint is:<br>SHA256:qZw7BWqLWpAlbn1qhkuAPPBaKOqzAbf3vONZi2kLN/s first.email@gmail.com</pre><p>Store that key in where you can look at it again later. You have to register it in your job git account online.</p><h4>Generate the SSH key for the second account</h4><pre>$ ssh-keygen -t rsa -C &quot;second.email@gmail.com&quot;</pre><p>Now, you have to set up a different filename. This is <strong>important</strong> to avoid overriding the other key you just created. In my case, i just added the name id_rsa_personal :</p><pre>/Users/{YOUR_USER}/.ssh/id_rsa_personal</pre><p>Copy the public key to the clipboard:</p><pre>$ pbcopy &lt; ~/.ssh/id_rsa_personal.pub</pre><h3>Step 2. Save the SSH Key to the Git host</h3><p>Here, I&#39;m using Github.com, but it is probably almost the same steps for others git hosts.</p><ol><li>Go to Settings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*OZpPIYkmPGtNlmPY4kyxHA.png" /></figure><p>2. From the left side menu bar, click on SSH and GPG keys and click on New SSH key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*TioDNGCKwNUAekV8S4KjBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*LBvQ1afWlz7tDcBElnMnTQ.png" /></figure><p>3. Name it with a title. A good ideia is to add the computer name you&#39;re using, so in my case I titled it with that refers to my work&#39;s Macbook.</p><p>4. Paste the ssh public key you just copied with pbcopy &lt; ~/.ssh/... and press Add SSH key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*rw8fqxiNMK0POrjoa6vl3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*z86h6Jh8mkzUsm63UYENRA.png" /></figure><h3>Step. 3 Add an SSH agent</h3><p>In your Terminal (I like<a href="https://medium.com/@Clovis_app/configuration-of-a-beautiful-efficient-terminal-and-prompt-on-osx-in-7-minutes-827c29391961"> iTerm with zsh settings</a>, it&#39;s a personal suggestion), write ssh-add for each of the keys you created:</p><pre>$ ssh-add ~/.ssh/id_rsa_medium<br>$ ssh-add ~/.ssh/id_rsa_personal</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Cf4u2fKBxlKAuyu6ZZy0Ow.png" /></figure><h3>Step. 4 Config file for SSH keys</h3><p>By default, a config file doesn&#39;t exists. So we&#39;ll create it using touch ~/.ssh/config. Then, open it using any text editor (like Visual Studio Code) or vim editor. I created a shortcut to open any file in Visual Studio Code with an alias vscode.</p><pre>$ vscode ~/.ssh/config</pre><p>Add configuration for each git account you created SSH keys. By the first, you can do it for the work config adding this:</p><pre># Account 1 (work) - Medium <br>Host github.medium.com<br>   Hostname github.medium.com<br>   User git<br>   IdentityFile ~/.ssh/id_rsa_medium</pre><ul><li>You can add a comment using # to create a title for each configuration. I wrote Account 1 (work) — Medium just for an example, but you can write anything you want.</li><li>In <strong>Host</strong> and <strong>Hostname</strong> it&#39;s important to write the exact name which is defined in git repository when you click to clone it using SSH way. For example, if you are under an enterprise project for GitHub, probably this would be something like github.medium.com:</li></ul><pre>git clone git@github.medium.com:first.email/repository_name.git</pre><p>Then, add configuration for the personal account:</p><pre># Account 2 (personal) <br>Host github.com<br>   Hostname github.com<br>   User git<br>   IdentityFile ~/.ssh/id_rsa_personal</pre><p>And that you can save it and close the file.</p><h3>Step 5. Remote repository using SSH config</h3><p>Now you&#39;re one step closer to happiness: Everything you have to do is configuring the repository using SSH configuration.</p><p>Go to the repository page and click on Code &gt; Clone &gt; SSH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*Wf7neeSxgnHmjfvOdliR6A.png" /></figure><p>If you are going to create a new repository, use git remote add origin. Otherwise, if you already have a remote repository all you should do is to use git clone.</p><pre>$ git clone git@github.com:second.email/repo_name.git</pre><p>Now you have to associate your commits with the correct username (this is what we want first of all). To do that, go to the local repository for the job project and write your username and user e-mail using git config:</p><pre>$ git config user.name &quot;first.email&quot;<br>$ git config user.email &quot;first.email@gmail.com&quot;</pre><p>Once it is correctly set up, go to the personal local repository and write this:</p><pre>$ git config user.name &quot;second.email&quot;<br>$ git config user.email &quot;second.email@gmail.com&quot;</pre><p>That&#39;s all, we have it done! Even though it wasn&#39;t too detailed, I hope I could help you with this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8921c5a691e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>