<?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 Busayo Ajide on Medium]]></title>
        <description><![CDATA[Stories by Busayo Ajide on Medium]]></description>
        <link>https://medium.com/@busayoajide?source=rss-5bdd6863a18b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z3f4XlOcf-6Uydw2TeI0ww.jpeg</url>
            <title>Stories by Busayo Ajide on Medium</title>
            <link>https://medium.com/@busayoajide?source=rss-5bdd6863a18b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:49:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@busayoajide/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 to build a SwiftUI App with JSON, URLSession and SwiftData]]></title>
            <link>https://busayoajide.medium.com/how-to-build-a-swiftui-app-with-json-urlsession-and-swiftdata-d02c881236db?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d02c881236db</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Sat, 23 Dec 2023 05:40:35 GMT</pubDate>
            <atom:updated>2023-12-23T05:40:35.251Z</atom:updated>
            <content:encoded><![CDATA[<p>A HackingWithSwift Challenge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2d4P7HCrZNIyZ3R" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Let’s get right to it!</p><p>At Day 60 of 100 of the SwiftUI series, the challenge is straight-forward and two fold:</p><ol><li>Build an app that uses URL Session to get randomly generated user data from the web and display that as a list. Also include a detail view to show more information about each user on your list. <a href="https://www.hackingwithswift.com/100/swiftui/60"><em>More details here</em></a><em>.</em></li><li>Extend the app to use SwiftData i.e upgrade your Structs to Models and write custom Codable implementations. <a href="https://www.hackingwithswift.com/100/swiftui/61"><em>More details here.</em></a></li></ol><h4>Getting to Work</h4><p>The <a href="https://www.hackingwithswift.com/samples/friendface.json">data</a> is a relatively simple json file containing an array of people, and each person has an ID, name, age, email address, and more. They also have an array of tag strings, and an array of friends, where each friend has a name and ID.</p><p>Getting the data into SwiftUI meant creating Structs for User and Friend that the information can be parsed into. The Friend Struct was relatively easy as that only has two properties ID and name. The User Struct is also relatively straightforward except it also has an array of the Friend struct.</p><p>The Structs also need to conform to the Codable and Identifiable Protocols.</p><p>Next is setting up the views; one to show a list of all the users and a detail view to show more information about each user</p><h4>Solution 1 — Getting the app to work with a downloaded JSON file</h4><p>I initially misread/understood the first challenge and went ahead to download the data into my XCode project and tried to get the app to work. Instead of two separate Structs, I nested the Friend struct inside of the User struct. I created a new swift file called User.swift and added the following code. The variable names in the json file are exactly the same in the Struct and because they match with Swift’s naming convention, no additional work is required to get them to decode properly.</p><pre>struct User: Codable, Identifiable {<br>    struct Friend: Codable, Identifiable {<br>        let id : String<br>        let name: String<br>    }<br>    <br>    let id : String<br>    let isActive : Bool<br>    let name : String<br>    let age : Int<br>    let company : String<br>    let email : String<br>    let address : String<br>    let about : String<br>    let registered : Date<br>    let tags : [String]<br>    let friends : [Friend]<br>    <br>    var formattedRegisteredDate: String {<br>        registered.formatted(date: .abbreviated, time: .omitted)<br>    }<br>}</pre><p>To decode the data from the downloaded json file I also created another swift file called Bundle-Decodable.swift with the following code. Most of this is exactly the same as the original lesson from the 100DaysOfSwiftUI course on <a href="https://www.hackingwithswift.com/100/swiftui/40"><em>Day 40.</em></a></p><pre>extension Bundle {<br>    func decode(_ file: String) -&gt; [User] {<br>        guard let url = self.url(/service/forresource: file, withExtension: nil) else {<br>            fatalError(&quot;Failed to locate \(file) in bundle.&quot;)<br>        }<br>        <br>        guard let data = try? Data(contentsOf: url) else {<br>            fatalError(&quot;Failed to load \(file) from bundle.&quot;)<br>        }<br>        <br>        let decoder = JSONDecoder()<br>        decoder.dateDecodingStrategy = .iso8601 <br>        <br>        guard let loaded = try? decoder.decode([User].self, from: data) else {<br>            fatalError(&quot;Failed to decode \(file) from bundle.&quot;)<br>        }<br>        <br>        return loaded<br>    }<br>}</pre><p>To test that the json is properly decoded and I had access to all the user information, I added this code to my content view. This returned a plain screen with “100” which is the total no of users in the json file.</p><pre>struct ContentView: View {<br>    let users = Bundle.main.decode(&quot;friendface.json&quot;) // use to load json from file<br>    <br>    var body: some View {<br>        Text(&quot;\(users.count)&quot;)<br>    }<br>    <br>}</pre><p>Now that the json file and data have successfully been loaded and decoded, I updated my ContentView to show a list of all the users and their active status using <strong>Navigation Stack</strong> and <strong>List</strong>. I want each user to be tappable for further information so I used a <strong>Navigation Link</strong> as well.</p><pre>struct ContentView: View {<br>    let users = Bundle.main.decode(&quot;friendface.json&quot;) // use to load json from file<br>    <br>    var body: some View {<br>        NavigationStack{<br>            List{<br>                ForEach(users, id: \.id) { user in<br>                    NavigationLink{<br>                       // more code to come<br>                    }label:{<br>                        HStack{<br>                            Text(user.name)<br>                            Spacer()<br>                            Text(user.isActive ? &quot;Active&quot; : &quot;Not Active&quot;)<br>                        }<br>                    }<br>                }<br>            }<br>            .navigationTitle(&quot;FriendFace&quot;)<br>        }<br>    }<br>    <br>}</pre><figure><img alt="XCode Simulator View of List of users from json file" src="https://cdn-images-1.medium.com/max/1024/1*iz2Zx7wb2J-OdU8Z6k51ng.png" /><figcaption>XCode Simulator View of List of users from json file</figcaption></figure><p>The next step was to add a Detail view so that when each user is tapped more information is presented. I created a new SwiftUIView file called UserView.swift and added the following code.</p><pre>struct UserView: View {<br>    let user : User<br>    <br>    var body: some View {<br>        NavigationStack{<br>            VStack(alignment: .leading, spacing: 5) {<br>                <br>                VStack(alignment: .leading) {<br>                    Section(&quot;Bio&quot;) {<br>                        Text(&quot;Status: \(user.isActive ? &quot;Active&quot; : &quot;Not Active&quot;)&quot;)<br>                        Text(&quot;Join date: \(user.formattedRegisteredDate)&quot;)<br>                        Text(&quot;Company: \(user.company)&quot;)<br>                        Text(&quot;Email: \(user.email)&quot;)<br>                    }<br>                }.padding()<br>                <br>                VStack(alignment: .leading) {<br>                    Section(&quot;Friends : \(user.friends.count)&quot;) {<br>                        ForEach(user.friends){ friend in<br>                            Text(friend.name)<br>                        }<br>                    }<br>                }.padding()<br>                <br>            }<br>            .navigationTitle(user.name)<br>            .padding()<br>        }<br>    }<br>}</pre><p>To navigate to this view from the ContentView I updated the navigation link and replaced <strong>// more code to come</strong> with this line of code</p><pre>NavigationLink{<br>    UserView(user: user)<br>}</pre><figure><img alt="XCode Simulator Detailed user view for ‘Alford Rodriguez’" src="https://cdn-images-1.medium.com/max/1024/1*ykfyLNtccmhYjt0o_as10Q.png" /><figcaption>XCode Simulator Detailed user view for ‘Alford Rodriguez’</figcaption></figure><p>And we’re done! Not quite — but the basic components of the app are in place. We’ve mapped our JSON to SwiftUI Structs and successfully parsed the information, we have a list of users and we can get detailed information for each user by tapping their name.</p><p>Next we need to update the code to use <strong>URLSession</strong> to fetch the data from the web instead of using the downloaded file.</p><p><strong>Solution 2 — Using URL Session</strong></p><p>Now that I know I can decode the information from the json file, all I need to do is have SwiftUI point to a different location for the information. In this case, the internet. This means I’ll be using URLSession and I no longer need my Bundle-Decodable.swift file.</p><p>This requires only two changes. First I need to add a variable to store the array of users when it’s downloaded and secondly I need a function to download the data. To accomplish the first I change the code <strong>let user : User</strong> to a state variable and to accomplish the second, I add the <strong>downloadJson</strong> function to ContentView and a <strong>task</strong> modifier to the <strong>List </strong>right after the <strong>navigationTitle </strong>modifier.</p><pre>struct ContentView: View {<br>    @State private var users = [User]()<br><br>    var body: some View {<br>        NavigationStack{<br>            List{ <br><br>            /// more code here<br>     }<br>    .navigationTitle(&quot;FriendFace&quot;)<br>    .task{<br>      await downloadJson()<br>    }<br>  }<br>}<br>    func downloadJson() async {<br>        <br>        guard let url = URL(string: &quot;https://www.hackingwithswift.com/samples/friendface.json&quot;) else {<br>            fatalError(&quot;Invalid URL.&quot;)<br>        }<br>        <br>        let decoder = JSONDecoder()<br>        decoder.dateDecodingStrategy = .iso8601<br>        <br>        do {<br>            let (data, _) = try await URLSession.shared.data(from: url)<br>            if users.isEmpty {<br>                guard let decodedResponse = try? decoder.decode([User].self, from: data) else {<br>                    fatalError(&quot;Failed to decode data.&quot;)<br>                }<br>                users = decodedResponse<br>            }<br><br>        } catch {<br>            fatalError(&quot;Failed to decode data.&quot;)<br>        }<br>    }<br>}</pre><p>With these changes, the app works exactly the same except now it gets the data from the web using URLSession instead.</p><p>The next and dare I say greatest challenge is to upgrade it all to use SwiftData instead.</p><p><strong>Solution 3 — Updating to SwiftData</strong></p><p>Updating the app to use SwiftData includes more than a few steps and I ran into quite a bit of challenges but in retrospect seems relatively simple. Here’s what I did :</p><ol><li>First I separated the Friend Struct from the User Struct and created a new Friend.swift file.</li><li>Then I changed the Structs to Classes and added Model notations. I also added an import statement for SwiftData into each file. I still needed the User and Friend model to be Codable but since I’m using SwiftData, I could remove the Identifiable keyword because SwiftData models already conform to that protocol. Adding Codable to the models means writing custom Codable implementation code which you can read more about <a href="https://www.hackingwithswift.com/guide/ios-swiftui/5/2/key-points">here</a>. This is what the final User and Friend Models look like in swift.</li></ol><pre>import Foundation<br>import SwiftData<br>import SwiftUI<br><br>@Model<br>class User: Codable {<br>    <br>    let id : String<br>    let isActive : Bool<br>    let name : String<br>    let age : Int<br>    let company : String<br>    let email : String<br>    let address : String<br>    let about : String<br>    let registered : Date<br>    let tags : [String]<br>    let friends : [Friend]<br>    <br>    var formattedRegisteredDate: String {<br>        registered.formatted(date: .abbreviated, time: .omitted)<br>    }<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case isActive<br>        case name<br>        case age<br>        case company<br>        case email<br>        case address<br>        case about<br>        case registered<br>        case tags<br>        case friends<br>    }<br>    <br>    required init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        self.id = try container.decode(String.self, forKey: .id)<br>        self.isActive = try container.decode(Bool.self, forKey: .isActive)<br>        self.name = try container.decode(String.self, forKey: .name)<br>        self.age = try container.decode(Int.self, forKey: .age)<br>        self.company = try container.decode(String.self, forKey: .company)<br>        self.email = try container.decode(String.self, forKey: .email)<br>        self.address = try container.decode(String.self, forKey: .address)<br>        self.about = try container.decode(String.self, forKey: .about)<br>        <br>        let stringRegistered = try container.decode(String.self, forKey: .registered)<br>        self.registered = ISO8601DateFormatter().date(from: stringRegistered) ?? Date.distantPast<br>        <br>        self.tags = try container.decode([String].self, forKey: .tags)<br>        self.friends = try container.decode([Friend].self, forKey: .friends)<br>    }<br>    <br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(self.id, forKey: .id)<br>        try container.encode(self.isActive, forKey: .isActive)<br>        try container.encode(self.name, forKey: .name)<br>        try container.encode(self.age, forKey: .age)<br>        try container.encode(self.company, forKey: .company)<br>        try container.encode(self.email, forKey: .email)<br>        try container.encode(self.address, forKey: .address)<br>        try container.encode(self.about, forKey: .about)<br>        try container.encode(ISO8601DateFormatter().string(from: self.registered), forKey: .registered)<br>        try container.encode(self.tags, forKey: .tags)<br>        try container.encode(self.friends, forKey: .friends)<br>    }<br>}</pre><pre>import Foundation<br>import SwiftData<br>import SwiftUI<br><br>@Model<br>class Friend: Codable {<br>    let id : String<br>    let name: String<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case name<br>    }<br>    <br>    required init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        self.id = try container.decode(String.self, forKey: .id)<br>        self.name = try container.decode(String.self, forKey: .name)<br>    }<br>    <br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(self.id, forKey: .id)<br>        try container.encode(self.name, forKey: .name)<br>    }<br>    <br>    <br>}</pre><p>3. Next I updated the views to point to the SwiftData models for information. First I added an import statement for SwiftData to each view file. Next I added the following single extra line of code inside the UserView struct and that was all the change that was required there.</p><pre>@Environment(\.modelContext) var modelContext</pre><p>For the ContentView, I replaced the state variable with the following lines inside the view struct. The body variable remains exactly the same.</p><pre>@Environment(\.modelContext) var modelContext<br>@Query var users : [User]</pre><p>Next, since I still need the app to first download the data from the web but this time load the information into the SwiftData model, I replaced the <strong><em>do</em></strong> block inside the <strong>downloadJson</strong> function to this. The rest of the code block stayed the same.</p><pre> func downloadJson() async {<br>        <br>        // more code here<br>        <br>        do {<br>            let (data, _) = try await URLSession.shared.data(from: url)<br>            if users.isEmpty {<br>                guard let decodedResponse = try? decoder.decode([User].self, from: data) else {<br>                    fatalError(&quot;Failed to decode data.&quot;)<br>                }<br>                try? modelContext.delete(model: User.self)<br>                for user in decodedResponse {<br>                    modelContext.insert(user)<br>                }<br>            }<br><br>        // more code here<br>    }</pre><p>4. The final step was to update the App.Swift file, my app is called FriendFace so in my case that would be the FriendFaceApp.swift. First I added an import statement for SwiftData and next I added a <strong>modelContainer </strong>modifier to the WindowGroup like this</p><pre>@main<br>struct FriendFaceApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        // comment out if not using swift data<br>        .modelContainer(for: User.self)<br>    }<br>}</pre><p><strong>That’s it!</strong> With these changes, the app works! It’s exactly the same UI and nothing has changed visually from Solution 1 to 3 but the data is now being called from SwiftData instead after the initial download.</p><p><strong>Conclusion</strong></p><p>We did it! We built an app that loads data from the web, saves that information in a SwiftData model and then presents it to the user. Going the long way around to solving this challenge definitely made it more manageable in my opinion. I’m still new to SwiftUI but I’m relatively certain that each of the solutions above are key foundations for app development and any app developer to have.</p><p>In retrospect it all seems quite straight forward and since I’m writing this a few days after the fact, I don’t remember most/all of the challenges I faced trying to build this app. For example it took me a few days to figure out the right changes I need to make in the <strong>downloadJson</strong> function to pass the decoded data into the <strong>modelContext</strong> for SwiftData. Turns out it was just three lines of code! I also haven’t fully screened for bugs which probably exist.</p><p>Overall, the original challenge requirements have been met and I can see a few options to extending the app like adding sorting / filtering capabilities plus making it a little more visually appealing.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d02c881236db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple app in SwiftUI]]></title>
            <link>https://busayoajide.medium.com/a-simple-app-in-swiftui-5f718e9fefa8?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f718e9fefa8</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 05:36:55 GMT</pubDate>
            <atom:updated>2023-12-02T05:36:55.367Z</atom:updated>
            <content:encoded><![CDATA[<p>A HackingWithSwift Challenge</p><figure><img alt="XCode screenshot for MultiplyWithMe" src="https://cdn-images-1.medium.com/max/1024/1*x5CRvqHlirYs5-WSnxNAoA.png" /><figcaption>XCode screenshot for MultiplyWithMe</figcaption></figure><h4>Introduction</h4><p>By day 35 of the 100DaysOf SwiftUI course after learning things like animation and styling in SwiftUI, we’re challenged to build an edutainment(Education + entertainment) app from scratch. The challenge was simple enough — <strong><em>build an “edutainment” app for kids to help them practice multiplication tables — “what is 7 x 8?” and so on.</em></strong></p><p>Breaking it down:</p><ul><li>The player needs to select which multiplication tables they want to practice. This could be pressing buttons, or it could be an “Up to…” stepper, going from 2 to 12.</li><li>The player should be able to select how many questions they want to be asked: 5, 10, or 20.</li><li>You should randomly generate as many questions as they asked for, within the difficulty range they asked for.</li></ul><p>Full challenge details can be found <a href="https://www.hackingwithswift.com/guide/ios-swiftui/3/3/challenge"><strong>here</strong></a><strong>.</strong></p><p>My approach to solving this challenge was two part-</p><ol><li>Make it functional</li><li>Make it pretty</li></ol><p><em>Disclaimer — I’m completely aware there are probably smarter ways to solve this challenge i.e there’s a high chance this code is ugly.</em></p><h4>Make it functional</h4><p>My first goal was to make sure the app works and completes the challenge requirements at a minimum. Function over Form was my motto here. The main components I chose achieve this were to collect information from the user using</p><ul><li><strong>Stepper</strong> — for which multiplication table they want to practice between 2 and 12.</li><li><strong>Picker</strong> — for how many question they wanted to practice</li><li><strong>TextField</strong> — for answers one at a time</li></ul><p>The following block of code shows how all of this is written in Swift. There are two <strong>VStack</strong>s nested in a third <strong>VStack</strong>. The first nested <strong>VStack</strong> contains the code for user settings and the second nested <strong>VStack</strong> contains the question and a <strong>TextField</strong> to input answers.</p><p><strong>Important note:</strong> The code represented here excludes the functionality to process answers and is just to show the basic components of the app. The full code block for variables et al is on GitHub and linked below.</p><pre>var body: some View {<br>     NavigationStack{<br>         VStack{<br>                VStack{<br>                      Text(&quot;Score - \(score)&quot;)<br><br>                       Text(&quot;Choose a times table between 2 and 12&quot;)<br>                        <br>                       Stepper(&quot;\(noToMultiply)&quot;, value: $noToMultiply, in: 2...12, step:1)<br><br>                       Text(&quot;How many practice questions do you want?&quot;)<br><br>                       Picker(&quot;&quot;, selection: $question){<br>                            ForEach(questions, id:\.self) {<br>                                Text(&quot;\($0)&quot;)<br>                              }<br>                          }<br>                       }<br>                    <br>                 VStack(spacing: 15) {<br><br>                       Text(&quot;What is \(noToMultiply) x \(number) ?&quot;)<br>                        <br>                       TextField(&quot;Answer&quot;, value: $answer, format: .number)<br>                <br>                       Text(&quot;\(count) of \(question) questions answered&quot;)                        <br>                        <br>                       Button(&quot;Start Over&quot;){<br>                             // enter button action<br>                       }<br>                   }<br>               }<br>               .navigationTitle(&quot;MultiplyWithMe&quot;)<br>               .padding()<br>           }<br>       }</pre><p>Visually this is how that looks. Quite ordinary and honestly unattractive. Plus it doesn’t work just yet.</p><figure><img alt="SwiftUI view of Edutainment app components" src="https://cdn-images-1.medium.com/max/1024/1*0qNS2dIsbaq3RJI8m4ffQA.png" /><figcaption>SwiftUI view of Edutainment app components</figcaption></figure><p>To process the responses and get a fully functional app, I added the following modifiers to the <strong>TextField</strong>, an action when the <strong>Button</strong> is clicked as well as the necessary functions to check the answer, ask a new question or restart the game.</p><pre>TextField(&quot;Answer&quot;, value: $answer, format: .number)<br>      .onSubmit{checkAnswer()}<br>      .alert(alertTitle, isPresented: $showingScore){<br>            Button(&quot;Continue&quot;, action: askQuestion)<br>      } message: {<br>           Text(alertMessage)<br>      }<br>      .alert(&quot;Game Over&quot;, isPresented: $restartGame){<br>           Button(&quot;Play Again&quot;, action: restart)<br>      } message: {<br>          Text(&quot;Your Final Score is \(score)/\(question)&quot;)<br>      }<br><br>Button(&quot;Start Over&quot;){<br>      restart()<br>       }<br><br>func checkAnswer(){<br>        correctAnswer = noToMultiply * number<br>        if answer == correctAnswer {<br>            score += 1<br>            alertTitle = &quot;Good Job!&quot;<br>            alertMessage = &quot;That is correct.&quot;<br>            <br>            animationAmount = 360.0<br>            animateIcon.toggle()<br>        } else {<br>            alertTitle = &quot;Uh Oh!&quot;<br>            alertMessage = &quot;The correct answer is \(correctAnswer).&quot;<br>        }<br>        showingScore = true<br>        count += 1<br>    }<br>    <br>    func askQuestion(){<br>        correctAnswer = 0<br>        answer = 0<br>        if count &lt; question {<br>            number = Int.random(in: 0..&lt;15)<br>        }<br>        else {<br>            restartGame = true<br>        }<br>        <br>    }<br>    <br>    func restart() {<br>        score = 0<br>        count = 0<br>        answer = 0<br>        correctAnswer = 0<br>        askQuestion()<br>        }</pre><p>The UI looks exactly the same but now all the components of the app work. The user is able to -</p><ol><li>Select which multiplication table they want to practice ✅</li><li>Choose how many questions they want ✅</li><li>Answer the questions as they are asked and get presented with an alert whether the right or wrong ✅</li><li>The score gets updated and a final alert is presented when all the answers are asked with the option to play again ✅</li></ol><figure><img alt="SwiftUI View of completed Edutainment app with alert" src="https://cdn-images-1.medium.com/max/1024/1*CHGEsNC_xDav3H-ABnHSUw.png" /><figcaption>SwiftUI View of completed Edutainment app with alert</figcaption></figure><h4>Make it pretty</h4><p>I didn’t have any notion on what to make the app look like so this was mostly just a try-everything-until-it-looks-good approach. After some thought I decided I also wanted to add colors, animations and images at a minimum since we’d covered these topics in previous lessons. After some trial and error and feedback, the completed app looks like this.</p><figure><img alt="SwiftUI View of Edutainment App after some styling" src="https://cdn-images-1.medium.com/max/1024/1*vRAIACvLCxNBjcO6csPPgQ.png" /><figcaption>SwiftUI View of Edutainment App after some styling</figcaption></figure><p><strong>Steps</strong></p><ol><li>I wrapped the outer <strong>VStack</strong> in a <strong>ZStack</strong> to add the color in the background using <strong>LinearGradient</strong> and <strong>ignoreSafeArea()</strong> to extend to the edges of the screen.</li></ol><pre>ZStack{<br>      LinearGradient(colors: [.yellow, .pink], startPoint: .top, endPoint:.bottom)<br>                    .ignoresSafeArea()<br>      VStack {<br>          //more code here<br>    }<br>}</pre><p>2. I added the following modifiers to the first nested <strong>VStack</strong> to separate the settings from the answers. They change the font style of the text, width of the <strong>Stepper</strong> and <strong>Picker</strong> and add a background frame with some padding and rounded corners.</p><pre>VStack{<br>      Text(&quot;Score - \(score)&quot;)<br>          .font(.title).bold()<br>                        <br>      Spacer()<br><br>      Text(&quot;Choose a times table between 2 and 12&quot;)<br>          .font(.title3)<br>                        <br>      Stepper(&quot;\(noToMultiply)&quot;, value: $noToMultiply, in: 2...12, step:1)<br>          .frame(maxWidth: 150)<br>                        <br>      Spacer()<br>                    <br>      Text(&quot;How many practice questions do you want?&quot;)<br>         .font(.title3)<br>      Picker(&quot;&quot;, selection: $question){<br>          ForEach(questions, id:\.self) {<br>                Text(&quot;\($0)&quot;)<br>               }<br>      }<br>      .pickerStyle(.segmented)<br>      .frame(maxWidth: 200)<br>   }<br>   .frame(maxWidth: .infinity)<br>   .padding(.vertical, 25)<br>   .background(.regularMaterial)<br>   .clipShape(.rect(cornerRadius: 20))</pre><p>3. I downloaded and added images from <a href="https://kenney.nl/assets/animal-pack-redux">Kenny’s Animal Pack</a> (a public domain) and only used a handful in the app. To make it fun the app loads a new image for each question and the image does a 3D rotation on the y-axis when the answer is correct.</p><pre>VStack (spacing: 15) {<br>Image(icons[number])<br>     .rotation3DEffect(<br>            .degrees(animateIcon ? animationAmount : 0.0),axis: (x: 0.0, y: 1.0, z: 0.0)<br>        )<br>     .animation(.default, value: animateIcon)<br><br>//more code here<br>}</pre><p>4. I added the following modifiers to the rest of the second nested <strong>VStack </strong>to style the <strong>TextField</strong>, font colors and <strong>Button.</strong></p><pre>VStack(spacing: 15) {<br>        //Image code here<br>        <br>        Text(&quot;What is \(noToMultiply) x \(number) ?&quot;).font(.title2).bold()<br>                        <br>        TextField(&quot;Answer&quot;, value: $answer, format: .number)<br>              .foregroundStyle(answer == correctAnswer ? .black : .red)<br>              .textFieldStyle(.roundedBorder)<br>              .onSubmit{checkAnswer()}<br>              .frame(maxWidth: 200)<br>              .alert(alertTitle, isPresented: $showingScore){<br>                    Button(&quot;Continue&quot;, action: askQuestion)<br>               } message: {<br>                    Text(alertMessage)<br>               }<br>               .alert(&quot;Game Over&quot;, isPresented: $restartGame){<br>                    Button(&quot;Play Again&quot;, action: restart)<br>               } message: {<br>                    Text(&quot;Your Final Score is \(score)/\(question)&quot;)<br>               }<br>                       <br>                        <br>       Text(&quot;\(count) of \(question) questions answered&quot;)<br>             .fontWeight(.medium)<br>                        <br>                        <br>       Button(&quot;Start Over&quot;){<br>             restart()<br>       }<br>       .padding()<br>       .background(.green)<br>       .fontWeight(.bold)<br>       .clipShape(.capsule)<br>   }<br>   .foregroundStyle(.white)<br></pre><p>5. Finally, I played around with and added <strong>Spacer()</strong> in various places to adjust the position of the various components till I was satisfied.</p><p><strong>Challenges</strong></p><ol><li><strong>Image sizing </strong>— At the time of this challenge, we hadn’t learned how to properly size images in SwiftUI so after a quick google search and failed attempt, I decided to use the images in their default size. The implication is for every new image, the remaining components on the screen move around to accommodate the change in image size. Not a deal breaker, but also not ideal.</li><li><strong>Animations</strong> — It took me a while to figure out exactly how to get the animations working and while I also wanted to add an additional animation if the answer was wrong, I didn’t quite figure it out and so I chose to change the font color of the answer to red instead if the user entered the wrong answer.</li><li><strong>Duplicates — </strong>The current version of this app has no way to safeguard against asking the same question more than once as it simply chooses a random number each time between 0 and 15. So if the user were to choose 20 as the number of questions to practice, duplicates are inevitable. This is quite annoying and I know this is probably a relatively simple problem to fix but as at the time of writing this article it exists. (This is true for the image displayed as well because it uses the same number.)</li></ol><h4>Make it better</h4><p>In addition to fixing the issues above to make this app better, a couple of ideas to extend the app include:</p><ol><li>Adding difficulty levels — for example an <strong>easy</strong> level could be simply asking the user to multiply from 1 through 20 depending on how many questions they want while <strong>medium</strong> or <strong>hard</strong> level could present random numbers starting from a higher range instead.</li><li>Buttons — as suggested in the full challenge details, switching out the Stepper with colorful Buttons.</li><li>Animations — adding a different animation if the answer is wrong for example as a reduced image size or fade out.</li></ol><h4>Code</h4><p>The full code for this project is located here on <a href="https://github.com/beethedev/100DaysOfSwiftUI/tree/main/Challenge2-Edutainment/Edutainment">Github</a></p><p>If you got this far, I would love to hear your thoughts, recommendations and ideas on this app. Please leave a comment. Thank you and Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f718e9fefa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forms in SwiftUI]]></title>
            <link>https://busayoajide.medium.com/forms-in-swiftui-49fc417f537f?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/49fc417f537f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 23:37:07 GMT</pubDate>
            <atom:updated>2023-11-05T23:37:07.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Type here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eIGHaeCB0mUeLc7y" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Forms are very useful and make up parts of most apps that we use. Any screen/view or user interface that requests inputs from a user for example is built using a form. Adding a form component to your app view in SwiftUI is simple. For example, this code generates a simple form to collect user name and email address —</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>        @State private var name = &quot;&quot;<br>        @State private var email = &quot;&quot;<br>            <br>            var body: some View {<br>                <br>                NavigationStack{<br>                    Form {<br>                        Section(&quot;About&quot;){<br>                            <br>                            TextField(&quot;Name&quot;, text: $name)<br>                            Text(name)<br>                            TextField(&quot;Email address&quot;, text: $email)<br>                            Text(email)<br><br>                        }<br>                        .navigationTitle(&quot;User Info&quot;)<br>                    }<br>                }<br>        }<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96Q9GE7jDM4YI1NvQ1dF_g.png" /><figcaption>User Info Form in Xcode Simulator</figcaption></figure><p>The <strong>TextField</strong> keyword allows the user to input some information and the <strong>Text</strong> keyword is used to display text for the user to read; in this case the same name and email the user just typed as it is saved by the code. In the image above the placeholder text <em>“Name”</em> and <em>“Email address”</em> show the user exactly what information goes where. The blank rows are for the <strong>Text</strong> keyword to display information back to the user.</p><p>A few things to note about the block of code above —</p><ol><li><strong>“@State”</strong> is used to tell Swift that you want to watch your view to update certain variables for example if there are any changes. In this case you would like Swift to update the variables <strong>name and email</strong> that are initially set to empty strings with whatever the user types in.</li><li>The <strong>$</strong> in front of name and email in the <strong>Textfield</strong> keyword. This tells Swift that when the user provides this information it should update the variables in memory accordingly. You can see it in action in the <strong>Text</strong> field since this will automatically show what Swift has in memory for those variables.</li></ol><p>This is a very simple form. It only shows how you would collect and display information back to a user and would accept whatever is typed in even if it&#39;s gibberish.</p><p>Forms can be used to collect all sorts of data and ideally you want to validate and/or restrict the type of information collected. For example when asking for date of birth, you wouldn’t want someone typing February 30th or if you asked for a phone number you will want to make sure only a certain no of digits can be entered and definitely no text. There are different ways to do just that in Swift and you can go <a href="http://www.hackingwithswift.com/">here</a> to learn more.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49fc417f537f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optionals in Swift]]></title>
            <link>https://busayoajide.medium.com/optionals-in-swift-f006c42a5c91?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f006c42a5c91</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 00:07:06 GMT</pubDate>
            <atom:updated>2023-10-31T00:07:06.246Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What is nothing?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WT57u9ruOxdbDo6a" /><figcaption>Photo by <a href="https://unsplash.com/@honeypoppet?utm_source=medium&amp;utm_medium=referral">Sandie Clarke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Programming languages all have to deal with no value and/or missing data. Usually the user gets to decide what that should mean and how to address it. In Swift, you can have no data mean exactly that and Swift will understand. This is basically what Optionals are; they are data that may or may not exist until you check. For example an Optional string could be a string that says “Hello”, “Yes”, “ ”(i.e empty string) or <strong>nil</strong> — meaning it doesn’t exist. Optionals are not restricted to Strings, they are also applicable to Int, Bool, Double and instances of Structs, Enums or Classes.</p><p>An optional type in Swift is denoted using a <strong>? </strong>after the type<strong> </strong>e.g <strong>String?</strong> denotes an optional string, <strong>Int?</strong> an optional integer, <strong>[Double]?</strong> an optional array of doubles. Here’s a simple dictionary in Swift.</p><pre>var dtypes = [&quot;Int&quot;: &quot;Integers&quot;, &quot;Double&quot;: &quot;Decimals&quot;, &quot;String&quot;: &quot;Words&quot;]<br><br>let boolean = dtypes[&quot;Bool&quot;]</pre><p>If I wanted to look up the key “Bool” and assign that to the constant boolean, it will return <strong>nil</strong> because “Bool” does not exist in the dytpes dictionary and I didn’t provide a default value to return. Since a key may or may not exist in a dictionary, looking up keys in a dictionary will always return an optional.</p><p>Writing code in Swift means you need some method for handling situations where a value may or may not exist. There are a number of ways to unwrap optionals (i.e safely check if an optional contains a real value or <strong>nil</strong>) in Swift such as —</p><ol><li><strong>if let</strong> — this tells Swift to run some code if after unwrapping the optional it has a value. For example I can check the dictionary dtypes for “Int”. In this case the code will unwrap my optional and assign that to the constant <strong>int</strong>.</li></ol><pre>if let int = dtypes[&quot;Int&quot;] {<br>    print(&quot;Int means \(int)&quot;)<br>} </pre><p>I can also add an else block if I want to like this. Notice that since I am checking for “Bool” which does not exist, the else statement is executed instead.</p><pre>if let boolean = dtypes[&quot;Bool&quot;] {<br>    print(&quot;Bool means \(boolean)&quot;)<br>} else {<br>    print(&quot;Bool does not exist in dtypes&quot;)<br>}</pre><p>2. <strong>guard let</strong> — This is the opposite of <strong>if let</strong>, it is used to run some code if the optional has no value when it is unwrapped. When using <strong>guard</strong>, Swift requires you to use <strong>return </strong>if the check fails. If the optional has a value, you can use it only after the guard code is finished.</p><pre>func tvShow(name: String?) -&gt; String {<br>    guard let name = name else {<br>        return &quot;Missing input&quot;<br>    }<br><br>   return &quot;The name of your favourite tv show is \(name)&quot;<br>}</pre><p><strong>3. nil coalescing</strong> — This allows you to provide a default value if you are checking if an optional exists or not so you always return a non optional type. So if we were to use it on the dtypes dictionary for example it would look like this:</p><pre>let boolean = dtypes[&quot;Bool&quot;] ?? &quot;N/A&quot;</pre><p>The <strong>?? </strong>after the code tells Swift that if the optional has no value it should return the default value in this case <strong>“N/A”</strong>. Nil coalescing can be very useful in many places where an optional can be created.</p><p>There’s a lot more to optionals like optional chaining and optional try. Optionals can be tough to get a handle on, read about them some more <a href="https://www.hackingwithswift.com/100/swiftui/14">here</a>. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f006c42a5c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures in Swift]]></title>
            <link>https://busayoajide.medium.com/closures-in-swift-f9d653689f9c?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d653689f9c</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 04:26:14 GMT</pubDate>
            <atom:updated>2023-10-25T04:26:14.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Why???</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6qBGu1fYGbEf4aFS83P0Q@2x.jpeg" /><figcaption>Photo by Mathew Schwartz on Unsplash</figcaption></figure><p>Let me start by stating the obvious. I cannot explain the entirety of what closures are in a 2 minute read and you’ll see why soon. Now, functions are cool, powerful and versatile so why do we need closures? Apparently they are very useful and appear all over the place in SwiftUI. So what’s the deal with closures then? Well, here’s how I understand them right now.</p><p>When you assign a function’s function (what the function does) to a variable without creating the function (i.e using keyword ‘func’), that’s a closure! See, confounding. Let me explain what I mean.</p><p>Say I have a function that calculates the sum of two numbers and returns a string telling you if it’s even or odd, I could write that like this</p><pre>func evenOrOdd(no1:Int, no2:Int) -&gt; String {<br>   if (no1 + no2).isMultiple(of: 2){<br>       return (&quot;\(no1 + no2) is even&quot;)<br>   } else {<br>       return (&quot;\(no1 + no2) is odd&quot;)<br>   }<br>}<br><br>evenOrOdd(no1: 3, no2: 5) //calling the function will return &quot;8 is even&quot;</pre><p>If I wanted to make this a closure instead of a function that means I could take all that information and assign to a variable like this and that’s a closure.</p><pre>let evenOrOddClosure = {(no1: Int, no2:Int) -&gt; String in<br>    if (no1 + no2).isMultiple(of: 2){<br>        return (&quot;\(no1 + no2) is even&quot;)<br>    } else {<br>        return (&quot;\(no1 + no2) is odd&quot;)<br>    }<br>}<br><br>evenOrOddClosure(3,5) //using this closure will also return &quot;8 is even&quot;</pre><p>Notice the main differences between the two blocks of code</p><ol><li>Everything is included in the braces { }. Closures require you to contain all your code inside them including parameters and whatever type of data you want to return.</li><li>The keyword <strong>‘in’ -</strong> this is how Swift is able to tell where your parameters and return type end and where the ‘function’ or code doing the work begins. Without it Swift will not build your code.</li></ol><p>Now why would we need to something as convulated as closures when the function worked just fine and is much easier to read and understand? Well there are a number of very good reasons and I’m still working on totally understanding them well enough to explain myself but until then read more <a href="https://www.hackingwithswift.com/100/swiftui/9">here</a>. Happy Coding!</p><p>#Day9of100 #HackingWithSwift #SwiftUI #LearningToCode</p><p><em>P.S I’m still learning about closures so if I’m wrong and you have a simpler explanation please let me know.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d653689f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing functions in Swift]]></title>
            <link>https://busayoajide.medium.com/writing-functions-in-swift-0aafd74c5738?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aafd74c5738</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 00:26:55 GMT</pubDate>
            <atom:updated>2023-10-23T00:26:55.934Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>func</strong> theBasics()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUzFPhKdhglLANsh" /><figcaption>Photo by <a href="https://unsplash.com/@framesforyourheart?utm_source=medium&amp;utm_medium=referral">Frames For Your Heart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Simply put, functions are best used to write code that you would like to use multiple times. Basically if you would need to write the same lines in more than one place in your code you should consider making it a function. The simplest reason for this is that you would avoid making mistakes that come with copying and pasting or forgetting to update the code in all the places they appear if you decide to make a change.</p><p>So how would you write a function in Swift and what would that look like practically? There are a few key things to remember for a basic function.</p><ol><li>Use the keyword ‘<strong>func</strong>’ to let Swift know you are writing a function</li><li>You need to name your function; ideally some name that is self explanatory as to what your function does</li><li>Include parentheses () after your function name and</li><li>Braces { } to contain the body of your function i.e the code that your function executes.</li></ol><p>Here’s a simple function using the 4 points above -</p><pre>func welcomeNote() {<br>    print(&quot;Hello there!&quot;)<br>    print(&quot;Welcome to my medium post&quot;)<br>}<br><br>welcomeNote() //This is how to call the function above</pre><p>You may want your function to accept parameters and do something with that or what if your function needs to perform some calculation and return the answer so you can pass that to another function? You would need just a little more than the four points above.</p><p>Here’s a simple function that calculates the circumference of a circle.</p><pre>func circumference(radius: Double) -&gt; Double{<br>    return 2*3.14*radius<br>}<br><br>circumference(radius: 3.0)</pre><p>Let’s go over how this function is different from the welcomeNote() function.</p><ol><li>First, you will notice that there’s new information inside the parentheses after the function name. In this case <strong><em>radius:Double</em></strong><em>. </em>This tells Swift that I want to pass a value of type <strong>Double</strong> called <strong>radius</strong> to the function since I need it inside the function body contained in the braces { }.</li><li>Secondly, I have also added ‘<strong>-&gt; Double</strong>’ to let Swift know that I want it to return a value of datatype Double when the function is run. You may notice that when you call the welcomeNote() function it does not return the print statements inside the function body and that’s because you haven’t told Swift to do that.</li><li>Finally inside the function body is the keyword ‘<strong>return</strong>’. This simply tells Swift that when this function is called, it should return the result. So when the final line of code <strong><em>circumference(radius: 3.0)</em></strong> executes the value <strong>18.4</strong> is returned.</li></ol><p>These are just the basics about functions in Swift. Functions are powerful, help you write fewer lines of code and can be used in very many different ways. You can read more about them <a href="https://www.hackingwithswift.com/100/swiftui/7">here</a>. Happy Coding!</p><p>#Day7of100</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aafd74c5738" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loops in Swift]]></title>
            <link>https://busayoajide.medium.com/loops-in-swift-2cdaab36732f?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cdaab36732f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 03:59:19 GMT</pubDate>
            <atom:updated>2023-10-22T03:59:19.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>Do it again and again and again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yglhrPg2it8BlntcO_Ry6Q@2x.jpeg" /><figcaption>Photo by Tine Ivanič on Unsplash</figcaption></figure><p>The great thing about writing computer programs is that you can pass off repetitive tasks so that you don’t have to do them yourself. ‘<strong>For</strong>’ and ‘<strong>While</strong>’ loops in Swift allow you to do just that for as long as you like.</p><p><strong>For</strong> loops are used when you want to run a particular command a known number of times for example to iterate over a list. Say I want to go over the names in an array and extract all names that start with the letter ‘B’. I could use a for loop like so -</p><pre>var names = [&quot;Ariel&quot;, &quot;Jasmine&quot;, &quot;Mulan&quot;, &quot;Belle&quot;, &quot;Elsa&quot;, &quot;Tiana&quot;, &quot;Rapunzel&quot;]<br>var bNames = [String]()<br>for name in names{<br>    if name.hasPrefix(&quot;B&quot;){<br>       bNames.append(name) <br>    }<br>print(bNames)<br>}</pre><p>Suppose I want to randomly select integers in a range and stop only when I select a particular no, in that case a <strong>while</strong> loop would serve me better. <strong>While</strong> loops are used when you don’t know how many times you need to run a command in advance.</p><pre><br>var selected = 35<br>var values = [Int]()<br>while selected != 40 { <br>    selected = Int.random(in:1...250)<br>    values.append(selected)<br><br>print(&quot;40 has been selected after \(values.count) tries&quot;)<br>}<br></pre><p>The first time I ran the code above, the number 40 was selected after 213 tries, the second time 151 tries and 419 tries the third time. I could not have predicted the no of tries in advance and this is why it’s a good use of while loops.</p><p>Swift also lets you interrupt or exit your loop prematurely if you want. For example if I wanted the while loop to stop running after a certain number of tries? You can use the <em>break</em> or <em>continue</em> keywords for just this purpose and you can read all about them <a href="https://www.hackingwithswift.com/quick-start/beginners/how-to-skip-loop-items-with-break-and-continue">here</a>. Happy Coding!</p><p>#LearnToCode #SwiftUI #Swift #Day6of100</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cdaab36732f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write if statements in Swift]]></title>
            <link>https://busayoajide.medium.com/what-if-61d4b9c8363b?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d4b9c8363b</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 01:18:50 GMT</pubDate>
            <atom:updated>2023-10-21T01:25:50.771Z</atom:updated>
            <content:encoded><![CDATA[<h2>How to write If statements in Swift</h2><h3>What if….</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKJe_TVrNw2fGk-24R_HWA@2x.jpeg" /><figcaption>Photo by Vadim Bogulov on Unsplash</figcaption></figure><p>If statements are exactly what they sound like – what if something happened? What next? What if it didn’t happen, what then? How do you write all of that in Swift? It’s simple really, for example -</p><pre>let somethingHappened = false <br><br>if somethingHappened {<br>  print(“it really happened”) <br>} else {<br>  print(“it didnt happen”)<br>}<br><br>// running this code will print the second statement “it didnt happen” because somethingHappened is false</pre><p>It can get a little more complicated if you want to check multiple things (conditions) at once for example -</p><pre>var check = false<br>var check2 = true<br><br>if check { <br>  print (“check passed”)<br>} else if check2 {<br>  print (“check2 passed instead”)<br>} else {<br>  print (“check and check2 failed”)<br>}<br><br>//you can write as many ‘else if’ as you want but must have only one ‘if’ <br>//and one or no ‘else’ for each if statement<br></pre><p>It is important to note that swift will exit the <em>if statement</em> as soon as it passes the first true condition. For instance, in the example above the final <em>else</em> statement is not checked because the <em>else if </em>condition passed and so the code “check2 passed instead” was executed.</p><p>Nesting multiple else ifs in one if statement block while possible can get convoluted and make your code harder to read and more susceptible to errors so Swift has something called <em>switch statements</em> to help combat this issue. You can read more about them <a href="https://www.hackingwithswift.com/quick-start/beginners/how-to-use-switch-statements-to-check-multiple-conditions">here</a>.</p><p>Happy Coding!!</p><p>#Day5of100 #LearnToCode #SwiftUI #ifStatements #100DaysOfSwift</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d4b9c8363b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data types in Swift]]></title>
            <link>https://busayoajide.medium.com/data-types-in-swift-33967225bfc5?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/33967225bfc5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 22:29:10 GMT</pubDate>
            <atom:updated>2023-10-19T22:29:10.375Z</atom:updated>
            <content:encoded><![CDATA[<h3>When and how to use them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1teHYATa9SjKJPlnehkDQ@2x.jpeg" /><figcaption>Photo by Pawel Czerwinski on Unsplash</figcaption></figure><p>Swift is the programming language used for applications that run on Apple devices from iOS to tvOS. As a beginner coder in any programming language it is important to understand data types, what they do, when and how to use them. Here are some of the data types in Swift.</p><ul><li>Int – Integers are used to denote/store whole numbers of any size both negative and positive.</li><li>Double – Doubles are used to store decimals of any size.</li><li>String – Strings are used to denote and store text data.</li><li>Boolean – Booleans are used to store true or false values.</li><li>Enum – Enums (enumerations) are swifts way of letting you create your own data types. It’s kind of like booleans but lets you have more than two options and you choose what those are. It’s especially useful when you have a fixed list of possible options that will not change. For example if you wanted to create a variable for days of the week or months in the year.</li><li>Array – Arrays hold many values, in a particular order and can contain duplicate values.</li><li>Dictionary – D/ictionaries also let you store many values in key: value pairs allowing you access the contents using the keys and finding values faster than in arrays.</li><li>Sets – Sets like arrays and dictionaries can store a lot of values but have the advantage of being unordered and cannot have duplicates allowing swift store the data efficiently and making accessing its contents very fast.</li></ul><p>Swift lets you store data either as variables (meaning you can change the value anytime ) or constants (meaning you cannot change the value after it’s created). Whichever you choose would depend on your use case. You can create variables and constants using <em>var</em> and <em>let</em> keywords respectively for example:</p><pre>var language = “swift”<br>let version = 15<br><br>//if i want to change the value of language all i simply need to do is write this <br><br>language = “not swift”<br><br>//if i try to change version however swift won’t allow that because its a constant</pre><p>It is important to note that Swift must always know what type of data is stored in a variable. While I did not specify the data type for language and version, Swift through <em>type inference</em> knows to assign them <strong><em>String</em></strong> and <em>Int</em> respectively. There are cases where this is just fine but sometimes you may want to be specific (<em>type annotation</em>) and tell Swift what you want for example :</p><pre>var celsius : Double = 16<br><br>//Here swift knows even though I have written it like an integer that what I really <br>//want is a decimal and stores celsius as 16.0 without me having to be explicitThere’s not a single way to write good code as personal styles vary. </pre><p>Here’s how to explicitly declare the other data types in Swift</p><pre>var number: Int = 10<br>var temperature : Double = 16<br>var someText : String = “swift”<br>var isLoggedIn: Bool = true<br>var someArray: [String] = [“red”, “yellow”, “blue”]<br>var someDictionary: [String:Int] = [“red”:1, “yellow”:2, “blue”:3]<br>var someSet: Set&lt;String&gt; = Set([“red”, “yellow”, “blue”])<br><br>enum Direction {<br>	case north<br>    case east<br>    case south<br>    case west<br>}</pre><p>Personally, I lean more towards type inference because I find it easier to read and perhaps because I’m also a python programmer. There’s no single right way so long as you understand the concepts and when to use them to avoid unintended consequences. Happy coding!</p><h3>References</h3><p><a href="https://www.hackingwithswift.com/quick-start/beginners/how-to-use-type-annotations">100DaysOfSwiftUI</a></p><p>#Day4of100 #SwiftUI #DataTypes #LearnToCode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33967225bfc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Froggy didn’t go on mute]]></title>
            <link>https://busayoajide.medium.com/froggy-didnt-go-on-mute-4a5064928cc6?source=rss-5bdd6863a18b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5064928cc6</guid>
            <dc:creator><![CDATA[Busayo Ajide]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 19:44:19 GMT</pubDate>
            <atom:updated>2023-10-18T19:44:19.901Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hablas Español?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jXss0vDD294C7NBexLOyg.jpeg" /><figcaption>My infant and his laptop</figcaption></figure><p>Recently I found myself wondering how easy it would be for a native French speaker to learn Spanish. You see, my kid has a toy laptop which among many songs <em>(my favourite song is ‘Froggy didn’t go on mute’)</em> also teaches colors, numbers and alphabets in Spanish. I took a few french lessons as a kid and I thought I could hear some similarities between numbers in French and Spanish whenever he’s playing with the laptop and the sounds inevitably come out.</p><p>Today’s lesson was about more data types in Swift specifically <em>Arrays, Dictionaries, Sets and Enums</em>. As I went through the lesson I started to draw similarities between Swift and Python. Now I’m not comparing both languagues but having prior experience with Python made grasping these concepts faster. First off, they are really easy concepts to get but it didn’t feel like I was learning how to write a whole new language with its own syntax et al once I figured out —</p><ol><li>Arrays are basically Lists,</li><li>Dictionaries are the same as Dicts with Key:Value pairs,</li><li>Sets are.. let’s be honest even on my best days I didn’t really get sets in python but now I do and guess what they mostly work the same way.</li><li>Enums are a little different and while I don’t know a Python parallel if it does exist, I do appreciate them and am looking forward to using them some more.</li></ol><p>It was also nice to know that each of these data types had similar methods that I was familiar with in python. All in all a good day to learn something new!</p><p>#Day3of100 #SwiftUI #LearnToCode #Python #HackingWithSwift</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5064928cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>