<?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 Jimmy chao on Medium]]></title>
        <description><![CDATA[Stories by Jimmy chao on Medium]]></description>
        <link>https://medium.com/@myname90196?source=rss-1814435be66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wulpH7s9JvZFlGlyS3D69Q.jpeg</url>
            <title>Stories by Jimmy chao on Medium</title>
            <link>https://medium.com/@myname90196?source=rss-1814435be66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:16:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myname90196/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[Drinks on me(Part one)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/drinks-on-me-part-one-92f1e8aae509?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f1e8aae509</guid>
            <category><![CDATA[booking-app]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kebuke]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 05:11:21 GMT</pubDate>
            <atom:updated>2023-08-27T05:11:21.372Z</atom:updated>
            <content:encoded><![CDATA[<p>For my final iOS training project, I’ve developed an app for booking drinks. Simple idea, right? But there’s a lot more to it. It’s more than just ordering a drink; there are some nuances and cool features to explore. Let’s dive in and see what it’s all about. Ready?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*LyXR_lUXCnm4d_wn_ykPvA.png" /><figcaption>Yes, we’re going to build an app to book drinks from kebuke.</figcaption></figure><h3>Requirement</h3><ul><li>Be able to add drinks</li><li>Be able to choose drinks</li><li>Be able to add your name to the order</li><li>Has sweetness option</li><li>Has temperature option</li><li>Has size option</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*iiem8ehKZLb6rUBhlb2OYQ.gif" /><figcaption>Demonstration</figcaption></figure><h3>Topic</h3><ul><li>What’s escaping</li><li>Table view reload</li><li>Sort parameter</li><li>Auto update</li><li>Return to fold the keyboard</li></ul><h3>What’s escaping</h3><p>What on earth is escaping? Who are we running from? I tried to connect to the endpoint API with a function. This function takes in a closure which will give me the access to decide what to do with the fetched data. But if I run the function without adding @escaping then Swift will complain loudly.</p><p>Now, here’s where the concept of escaping comes in. In Swift, when we pass a closure as an argument to a function and that closure is called <strong>after</strong> the function returns, we label it as escaping. Why? Because it &quot;escapes&quot; the function it was passed to. Say we’re making an API call: the function we use to initiate that call finishes its job way before the server responds. If we want to do something with the server&#39;s response, that action (represented by the closure) has to &quot;live on&quot; or &quot;escape&quot; beyond the lifetime of the initial function call. By marking a closure with the @escaping syntax, we’re essentially saying: &quot;Hey, this closure might be called sometime in the future, Be ready!&quot;</p><pre>// MARK: - Fetch and unwrap API<br><br>/// Fetches the order details from a specified API endpoint.<br>/// - Parameter completion: A completion handler that is triggered after fetching data, <br>///   passing the parsed `ResponseRoot` object as a parameter.<br>func fetchOrder(_ completion: @escaping ((_ fetchedOrderRoot:ResponseRoot) -&gt; Void)){<br>    <br>    // Define the endpoint URL string.<br>    let urlStr = &quot;https://api.airtable.com/v0/appN21f5f7mgnzUIi/order&quot;<br>    if let url = URL(string: urlStr){<br>        <br>        // Create a URLRequest object with the specified URL.<br>        // The cache policy is set to ignore local cache, ensuring fresh data is always fetched.<br>        var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)<br>        <br>        // Specify that the request method is &quot;GET&quot;.<br>        urlRequest.httpMethod = &quot;GET&quot;<br>        <br>        // Set the authorization header with the bearer token.<br>        // Note: It&#39;s crucial to keep tokens like this secret in a real-world application.<br>        urlRequest.setValue(&quot;Bearer patVvuJLhCGDlIA5N.bb43e3d5bf2d60015a897eff3ed89c044143a0c5fc967a59bcb9d20d8cc5043a&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        <br>        // Create a URLSession data task with the request.<br>        URLSession.shared.dataTask(with: urlRequest) { data, _, _ in<br>            // Check if data is received from the API.<br>            if let data = data {<br>                let decoder = JSONDecoder()<br>                // Uncomment below if you need to decode dates in ISO8601 format.<br>                //decoder.dateDecodingStrategy = .iso8601<br>                <br>                do {<br>                    // Decode the received data into a `ResponseRoot` object.<br>                    let orderRoot = try decoder.decode(ResponseRoot.self, from: data)<br>                    <br>                    // Switch to the main thread, as UI changes should be made on the main thread.<br>                    DispatchQueue.main.async {<br>                        <br>                        // Pass the decoded `ResponseRoot` object to the completion handler.<br>                        completion(orderRoot)<br>                        <br>                        // Uncomment below if you want to update some UI components.<br>                        //self.resultRecords = responseRecords<br>                        //self.tableView.reloadData()<br>                    }<br>                    <br>                } catch  {<br>                    // Print any decoding errors.<br>                    print(error)<br>                }<br>            }<br>        }.resume() // Start the URLSession data task.<br>    }<br>}</pre><h3>TableView.reload and reloadRows</h3><p>I came across situations where I need to update the content displayed in a UITableViewa lot. The UITableView offers few methods to reload its content, but the two most commonly used are tableView.reloadData() and tableView.reloadRows(at:with:). Let&#39;s dive into the nuances of each.</p><ol><li>tableView.reloadData()</li></ol><ul><li>Purpose: It’s the go-to method when we want to reload all the rows in the table view.</li><li>Performance: Depending on the size of our data source, this method can be heavy because it dequeued all current cells and re-queries all the cells and sections.</li><li>Use case: In the updateOrders function, after fetching the order data, the entire table view is reloaded. This ensures all rows reflect the most recent data.</li></ul><p>2. tableView.reloadRows(at:with:)</p><ul><li>Purpose: This method is more targeted and allows us to reload specific rows in the table view. It’s ideal for scenarios where only a few rows need updating, leaving the rest untouched.</li><li>Performance: Typically more efficient than reloadData(), especially when the table view has many rows and only a subset needs refreshing.</li><li>Use case: In the reviseOrder function, when the order of a specific row is revised, only that particular row is refreshed. This method provides a smoother user experience.</li></ul><p>So that sounds easy enough. But I still manage to spend half a day on it somehow… In short, use TableView.reload when the table is short and simple. Use TableView.reloadRows when the table is long and complex.</p><pre>@IBAction func reviseOrder(_ sender: UIStepper) {<br>    <br>        print(sender.value)<br>        <br>        let point = sender.convert(CGPoint.zero, to: inlineTableView)<br>            if let indexPath = inlineTableView.indexPathForRow(at: point),<br>               let originalCup = orderRoot?.records[indexPath.row].fields.cups {<br>                <br>                <br>                // Update local data source<br>                patchInfo.cups = originalCup + Int(sender.value)<br>                <br>                orderRoot?.records[indexPath.row].fields.cups = patchInfo.cups<br>                <br>                // Reload the specific row with animation<br>                inlineTableView.reloadRows(at: [indexPath], with: .automatic)<br><br>                // Fetch the record ID to be revised<br>                let reviseID = orderRoot?.records[indexPath.row].id<br>                recordsToRevise = reviseID<br>                reviseRecord()<br>            }<br>        sender.value = 0<br>        <br>        calculateSum()<br>    }</pre><pre>@objc func updateOrders() {<br>    <br>    //Call the &#39;fetchOrder&#39; method to retrieve order data.<br>    fetchOrder { fetchedOrderRoot in<br>        <br>        //Once the fetch is complete, assign the fetched data to the &#39;orderRoot&#39; property of the current object.<br>        self.orderRoot = fetchedOrderRoot<br>        <br>        //Perform a UI animation block to reload the tableView data.<br>        UIView.transition(with: self.inlineTableView,<br>                          duration: 0.4,<br>                          options: .transitionCrossDissolve,<br>                          animations: { <br>                              // Within the animation block, reload the tableView data.<br>                              self.inlineTableView.reloadData() <br>                          })<br>    }<br>    <br>    //After fetching the order and updating the tableView, recalculate the total sum.<br>    calculateSum()<br>}</pre><h3>Sort parameter</h3><p>The query parameter. These are the key-value pairs we’ll often spot in a URL, typically coming after a ? and separated by &amp; symbols. They allow us to refine our requests, fetching data to our special needs.</p><p>Here, the query parameters sort[0][field] and sort[0][direction] are being used to dictate how the fetched data should be sorted. The former specifies the field we&#39;re sorting by (defaulting to &quot;tag&quot;), while the latter tells us the direction of the sort.</p><p>Here’s a portal to airtable rest API documentation.</p><p><a href="https://airtable.com/appN21f5f7mgnzUIi/api/docs#curl/table:order:list">Airtable | Everyone&#39;s app platform</a></p><pre>let urlStr = &quot;https://api.airtable.com/v0/appN21f5f7mgnzUIi/menu?sort%5B0%5D%5Bfield%5D=\(sortField)&amp;sort%5B0%5D%5Bdirection%5D=\(sortDirection)&quot;</pre><pre>// MARK: - API Integration<br><br>func fetchData(sortField:String = &quot;tag&quot;, sortDirection:String = &quot;asc&quot;) {<br><br>    // Construct the API endpoint URL string with provided sort field and direction.<br>    let urlStr = &quot;https://api.airtable.com/v0/appN21f5f7mgnzUIi/menu?sort%5B0%5D%5Bfield%5D=\(sortField)&amp;sort%5B0%5D%5Bdirection%5D=\(sortDirection)&quot;<br>    if let url = URL(string: urlStr) {<br>        <br>        // Initialize a URLRequest object with the URL.<br>        var urlRequest = URLRequest(url: url)<br>        <br>        // Set the HTTP method to GET since we are fetching data.<br>        urlRequest.httpMethod = &quot;GET&quot;<br>        <br>        // Set the Authorization header with the bearer token for API authentication.<br>        urlRequest.setValue(&quot;Bearer patVvuJLhCGDlIA5N.bb43e3d5bf2d60015a897eff3ed89c044143a0c5fc967a59bcb9d20d8cc5043a&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        <br>        // Start a data task to fetch data from the API.<br>        URLSession.shared.dataTask(with: urlRequest) { data, _, _ in<br>            <br>            // Check if data was received from the API.<br>            if let data = data {<br>                <br>                // Create a JSONDecoder object to decode the received data.<br>                let decoder = JSONDecoder()<br>                <br>                // Attempt to decode the received data into the &#39;SearchRoot&#39; model.<br>                do {<br>                    let searchRecords = try decoder.decode(SearchRoot.self, from: data)<br>                    <br>                    // If decoding is successful, update the UI on the main thread.<br>                    DispatchQueue.main.async {<br>                        // Assign the decoded data to the &#39;resultRecords&#39; property.<br>                        self.resultRecords = searchRecords<br>                        <br>                        // Reload the tableView to reflect the fetched data.<br>                        self.tableView.reloadData()<br>                    }<br>                } catch {<br>                    // If decoding fails, print the error.<br>                    print(error)<br>                }<br>            }<br>            <br>        // Resume the data task. This actually starts the network request.<br>        }.resume()<br>    }<br>}</pre><h3>Auto update</h3><p>Okay, this one is a bit longer than I thought. The piece of code below showed a list of ordered items in the cart. But most importantly. This cart can update its content automatically. In the following code, we activate and deactivate a timer several times. Let me point it out for ya.</p><p>In viewDidLoad We schedule a timer to repeatedly call the updateOrders method every 10 seconds. The purpose? To fetch the latest orders and update the UI seamlessly. This ensures that the user always sees the most up-to-date content without any manual intervention.</p><pre>updateTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateOrders), userInfo: nil, repeats: true)</pre><p>In the function updateOrders . It fetches the latest orders and then uses a cross-dissolve animation to update the table view.</p><pre>@objc func updateOrders() {<br>    fetchOrder { fetchedOrderRoot in<br>        self.orderRoot = fetchedOrderRoot<br>        UIView.transition(with: self.inlineTableView, duration: 0.4, options: .transitionCrossDissolve, animations: { self.inlineTableView.reloadData() })<br>    }<br>    calculateSum()<br>}</pre><p>In function viewDidAppear and viewDidDisappear . It’s essential to manage the timer’s lifecycle, ensuring they’re active only when needed. Hence, when our view appears (viewDidAppear), the timer starts, set to refresh every 10 seconds. But when the view disappears (viewDidDisappear), the timer is stopped. By disabling the timer, we ensure that it no longer fires, consumes resources, and prevents potential memory costs.</p><pre>// When the view appears, start the timer to fetch orders every 12 seconds.<br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        updateTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(updateOrders), userInfo: nil, repeats: true)<br>    }<br><br>    // When the view disappears, invalidate (stop) the timer to avoid unnecessary API calls.<br>    override func viewDidDisappear(_ animated: Bool) {<br>        super.viewDidDisappear(animated)<br>        updateTimer?.invalidate()<br>        updateTimer = nil<br>    }</pre><pre>// MARK: - CartViewController<br><br>import UIKit<br><br>// Define a view controller for the cart screen.<br>class CartViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {<br>    <br>    // Outlets for the UI elements.<br>    @IBOutlet var orderButton: UIButton!<br>    @IBOutlet var footerView: UIView!<br>    @IBOutlet var cartView: UIView!<br><br>    // Data properties to store information about the orders and other related data.<br>    var patchInfo = PatchInfo()<br>    var recordsToDelete: String?<br>    var recordsToRevise: String?<br>    var orderRoot: ResponseRoot?<br><br>    // Timer used to periodically fetch and update orders.<br>    var updateTimer: Timer?<br>    @IBOutlet var inlineTableView: UITableView!<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Set the background color for the UI elements.<br>        inlineTableView.backgroundColor = UIColor.init(red: 23/255, green: 61/255, blue: 80/255, alpha: 1)<br>        cartView.backgroundColor = inlineTableView.backgroundColor<br>        footerView.backgroundColor = inlineTableView.backgroundColor<br><br>        // Initialize a timer to fetch orders every 10 seconds.<br>        updateTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateOrders), userInfo: nil, repeats: true)<br><br>        // Fetch the initial order data when the view loads.<br>        fetchOrder { fetchedOrderRoot in<br>            self.orderRoot = fetchedOrderRoot<br>            print(&quot;\(String(describing: self.orderRoot))&quot;)<br>            self.inlineTableView.reloadData()<br><br>            // Calculate the total price of the orders.<br>            self.calculateSum()<br>        }<br>    }<br><br>    // Function to show an alert for confirming the order.<br>    func showAlert() {<br>        let alertController = UIAlertController(title: &quot;訂單確認&quot;, message: &quot;確定要撥打電話？&quot;, preferredStyle: .actionSheet)<br>        let callAlertAction = UIAlertAction(title: &quot;02-26562288&quot;, style: .default)<br>        let cancelAlertAction = UIAlertAction(title: &quot;Cancel&quot;, style: .destructive)<br><br>        alertController.addAction(callAlertAction)<br>        alertController.addAction(cancelAlertAction)<br><br>        present(alertController, animated: true)<br>    }<br><br>    // Action triggered when the order button is tapped.<br>    @IBAction func orderButton(_ sender: Any) {<br>        showAlert()<br>    }<br><br>    // Timer function to update orders periodically.<br>    @objc func updateOrders() {<br>        fetchOrder { fetchedOrderRoot in<br>            self.orderRoot = fetchedOrderRoot<br>            UIView.transition(with: self.inlineTableView, duration: 0.4, options: .transitionCrossDissolve, animations: { self.inlineTableView.reloadData() })<br>        }<br>        calculateSum()<br>    }<br><br>    // When the view appears, start the timer to fetch orders every 12 seconds.<br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        updateTimer = Timer.scheduledTimer(timeInterval: 12.0, target: self, selector: #selector(updateOrders), userInfo: nil, repeats: true)<br>    }<br><br>    // When the view disappears, invalidate (stop) the timer to avoid unnecessary API calls.<br>    override func viewDidDisappear(_ animated: Bool) {<br>        super.viewDidDisappear(animated)<br>        updateTimer?.invalidate()<br>        updateTimer = nil<br>    }<br><br>    // Function to calculate the total sum of the orders in the cart.<br>    func calculateSum() {<br>        let records = orderRoot?.records ?? []<br>        totalPrice = 0<br><br>        for record in records {<br>            let pricePerCup = record.fields.originPrice<br>            let cups = record.fields.cups<br>            totalPrice += pricePerCup * cups<br>        }<br>        orderButton.setTitle(&quot;Order for $ \(totalPrice)&quot;, for: .normal)<br>    }<br><br>    // Action to revise the number of items in an order.<br>    @IBAction func reviseOrder(_ sender: UIStepper) {<br>        // Logic to update the order based on the stepper value...<br>        // This logic finds the corresponding order in the table view and updates its quantity.<br>        // After updating, it sends a request to the server to revise the order.<br>    }<br><br>    // Function to send a PATCH request to revise an order&#39;s data.<br>    func reviseRecord() {<br>        // API logic to revise the record...<br>    }<br><br>    // Action to delete a specific order.<br>    @IBAction func deleteOrder(_ sender: UIButton) {<br>        // Logic to delete an order...<br>    }<br><br>    // Function to send a DELETE request to remove an order.<br>    func deleteRecord(at indexPath: IndexPath) {<br>        // API logic to delete the record...<br>    }<br><br>    // MARK: - Table View Data Source and Delegate<br><br>    // Define the number of sections in the table view.<br>    func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        return 1<br>    }<br><br>    // Define the number of rows in a section.<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return orderRoot?.records.count ?? 20<br>    }<br><br>    // Define the cell for a specific row.<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: CartTableViewCell.reuseIdentifier, for: indexPath) as? CartTableViewCell else { fatalError(&quot;unable to find cell&quot;) }<br><br>        // Configure the cell based on the data...<br>        <br>        return cell<br>    }<br>}</pre><h3>Return to fold the keyboard</h3><p>To use this delegate function within the controller. It must conform the UITextFieldDelegate protocol. Then we will be able to access a function call textFieldShouldReturn which lets us dictate what additional action we want to perform when the return key is pressed. In our case we want the current active text field to be deactivated.</p><pre>class DetailTableViewController: UITableViewController,UITextFieldDelegate{ <br>.<br>.<br>.<br>}<br></pre><pre>    // MARK: - implement text field delegate function<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        textField.resignFirstResponder()<br>        return true<br>    }</pre><h3>Conclusion/ GIT</h3><p>Oh man, this project is something else! Don’t get me wrong, I’m totally vibing with the process. But wow, I’ve thrown in every trick I’ve got to build this app, and it feels so dang satisfying!</p><p><a href="https://github.com/JimmyChao90196/Drinks-on-me.git">GitHub - JimmyChao90196/Drinks-on-me</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f1e8aae509" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/drinks-on-me-part-one-92f1e8aae509">Drinks on me(Part one)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#51 Movie trailer list (Marvel vs DC)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/movie-trailer-list-marvel-vs-dc-d2295d6c80af?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2295d6c80af</guid>
            <category><![CDATA[table-view-controller]]></category>
            <category><![CDATA[type-casting]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[delegate]]></category>
            <category><![CDATA[datasource]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 13:28:16 GMT</pubDate>
            <atom:updated>2023-08-12T04:45:38.021Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s project, I’ll be showing you guys this movie trailer list. There are of course few bumps along the way. And I show you the subjects one by one. And let’s jump right in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*3Z1Iq0Xz9NOCUnqLi43IBQ.gif" /><figcaption>Demonstration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*LFHyLy96fIMtKZ-FXN3jOQ.png" /><figcaption>Page demo, more pages in the app.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-sOLsaF_Ne5bJDW45yNbA.png" /><figcaption>Layout</figcaption></figure><h3>Topic</h3><ul><li>as syntax explain</li><li>Self. self syntax explain</li><li>Data source and delegate in tableViewController</li><li>Mark syntax</li></ul><h3>As syntax explain</h3><p>The following piece of code is my configuration of the tableView data source function And the configuration itself is not something worth noticing. The important part is as syntax.</p><p>As is typically used for typecasting. Whether it’s downcasting or upcasting we generally go for as syntax.</p><p>The method dequeueReusableCell(withIdentifier:for:) returns a cell of type UITableViewCell. But, we&#39;re currently working with is of type MovieTableViewCell (which is a subclass of UITableViewCell). So, you need to tell Swift, &quot;Hey, I know this is a UITableViewCell, but treat it as a MovieTableViewCell for me.&quot;</p><p>But why? you might ask. What’s the point of that?</p><p>By using as?, we are downcasting the UITableViewCell to a MovieTableViewCell. And that allows us to access properties and methods from MovieTableViewCell. We can now access moviePoster , movieTitle and all kinds of self-defined property from cell.</p><pre><br>   // This function determines the cell that should be displayed for each row in the table view.<br>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    <br>    // Dequeue a reusable cell of type &#39;MovieTableViewCell&#39;. This is an optimization technique where <br>    // the table view recycles the cells that have gone off screen instead of creating new ones.<br>     guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieTableViewCell.reuseIdentifier , for: indexPath) as? MovieTableViewCell else {<br>            fatalError(&quot;Unable to dequeue MovieTableViewCell&quot;)<br>        }<br>    <br>    // Variable to hold the movie details for the current row.<br>    var movie: film<br>    <br>    // Check the current value of &#39;genreIndex&#39; to determine which genre&#39;s movie details should be loaded.<br>    if genreIndex == 0 {<br>        movie = MarvelFilmInfo.movies[indexPath.row]<br>    } else {<br>        movie = DCFilmInfo.movies[indexPath.row]<br>    }<br>    <br>    // Assign movie details to the respective cell properties.<br>    cell.moviePoster.image = movie.image<br>    cell.movieTitle.text = movie.name + &quot; &quot; + String(movie.years)<br>    cell.movieDescription.text = movie.description<br>    cell.stars.text = movie.stars<br>    <br>    // Clear any previous cast<br>    cell.movieCast.text = &quot;&quot;<br>    <br>    // Assign cast member to the &#39;movieCast&#39; label.<br>    for cast in movie.cast {<br>        var castText = cell.movieCast.text ?? &quot;&quot;<br>        castText += &quot;&quot; + cast<br>        cell.movieCast.text = castText<br>    }<br>    <br>    // Configure the appearance of the cell background.<br>    cell.cellBG.backgroundColor = .lightGray<br>    cell.cellBG.alpha = 0.9<br>    cell.cellBG.layer.cornerRadius = 15<br>    cell.cellBG.layer.borderWidth = 1.5<br>    cell.cellBG.layer.borderColor = .init(gray: 1, alpha: 0.85)<br><br>    // Return the fully configured cell to be displayed in the table view.<br>    return cell<br>}<br><br></pre><h3>Self/ self/ extension</h3><pre>guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieTableViewCell.reuseIdentifier , for: indexPath) as? MovieTableViewCell else {<br>            fatalError(&quot;Unable to dequeue MovieTableViewCell&quot;)<br>        }</pre><pre>extension UITableViewCell {<br>    static var reuseIdentifier: String { &quot;\(Self.self)&quot; }<br>}</pre><p>If you’re too lazy to type anything without auto-completion. Using an extension will be a neat way to do it. But what the heck is Self.self</p><p>Self refers to the current type.</p><p>self accesses the type itself.</p><p>Alright, I know, still vague and ambiguous. Let’s go deeper.</p><blockquote>In Swift, Self is a special type that refers to the<strong> type </strong>of the current &quot;thing&quot; in which it&#39;s used. This &quot;thing&quot; can be a class, struct, or enum.</blockquote><blockquote>The .self syntax is used to refer to the type itself, rather than an instance of the type. You can think of .self as a way to get a reference to the type object.</blockquote><p>Wait what? I just made it worst? Okay, give me another chance.</p><blockquote>Self typically indicate the object’s own type. It’s a concept, you can’t touch it.</blockquote><blockquote>self typically refers to property that is within a type. It almost works like my in real-life English. So combine them both. Self.self is basically saying give me<strong> the type of mine!</strong></blockquote><p>Here are two examples to help you understand the concept.</p><pre>class Cake {<br>    var message: String<br>    <br>    init(message: String) {<br>        self.message = message<br>    }<br>    <br>    func displayMessage() {<br>        print(&quot;The message on this cake is: \(self.message)&quot;)<br>    }<br>}</pre><pre>class DigitalProduct {<br>    class func sampleProduct() -&gt; Self {<br>        return self.init()<br>    }<br>}<br><br>class eBook: DigitalProduct { }<br>class eCourse: DigitalProduct { }<br><br>let bookSample = eBook.sampleProduct()//Return eBook<br>let courseSample = eCourse.sampleProduct()//Resturn eCourse</pre><h3>Data source and delegate in tableViewController</h3><p>It’s actually linked up when it’s created for us. No need to worry about it.<br>Here, let me show you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7ZN8pknyv-ieWSVe2UGGA.png" /></figure><p>And also you might wonder. But I don’t see anything in my table view controller. So it just conforms to UITableViewDelegate and UITableViewDataSource by magic?</p><p>Of course not. The super-class of our tableViewController is conform to those things already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F1LMYAEBqOZ8fJ8HQnd7Q.png" /></figure><h3>Mark syntax</h3><p>I discover this by accident. It comes with the table view controller we created. The simple syntax makes our life easier than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8wub2FhoM6jNd9JbuqO2Q.png" /></figure><h3>Git</h3><p>Thank you all for reading this. I’ll be making another article just for delegates and data source. I’ve been a bit busy lately. But I promise I’ll be back soon.</p><p><a href="https://github.com/JimmyChao90196/Movie_Trailer.git">GitHub - JimmyChao90196/Movie_Trailer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2295d6c80af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/movie-trailer-list-marvel-vs-dc-d2295d6c80af">#51 Movie trailer list (Marvel vs DC)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[選擇題期中考]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E9%81%B8%E6%93%87%E9%A1%8C%E6%9C%9F%E4%B8%AD%E8%80%83-1f7d72a0fac6?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f7d72a0fac6</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[performsegue]]></category>
            <category><![CDATA[catmemes]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 14:21:11 GMT</pubDate>
            <atom:updated>2023-08-09T14:21:11.485Z</atom:updated>
            <content:encoded><![CDATA[<p>這次的app是一次期中考核，有點慚愧的做了一個中規中矩的app沒有太多創意。但是我其實是想要趕快做完考核後去摸索這個禮拜的delegate and table view. 總而言之，這次的app 其實跟上次的心理測驗很像，幾乎就是一個重複練習的項目了。</p><p>一樣在以下會說明遇到比較有趣的主題， let’s dive into it!</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/16-enum-switch-struct-psychological-test-846600f1705">#16 Enum/Switch/Struct (psychological test)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*PpqOI9tVmeKD5unJw2XCJA.gif" /><figcaption>選擇題</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWBySIxjWgL1guQvNE7EQw.png" /><figcaption>Overall pages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAxhx2Xl9EgtKSVhqotDqA.png" /><figcaption>Layout</figcaption></figure><h3>Requirement</h3><ul><li>製作選擇題 App，每題有四個選項。</li><li>答對一題加 10 分 。</li><li>畫面上顯示目前題目是第幾題。</li><li>自訂選擇題的資料型別。</li><li>題庫有 n 題，隨機出其中的 10 題。( n &gt; 10 )</li><li>每次玩的時候題目順序都不一樣。(ps: 進階版: 每次玩的時候題目順序跟選項順序都不一樣)</li><li>包含多個頁面，至少有問題頁面和分數頁面。</li><li>利用 IBSegueAction &amp; performSegue 將結果從問題頁傳到分數頁。</li><li>用 UIAlertController 顯示答對或答錯，答錯時在 alert 裡顯示正確答案。</li></ul><h3>Topic</h3><ul><li><a href="#99c3">Folder structure</a></li><li><a href="#ede2">Alert controller</a></li><li><a href="#ca12">Perform segue</a></li><li><a href="#0236">Shuffle the quizzes</a></li><li><a href="#d07c">Property observer</a></li><li><a href="#e4c2">Git</a></li></ul><h3>Folder structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*5jDupmUkrTokvYoxOsPXdQ.png" /><figcaption>MVC folder structure</figcaption></figure><h3>Alert controller</h3><p>When a player taps on any of the answer options, a pop-up alert immediately appears. The content of this alert varies based on whether the player’s answer is right or wrong. That’s where the ternary operator comes into play. It helps us quickly display what message to show.</p><p>And after the player has gone through 10 rounds of questions, a different kind of alert is shown. This one indicates that the game is over. That’s the reason behind the if statement; it distinguishes between regular feedback alerts and the game-over alert.</p><pre><br>import UIKit     <br>import Foundation   <br>import OSLog    <br><br><br>class QuestionViewController: UIViewController {<br><br>    // Create a Logger instance to handle logging messages<br>    let logger = Logger()<br>    <br>    // IBOutlets: Interface Builder references to link the UI elements from the storyboard to the code<br>    @IBOutlet var roundLabel: UILabel!       // Displays the current round number<br>    @IBOutlet var bgImage: UIImageView!       // Displays the background image<br>    @IBOutlet var scoreLable: UILabel!       // Displays the current score<br>    @IBOutlet var question: UILabel!         // Displays the quiz question<br>    @IBOutlet var quizImage: UIImageView!    // Displays the image related to the quiz question<br>    @IBOutlet var optionCollection: [UIButton]!  // Collection of buttons representing answer options<br>    <br>    // Variables declaration<br>    var quizzes = CatBreedsQuizData().quizzes  // Fetch the set of quizzes related to cat breeds<br>    var roundNum: Int = 0  // Keeps track of the current round number<br>    var answerDescribtion = &quot;&quot; // Stores the description for the answer<br>    var ansIndex = 0  // Stores the index of the correct answer<br>    var quizIndex = 0 // Keeps track of the current quiz&#39;s index<br>    var score: Int = 0 {  // Keeps track of the user&#39;s score<br>        didSet {  // Observer that watches for changes in the score variable<br>            scoreLable.text = &quot;Score: is now \(self.score)&quot; // Update score label when the score changes<br>            roundNum += 1   // Increment the round number by 1<br>            roundLabel.text = String(roundNum)  // Update the round label<br>        }<br>    }<br>    <br>    // This method is called when the view is loaded into memory but not yet displayed on screen<br>    override func viewDidLoad() {<br>        super.viewDidLoad() // Call the parent class&#39;s implementation of viewDidLoad<br>        <br>        // Initial setup<br>        roundNum = 0   // Reset round number<br>        score = 0     // Reset score<br>        quizzes.shuffle()   // Randomize the order of quizzes<br>        initializeQuiz()    // Setup the first quiz<br>    }<br>    <br>    // Function to initialize or reset the quiz UI elements<br>    func initializeQuiz() {<br>  <br>        // Set the question text and associated images<br>        question.text = quizzes[quizIndex].question<br>        quizImage.image = quizzes[quizIndex].picture<br>        bgImage.image = quizImage.image<br>        ansIndex = quizzes[quizIndex].correctAnswer<br>        answerDescribtion = quizzes[quizIndex].answerDescription<br>        <br>        // Adjust the appearance of images<br>        quizImage.contentMode = .scaleAspectFill   // Scale the image to fill its bounds<br>        bgImage.contentMode = .scaleAspectFill<br>        bgImage.layer.opacity = 0.5   // Set background image opacity to 50%<br>        <br>        // Set the options for the quiz<br>        let quizOptions = quizzes[quizIndex].options<br>        for (index, optionButton) in optionCollection.enumerated() {<br>            optionButton.setTitle(quizOptions[index], for: .normal)<br>        }<br>        scoreLable.text = &quot;Score is now \(score)&quot;<br>    }<br>    <br>    // Function called when any option (answer) button is pressed<br>    @IBAction func optionsPressed(_ sender: UIButton) {<br>        <br>        // Find the index of the pressed button in the options collection<br>        guard let selectedIndex = optionCollection.firstIndex(of: sender) else { return }<br>        <br>        // Check if the selected option is the correct answer<br>        let scoreOrNot = selectedIndex == ansIndex<br>        <br>        // Create an alert to provide feedback to the user<br>        let alertController = UIAlertController(title: &quot;&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>        <br>        // Check if the round number is less than 10<br>        if roundNum &lt; 10 {<br>            alertController.title = scoreOrNot ? &quot;Correct&quot; : &quot;Wrong&quot;<br>            alertController.message = answerDescribtion<br>            <br>            // Add a &quot;Next&quot; button to the alert which will load the next question<br>            alertController.addAction(.init(title: &quot;Next&quot;, style: .default, handler: { _ in<br>                self.quizIndex = (self.quizIndex % 14) + 1  // Update the quiz index for the next question<br>                <br>                // Update the score based on the correctness of the answer<br>                self.score = scoreOrNot ? self.score + 10 : self.score - 5<br>                <br>                // Load the next quiz<br>                self.initializeQuiz()<br>                <br>                // Log the current quiz index<br>                self.logger.info(&quot;\(self.quizIndex)&quot;)<br>            }))<br>        } else {<br>            // Set the alert title to &quot;Game Over&quot; if all rounds are finished<br>            alertController.title = &quot;Game Over&quot;<br>            alertController.message = answerDescribtion<br>            <br>            // Add a &quot;See result&quot; button to the alert which will navigate to the results screen<br>            alertController.addAction(.init(title: &quot;See result&quot;, style: .default, handler: { _ in<br>                self.performSegue(withIdentifier: &quot;showResult&quot;, sender: nil)<br>                <br>                // Update the score based on the correctness of the answer<br>                self.score = scoreOrNot ? self.score + 10 : self.score - 5<br>            }))<br>        }<br>        <br>        // Present the alert to the user<br>        self.present(alertController, animated: true)<br>    }<br>    <br>    // Function to handle the segue (transition) from this view to the `ScoreViewController`<br>    @IBSegueAction func segueTriggered(_ coder: NSCoder) -&gt; ScoreViewController? {<br>        <br>        // Instantiate the `ScoreViewController` and set its `resultScore` property to the current score<br>        let controller = ScoreViewController(coder: coder)<br>        controller?.resultScore = score<br>        <br>        return controller  // Return the instantiated `ScoreViewController` to complete the segue<br>    }<br>}</pre><h3>Perform segue</h3><p>This one is a bit tricky. Originally I tried to use didSet to trigger the performSegue function. But nothing happened. I am not sure why even now.</p><p>So here’s the answer GPT gave me.</p><blockquote>When you use the didSet observer of the score property to trigger an action (like performSegue), it&#39;s possible that the view controller&#39;s view hierarchy is not yet fully established or is in the middle of another transition. When you try to perform a segue in such situations, it might fail because the view is not in the correct state to initiate another transition or present another view controller.</blockquote><blockquote>On the other hand, when you use the alert’s action handler to trigger the performSegue, it means the alert has already been presented and the view hierarchy is stable. The alert is on top of the view hierarchy, and dismissing the alert provides a clear path for the segue to be performed.</blockquote><p>It’s said that I probably shouldn’t use perform segue when the UI element is changing or updating. In my case, I did change my UI element at the time which is showing an alert.</p><p><strong>Now that we know the problem, there’s an alternative solution below. Always check if the current view controller is loaded or in the middle of a transition.</strong></p><pre>if isViewLoaded &amp;&amp; view.window != nil {<br>    // Safe to perform segue or other UI actions<br>}</pre><pre>.<br>.<br>.<br>            <br>            // Add a &quot;See result&quot; button to the alert which will navigate to the results screen<br>            alertController.addAction(.init(title: &quot;See result&quot;, style: .default, handler: { _ in<br>                self.performSegue(withIdentifier: &quot;showResult&quot;, sender: nil)<br>                <br>                // Update the score based on the correctness of the answer<br>                self.score = scoreOrNot ? self.score + 10 : self.score - 5<br>            }))<br>        }<br>        <br>        // Present the alert to the user<br>        self.present(alertController, animated: true)<br>    }<br>.<br>.<br>.</pre><h3>Shuffle the quiz array</h3><p>One of the requirements of the test is to shuffle the quizzes each time the player plays.</p><p>My quiz array is an array of structs, created in the file question model. I love using an array or enum with a struct. It is extremely convenient when it comes to accessing certain topic-related data. In this case — cat’s quizzes.</p><pre>//Variables<br>var quizzes = CatBreedsQuizData().quizzes<br>var roundNum:Int = 0<br>var answerDescribtion = &quot;&quot;<br>var ansIndex = 0<br>var quizIndex = 0<br>var score:Int = 0{<br>    didSet{<br>            scoreLable.text = &quot;Score: is now \(self.score)&quot;<br>            roundNum += 1<br>            roundLabel.text = String(roundNum)<br>            //logger.info(&quot;\(self.roundNum)&quot;)<br>        }<br>    }<br>.<br>.<br>.    <br>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        roundNum = 0<br>        score = 0<br>        quizzes.shuffle()<br>        initializeQuiz()<br><br>        // Do any additional setup after loading the view.<br>    }</pre><pre><br>import Foundation<br>import UIKit<br><br>// Define a struct named `QuizInfo` to represent individual quiz questions.<br>struct QuizInfo {<br>    // A string that represents the question text.<br>    let question: String<br>    // An array of strings representing the possible answers.<br>    let options: [String]<br>    // An integer that represents the index of the correct answer within the `options` array.<br>    let correctAnswer: Int<br>    // An image associated with the quiz question.<br>    let picture: UIImage<br>    // A string that provides additional information about the answer.<br>    let answerDescription: String<br>}<br><br><br>// Define a struct named `CatBreedsQuizData` to represent a collection of `QuizInfo`.<br>struct CatBreedsQuizData {<br>    let quizzes: [QuizInfo] = [<br>        QuizInfo(question: &quot;Which country does the Abyssinian cat likely originate from?&quot;,<br>                 options: [&quot;Ethiopia&quot;, &quot;Egypt&quot;, &quot;Greece&quot;, &quot;United States&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.Abyssinian.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Abyssinian cat likely originates from Ethiopia.&quot;),<br>        <br>        QuizInfo(question: &quot;The Aegean cat comes from which country?&quot;,<br>                 options: [&quot;Egypt&quot;, &quot;Greece&quot;, &quot;United States&quot;, &quot;China&quot;],<br>                 correctAnswer: 1,<br>                 picture: UIImage(named: CatBreedPicture.Aegean.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Aegean cat originates from Greece.&quot;),<br>        <br>        QuizInfo(question: &quot;What&#39;s distinctive about the American Bobtail?&quot;,<br>                 options: [&quot;It has a long tail.&quot;, &quot;It originates from Greece.&quot;, &quot;It has a shortened tail.&quot;, &quot;It has a very long coat.&quot;],<br>                 correctAnswer: 2,<br>                 picture: UIImage(named: CatBreedPicture.AmericanBobtail.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The American Bobtail is known for its shortened tail.&quot;),<br>        <br>        QuizInfo(question: &quot;The American Curl is known for?&quot;,<br>                 options: [&quot;Curled ears&quot;, &quot;Short tail&quot;, &quot;Wavy coat&quot;, &quot;Size&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.AmericanCurl.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The American Curl is recognized by its unique curled ears.&quot;),<br>        <br>        QuizInfo(question: &quot;Which country does the American Ringtail originate from?&quot;,<br>                 options: [&quot;China&quot;, &quot;Egypt&quot;, &quot;Greece&quot;, &quot;United States&quot;],<br>                 correctAnswer: 3,<br>                 picture: UIImage(named: CatBreedPicture.AmericanRingtail.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The American Ringtail cat originates from the United States.&quot;),<br>        <br>        QuizInfo(question: &quot;What type is the American Shorthair?&quot;,<br>                 options: [&quot;Natural&quot;, &quot;Mutation&quot;, &quot;Hybrid&quot;, &quot;Crossbreed&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.AmericanShorthair.rawValue) ?? UIImage(systemName: &quot;photo&quot;) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The American Shorthair is of the Natural type.&quot;),<br>        <br>        QuizInfo(question: &quot;What&#39;s unique about the American Wirehair&#39;s coat?&quot;,<br>                 options: [&quot;It&#39;s very long.&quot;, &quot;It&#39;s wavy or &#39;rexed&#39;.&quot;, &quot;It&#39;s double-layered.&quot;, &quot;It&#39;s hypoallergenic.&quot;],<br>                 correctAnswer: 1,<br>                 picture: UIImage(named: CatBreedPicture.AmericanWirehair.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The American Wirehair has a distinct wavy or &#39;rexed&#39; coat.&quot;),<br>        <br>        QuizInfo(question: &quot;Where does the Aphrodite Giant cat come from?&quot;,<br>                 options: [&quot;United States&quot;, &quot;China&quot;, &quot;Cyprus&quot;, &quot;Australia&quot;],<br>                 correctAnswer: 2,<br>                 picture: UIImage(named: CatBreedPicture.AphroditeGiant.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Aphrodite Giant originates from Cyprus.&quot;),<br>        <br>        QuizInfo(question: &quot;The Arabian Mau is native to?&quot;,<br>                 options: [&quot;Arabian Peninsula&quot;, &quot;India&quot;, &quot;Australia&quot;, &quot;United States&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.ArabianMau.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Arabian Mau is native to the Arabian Peninsula.&quot;),<br>        <br>        QuizInfo(question: &quot;The Asian cat is a crossbreed between which two breeds?&quot;,<br>                 options: [&quot;Burmese and Chinchilla Persians&quot;, &quot;Abyssinian and Siamese&quot;, &quot;Maine Coon and Persian&quot;, &quot;Bengal and Siamese&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.Asian.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Asian cat is a crossbreed between the Burmese and Chinchilla Persians.&quot;),<br>        <br>        QuizInfo(question: &quot;What is the coat type of the Asian Semi-longhair?&quot;,<br>                 options: [&quot;Short&quot;, &quot;Semi-long&quot;, &quot;Long&quot;, &quot;Rexed&quot;],<br>                 correctAnswer: 1,<br>                 picture: UIImage(named: CatBreedPicture.AsianSemiLonghair.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Asian Semi-longhair has a semi-long coat.&quot;),<br>        <br>        QuizInfo(question: &quot;The Australian Mist is a crossbreed involving which cat?&quot;,<br>                 options: [&quot;Siamese&quot;, &quot;Abyssinian&quot;, &quot;Bengal&quot;, &quot;Persian&quot;],<br>                 correctAnswer: 1,<br>                 picture: UIImage(named: CatBreedPicture.AustralianMist.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Australian Mist is a crossbreed involving the Abyssinian, among others.&quot;),<br>        <br>        QuizInfo(question: &quot;The Balinese cat is a mutation of which breed?&quot;,<br>                 options: [&quot;Siamese&quot;, &quot;Persian&quot;, &quot;Bengal&quot;, &quot;Maine Coon&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.Balinese.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Balinese cat is a mutation of the Siamese.&quot;),<br>        <br>        QuizInfo(question: &quot;What&#39;s unique about the Bambino cat?&quot;,<br>                 options: [&quot;It&#39;s hairless.&quot;, &quot;It has curled ears.&quot;, &quot;It&#39;s very large.&quot;, &quot;It has a long tail.&quot;],<br>                 correctAnswer: 0,<br>                 picture: UIImage(named: CatBreedPicture.Bambino.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Bambino is unique for being a hairless breed.&quot;),<br>        <br>        QuizInfo(question: &quot;The Bengal cat is a hybrid involving the leopard cat and which other breed?&quot;,<br>                 options: [&quot;Siamese&quot;, &quot;Abyssinian&quot;, &quot;Egyptian Mau&quot;, &quot;Persian&quot;],<br>                 correctAnswer: 1,<br>                 picture: UIImage(named: CatBreedPicture.Bengal.rawValue) ?? UIImage(systemName: &quot;photo&quot;)!,<br>                 answerDescription: &quot;The Bengal cat is a hybrid involving the leopard cat and the Abyssinian.&quot;)<br>    ]<br>}<br><br></pre><h3>Property observer</h3><p>This one is relatively easy. The didSet syntax in computed property can observe value. Once the value is altered, then execute the code in the scope. Very useful, and easy to use.</p><pre>    //Variables<br>    var quizzes = CatBreedsQuizData().quizzes<br>    var roundNum:Int = 0<br>    var answerDescribtion = &quot;&quot;<br>    var ansIndex = 0<br>    var quizIndex = 0<br>    var score:Int = 0{<br>        didSet{<br>            scoreLable.text = &quot;Score: is now \(self.score)&quot;<br>            roundNum += 1<br>            roundLabel.text = String(roundNum)<br>            //logger.info(&quot;\(self.roundNum)&quot;)<br>        }<br>    }</pre><h3>Git</h3><p><a href="https://github.com/JimmyChao90196/Crazy_Quizy.git">GitHub - JimmyChao90196/Crazy_Quizy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7d72a0fac6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E9%81%B8%E6%93%87%E9%A1%8C%E6%9C%9F%E4%B8%AD%E8%80%83-1f7d72a0fac6">選擇題期中考</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#16 Enum/Switch/Struct (psychological test)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/16-enum-switch-struct-psychological-test-846600f1705?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/846600f1705</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[psychological-tests]]></category>
            <category><![CDATA[switch]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 12:27:39 GMT</pubDate>
            <atom:updated>2023-08-06T12:27:39.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foreword</h3><p>So I made an app, called <strong>Trial of Tarnished</strong>, as a tribute to Elden Ring. The app generates corresponding runes based on various options and choices made by the user. Constructing this simple app requires a flexible understanding and usage of <strong>enum, switch, and struct</strong>. So let’s talk about them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*R1bILwcdRkNSm4hAoIBSrA.gif" /><figcaption>Gif demonstration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*R-9mlH3YVdr8NqiiOlwurQ.png" /><figcaption>Overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFBvE3Cn-bbEmXc-jjecgg.png" /><figcaption>Storyboard layout</figcaption></figure><h3>Topics</h3><blockquote><a href="#94b6"><em>MVC rules</em></a></blockquote><blockquote><a href="#2ddb"><em>Enum within struct</em></a></blockquote><blockquote><a href="#7908"><em>Switch return struct or dictionary</em></a></blockquote><blockquote><a href="#7866"><em>Max method and closure</em></a></blockquote><blockquote><a href="#0151"><em>Sending data with segue action</em></a></blockquote><h3>MVC rules</h3><p>To keep my folder nice and tidy. I group them according to <strong>Model, Visual, and Controller.<br>Model folder:</strong> It’s where I store all my database/ function/ and struct</p><p><strong>Visual folder: </strong>It’s where I put my visual components. In this case — storyboard.</p><p><strong>Controller folder</strong>: Pretty obvious, I put controllers in it. Let’s see there’s IntroViewController/ QuestionViewController/ FinalViewController</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*r1mG2oGjwrchBoFs_1UjmA.png" /><figcaption>MVC rules</figcaption></figure><h3>Enum within struct</h3><p>The piece of code below is a model for me to define all kinds of properties of corresponding demigods.</p><p>This approach is used when you want to tightly couple the enum to the struct, making it clear that the enum is specifically related to that struct.</p><p>So in the following code, I grouped all kinds of properties with associated enum into a single struct.</p><h4>Pros:</h4><ul><li><strong>Encapsulation</strong>: The enum is being contained within the struct, meaning it <strong>cannot</strong> be accessed or used elsewhere in your code. This can prevent misuse or confusion. The enum is created specifically for the Demigod struct and is protected from outside.</li><li><strong>Namespace Management</strong>: The enum&#39;s values are scoped to the struct, so they won&#39;t conflict with similar named values in other enums outside the struct.</li></ul><h4>Cons:</h4><ul><li><strong>Limited Accessibility</strong>: Because the enum is within the struct, it&#39;s not accessible to other parts of the code. If I have another struct or class that might need to use the same enum, I’ll have to redefine it or call the struct first.</li></ul><pre>// Importing necessary frameworks<br>import Foundation<br>import UIKit<br><br>//----DEMIGOD STRUCT---------------------------------------------------------------------------------<br><br>// Defining a new structure named DemigodInfo<br>struct DemigodInfo {<br>    <br>    // Defining an enumeration to represent the various nicknames of demigods<br>    // CaseIterable allows us to get a collection of all the cases,<br>    // Hashable allows us to use this enum in a Set or as a Dictionary key.<br>    enum Nickname: String, CaseIterable, Hashable {<br>        // Defining each case in the enumeration<br>        case godrickTheGrafted = &quot;Godrick the Grafted&quot;<br>        case rennalaQueenOfTheFullMoon = &quot;Rennala Queen of the Full Moon&quot;<br>        case starscourgeRadahn = &quot;Starscourge Radahn&quot;<br>        case morgottTheOmenKing = &quot;Morgott, the Omen King&quot;<br>        case rykardLordOfBlasphemy = &quot;Rykard, Lord of Blasphemy&quot;<br>        case maleniaBladeOfMiquella = &quot;Malenia, Blade of Miquella&quot;<br>        case mohgLordOfBlood = &quot;Mohg, Lord of Blood&quot;<br>    }<br><br>    // Defining a computed property for bossImage.<br>    // This switch statement will return different boss images values based on the value of resultDemigod.<br>    var bossImage:String{<br>        switch resultDemigod {<br>        case .godrickTheGrafted:<br>            return &quot;Godrick&quot;<br>        case .rennalaQueenOfTheFullMoon:<br>            return &quot;Rennala&quot;<br>        case .starscourgeRadahn:<br>            return &quot;Starscourge&quot;<br>        case .morgottTheOmenKing:<br>            return &quot;Morgott&quot;<br>        case .rykardLordOfBlasphemy:<br>            return &quot;Rykard&quot;<br>        case .maleniaBladeOfMiquella:<br>            return &quot;Melania&quot;<br>        case .mohgLordOfBlood:<br>            return &quot;Mohg&quot;<br>        }<br>    }<br>    <br>    // Similar to bossImage, this computed property provides different titles based on the value of resultDemigod.<br>    var titles:String { return &quot;You possess the greate rune of \(resultDemigod.rawValue)&quot;}<br>    <br>    <br>    <br>    // Another computed property, this one provides different URL strings based on the value of resultDemigod.<br>    var Urls:String{<br>        switch resultDemigod {<br>        case .godrickTheGrafted:<br>            return &quot;https://eldenring.wiki.fextralife.com/Godrick+the+Grafted&quot;<br>        case .rennalaQueenOfTheFullMoon:<br>            return &quot;https://eldenring.wiki.fextralife.com/Rennala+Queen+of+the+Full+Moon&quot;<br>        case .starscourgeRadahn:<br>            return &quot;https://eldenring.wiki.fextralife.com/Starscourge+Radahn&quot;<br>        case .morgottTheOmenKing:<br>            return &quot;https://eldenring.wiki.fextralife.com/Margit,+The+Fell+Omen&quot;<br>        case .rykardLordOfBlasphemy:<br>            return &quot;https://eldenring.wiki.fextralife.com/Rykard,+Lord+of+Blasphemy&quot;<br>        case .maleniaBladeOfMiquella:<br>            return &quot;https://eldenring.wiki.fextralife.com/Malenia+Blade+of+Miquella&quot;<br>        case .mohgLordOfBlood:<br>            return &quot;https://eldenring.wiki.fextralife.com/Mohg,+Lord+of+Blood&quot;<br>        }<br>    }<br><br>    // A computed property that provides different rune pictures based on the value of resultDemigod.<br>    var runePictures:String{<br>        switch resultDemigod {<br>        case .godrickTheGrafted:<br>            return &quot;greatRune_01&quot;<br>        case .rennalaQueenOfTheFullMoon:<br>            return &quot;greatRune_02&quot;<br>        case .starscourgeRadahn:<br>            return &quot;greatRune_03&quot;<br>        case .morgottTheOmenKing:<br>            return &quot;greatRune_04&quot;<br>        case .rykardLordOfBlasphemy:<br>            return &quot;greatRune_05&quot;<br>        case .maleniaBladeOfMiquella:<br>            return &quot;greatRune_06&quot;<br>        case .mohgLordOfBlood:<br>            return &quot;greatRune_07&quot;<br>        }<br>    }<br><br>    // This computed property provides different descriptions based on the value of resultDemigod.<br>    var description:String {<br>        switch resultDemigod{<br>        case .godrickTheGrafted :<br>            return &quot;Godrick, Stormveil&#39;s monarch bold, of lineage golden and ancient told. Branded weak by kin of spite, his strength in grafted limbs takes flight. A dragon&#39;s head his arm adorns, in battle&#39;s second phase reborn. His knights in golden emblems clad, of war-axe twain, and Serosh, the Regent lad.&quot;<br>        case .rennalaQueenOfTheFullMoon :<br>            return &quot;Beneath a gilded sky, young Rennala sought stars, bewitching Raya Lucaria&#39;s academy with lunar charms. From humble beginnings to queenly might, she led Glintstone knights, to challenge gold-clad champions in starlit fights. Marika&#39;s champion, Radagon, crossed her path in strife, till love supplanted war, and bound them man and wife. When Radagon departed, Rennala&#39;s heart did rend, her academy rebelled, her rule came to an end. Clutching Radagon&#39;s gift, the amber egg, she delved into rebirth&#39;s grim art, her sanity dissolved.&quot;<br>        case .starscourgeRadahn :<br>            return &quot;Born of Radagon and Rennala, Radahn, lion-armored, idolized Elden Lord Godfrey. Heir to fiery hair and demigod stature, he outgrew Leonard, his faithful steed, and sought gravitation&#39;s magic in Sellia&#39;s realm. Radahn, Starscourge shattered celestial cycles, his blades marked with gravity&#39;s crest. His Redmanes, fearless knights, stood with him, loyal in every quest.&quot;<br>        case .morgottTheOmenKing :<br>            return &quot;Born of golden lineage, Morgott, fiend confined, renounced his blood, his curse, in blade and staff enshrined. Amidst the shattered Ring, claimed he Leyndell&#39;s throne, swearing to protect the Erdtree, alone. As Margit, Fell Omen, he laid champions low, yet as the Veiled Monarch, his reign cast a shadow. Warned he of the Erdtree&#39;s wrath, fading on the throne, a warning left unheeded, his fate, by Godfrey known.&quot;<br>        case .rykardLordOfBlasphemy :<br>            return &quot;In aftermath of the Shattered Ring, Rykard, aggrieved, waged blasphemous war against the Erdtree, deceived. Fed himself to Gelmir&#39;s serpent, his ambition turned depraved, once noble lord to gluttonous beast, his honour waived. Even in death, he boasted, A serpent never dies, while Tanith, heartbroken, devoured his corpse beneath the skies.&quot;<br>        case .maleniaBladeOfMiquella :<br>            return &quot;Born of Marika and Radagon, Malenia and Miquella were the Empyreans afflicted. From Scarlet Rot emerged Malenia, her limbs lost, but in swordsmanship, she was gifted. Wars waged, battles won, until the Rot unleashed, her victory sunken. Coma-ridden, in Haligtree, she awaits her brother, while Rot&#39;s infection swelled greater.&quot;<br>        case .mohgLordOfBlood :<br>            return &quot;In lineage golden, Mohg and Morgott birthed, Omen-born twins &#39;neath Leyndell&#39;s earth. Royal blood, uncut horns, Mohg embraced his curse, found fire in blood from a Mother, diverse. Lord of Blood, he claimed, while wars raged above, and from Haligtree&#39;s heart, his brother&#39;s form he stole, in twisted love. His dream - a god-ruler, his brother to be, while he&#39;d be consort, in dark monarchy.&quot;<br>        }<br>    }<br><br>    // This is the nickname (of the enum type Nickname) for the current instance of the struct.<br>    var resultDemigod: Nickname<br>    <br>    // This is the initializer for the DemigodInfo struct. It takes a Nickname as argument and assigns it to resultDemigod.<br>    init(_ resultDemigod:Nickname) {<br>        self.resultDemigod = resultDemigod<br>    }<br>}</pre><h3>Switch return struct or dictionary</h3><p>In the code below, I want o return the corresponding demigod identifier for each option. So I decided to use<strong> switch</strong> to return an array of struct. Switching over an enum and returning a struct has the advantage of type safety and the convenience of accessing data. But… I was also told that I can actually use <strong>dictionary instead of struct.</strong> Let’s break them down and see what kind of situation to use them accordingly.</p><h4>Pros:</h4><ul><li>Struct : Switch statements with structs provide type safety.</li><li>Dictionary : Dictionaries offer more flexibility in terms of the kinds of data they can hold.</li></ul><h4>Cons:</h4><ul><li>Struct : Switching over a struct is more readable and easier to maintain, as the structure of data is defined in my code(in this case OptionInfo)</li><li>Dictionary : there’s a risk of errors if you try to access a key that doesn’t exist.</li></ul><pre>//<br>//  QuestionModel.swift<br>//  Trial of tarnished<br>//<br>//  Created by JimmyChao on 2023/8/3.<br>//<br><br>import Foundation<br>import UIKit<br><br><br><br>struct OptionInfo {<br>    let optionContent: String<br>    let optionTag: String<br>}<br><br><br><br>// Enum Quiz is used to represent different aspects of a character, such as their home landscape, combat method, leadership style, etc.<br>// It conforms to String, allowing the cases to be easily transformed to and from a string representation.<br>// It also conforms to CaseIterable, enabling the enumeration of all the cases.<br>enum Quiz: String, CaseIterable, Hashable {<br>    // These cases represent different character aspects that are part of the quiz.<br>    case HomeLandscape<br>    case CombatMethod<br>    case LeadershipStyle<br>    case ChallengeApproach<br>    case GreatestStrength<br>    case RulerType<br>    case GreatestWeakness<br>    case CherishedValue<br><br>    <br>    <br>    // Below, each case is mapped to a specific question that will be asked in the quiz.<br>    // The questions relate to different facets of a character&#39;s personality and preferences.<br>    var description: String {<br>        switch self {<br>        case .HomeLandscape:<br>            return &quot;Which of these landscapes would you prefer to call home?&quot;<br>        case .CombatMethod:<br>            return &quot;What is your preferred method of combat?&quot;<br>        case .LeadershipStyle:<br>            return &quot;How would you describe your leadership style?&quot;<br>        case .ChallengeApproach:<br>            return &quot;How do you approach a challenge?&quot;<br>        case .GreatestStrength:<br>            return &quot;What is your greatest strength?&quot;<br>        case .RulerType:<br>            return &quot;What type of ruler are you?&quot;<br>        case .GreatestWeakness:<br>            return &quot;What would be your greatest weakness?&quot;<br>        case .CherishedValue:<br>            return &quot;What&#39;s your most cherished value?&quot;<br>        }<br>    }<br><br><br>  //Each option has it&#39;s corresponding character stored in tags in order for me to keep track the score for corresponding character.<br>    var optionInfo: [OptionInfo] {<br>        switch self {<br>        case .HomeLandscape:<br>            return [<br>                OptionInfo(optionContent: &quot;A grand castle, teeming with knowledge and wealth.&quot;, optionTag: &quot;Godrick The Grafted&quot;),<br>                OptionInfo(optionContent: &quot;A tranquil forest, bathed in the glow of the full moon.&quot;, optionTag: &quot;Rennala Queen of the Full Moon&quot;),<br>                OptionInfo(optionContent: &quot;A desolate wasteland, scarred by falling stars.&quot;, optionTag: &quot;Starscourge Radahn&quot;),<br>                OptionInfo(optionContent: &quot;An imposing fortress, steeped in dark omens.&quot;, optionTag: &quot;Morgott, the Omen King&quot;)<br>            ]<br>        case .CombatMethod:<br>            return [<br>                OptionInfo(optionContent: &quot;Cunning trickery and powerful spells.&quot;, optionTag: &quot;Rykard, Lord of Blasphemy&quot;),<br>                OptionInfo(optionContent: &quot;Strength and brute force, unleashing the fury of a thousand suns.&quot;, optionTag: &quot;Starscourge Radahn&quot;),<br>                OptionInfo(optionContent: &quot;Swift, precise swordsmanship.&quot;, optionTag: &quot;Malenia, Blade of Miquella&quot;),<br>                OptionInfo(optionContent: &quot;Commanding legions of loyal followers.&quot;, optionTag: &quot;Morgott, the Omen King&quot;)<br>            ]<br>        case .LeadershipStyle:<br>            return [<br>                OptionInfo(optionContent: &quot;Wise and innovative, always seeking progress.&quot;, optionTag: &quot;Godrick The Grafted&quot;),<br>                OptionInfo(optionContent: &quot;Mysterious and enigmatic, ruling from the shadows.&quot;, optionTag: &quot;Rennala Queen of the Full Moon&quot;),<br>                OptionInfo(optionContent: &quot;Aggressive and dominant, seizing power through force.&quot;, optionTag: &quot;Mohg, Lord of Blood&quot;),<br>                OptionInfo(optionContent: &quot;Inspirational and revered, leading with charisma.&quot;, optionTag: &quot;Rykard, Lord of Blasphemy&quot;)<br>            ]<br>        case .ChallengeApproach:<br>            return [<br>                OptionInfo(optionContent: &quot;With careful planning and strategy.&quot;, optionTag: &quot;Godrick the Grafted&quot;),<br>                OptionInfo(optionContent: &quot;By overpowering it with brute strength.&quot;, optionTag: &quot;Mohg, Lord of Blood&quot;),<br>                OptionInfo(optionContent: &quot;By adapting and finding creative solutions.&quot;, optionTag: &quot;Malenia, Blade of Miquella&quot;),<br>                OptionInfo(optionContent: &quot;By confronting it head on, fearlessly.&quot;, optionTag: &quot;Starscourge Radahn&quot;)<br>            ]<br>        case .GreatestStrength:<br>            return [<br>                OptionInfo(optionContent: &quot;My unyielding thirst for knowledge.&quot;, optionTag: &quot;Godrick the Grafted&quot;),<br>                OptionInfo(optionContent: &quot;My mastery over the forces of nature.&quot;, optionTag: &quot;Rennala Queen of the Full Moon&quot;),<br>                OptionInfo(optionContent: &quot;My unparalleled combat skills.&quot;, optionTag: &quot;Malenia, Blade of Miquella&quot;),<br>                OptionInfo(optionContent: &quot;My unstoppable willpower and determination.&quot;, optionTag: &quot;Rykard, Lord of Blasphemy&quot;)<br>            ]<br>        case .RulerType:<br>            return [<br>                OptionInfo(optionContent: &quot;A feared despot, ruling with an iron fist.&quot;, optionTag: &quot;Morgott, the Omen King&quot;),<br>                OptionInfo(optionContent: &quot;A beloved sovereign, respected by all.&quot;, optionTag: &quot;Rennala Queen of the Full Moon&quot;),<br>                OptionInfo(optionContent: &quot;A warlord, leading through strength and victory.&quot;, optionTag: &quot;Mohg, Lord of Blood&quot;),<br>                OptionInfo(optionContent: &quot;An innovator, pushing the boundaries of what is possible.&quot;, optionTag: &quot;Godrick the Grafted&quot;)<br>            ]<br>        case .GreatestWeakness:<br>            return [<br>                OptionInfo(optionContent: &quot;My ruthless ambition.&quot;, optionTag: &quot;Morgott, the Omen King&quot;),<br>                OptionInfo(optionContent: &quot;My volatile temper.&quot;, optionTag: &quot;Mohg, Lord of Blood&quot;),<br>                OptionInfo(optionContent: &quot;My relentless pursuit of knowledge, at any cost.&quot;, optionTag: &quot;Rykard, Lord of Blasphemy&quot;),<br>                OptionInfo(optionContent: &quot;My inability to resist the allure of power.&quot;, optionTag: &quot;Starscourge Radahn&quot;)<br>            ]<br>        case .CherishedValue:<br>            return [<br>                OptionInfo(optionContent: &quot;Loyalty, the cornerstone of every great kingdom.&quot;, optionTag: &quot;Morgott, the Omen King&quot;),<br>                OptionInfo(optionContent: &quot;Courage, the heart of every warrior.&quot;, optionTag: &quot;Starscourge Radahn&quot;),<br>                OptionInfo(optionContent: &quot;Wisdom, the foundation of every decision.&quot;, optionTag: &quot;Godrick the Grafted&quot;),<br>                OptionInfo(optionContent: &quot;Harmony, the essence of a balanced life.&quot;, optionTag: &quot;Rennala Queen of the Full Moon&quot;)<br>            ]<br>        }<br>        <br>    }<br><br>    <br>}<br><br><br><br></pre><h3>Max method and closure</h3><p>I’ve always wanted to explore closure, I’ll probably write an article just about it. But for now, let’s have a glimpse through the Max method!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LC5uXz5g8qCZvcBpfhY6Jw.png" /></figure><p>Ignore the @escaping for now, we can see the argument of the max method has (Self.Element, Self.Element) -&gt; Bool) . This means the max(by:) method is asking for a function or closure. And closure is just a simplified version of a function, let’s keep that in mind for now.</p><h4>How closure works</h4><p>In Swift, you have a lot of flexibility with how you define closures. When you pass closure as a method’s argument, Swift allows us to write it in a very shortened form. But for clarity, here’s the code using the <strong>full closure</strong> syntax:</p><pre>var score: [String: Int] = [&quot;Zeus&quot;: 10, &quot;Hercules&quot;: 12, &quot;Ares&quot;: 8]<br><br>if let result = score.max(by: { (demigod1: (key: String, value: Int), demigod2: (key: String, value: Int)) -&gt; Bool in<br>    return demigod1.value &lt; demigod2.value<br>}) {<br>    let (demigod, _) = result<br>    print(&quot;Demigod with max score is: \(demigod)&quot;)<br>}</pre><ul><li>(demigod1: (key: String, value: Int), demigod2: (key: String, value: Int)) -&gt; Bool: This part declares the closure&#39;s parameters and return type. The closure takes two tuples as parameters (each containing a key and a value from the dictionary) and returns a Bool.</li><li>return demigod1.value &lt; demigod2.value: This is the body of the closure. It returns true if the value of the first demigod&#39;s score is less than the second demigod&#39;s score. This will cause the max(by:) method to return the demigod with the maximum score.</li><li>So, the shortened form { $0.value &lt; $1.value } is a shorthand way of writing the exact same closure. It omits the parameter and return type declaration and uses $0 and $1 as shorthand for the first and second parameters.</li></ul><p>In the following code, I use the <strong>max method</strong> with shortened closure to find the highest value within score dictionary.</p><pre>import Foundation<br>import UIKit<br><br>// ScoreTracker struct tracks the score for each demigod in Elden Ring.<br>struct ScoreTracker{<br>    <br>    <br>    // score dictionary uses the Nickname enumeration from DemigodInfo as the key and an integer as the value.<br>    var score:[DemigodInfo.Nickname:Int] = [<br>        .godrickTheGrafted: 0,<br>        .rennalaQueenOfTheFullMoon:0,<br>        .starscourgeRadahn:0,<br>        .morgottTheOmenKing:0,<br>        .rykardLordOfBlasphemy:0,<br>        .maleniaBladeOfMiquella:0,<br>        .mohgLordOfBlood:0<br>    ]<br>    <br>    <br>    <br>    //Hold the final result message after all scores are calculated.<br>    var resultText = &quot;&quot;<br>    <br>    <br>    <br>    //Hold the Nickname of the demigod who has the highest score.<br>    var resultDemigod:DemigodInfo.Nickname = .godrickTheGrafted<br><br>    <br><br>    // It assigns the nickname of the demigod with the highest score to resultDemigod.<br>    mutating func getHighestScore(){<br>        if let (demigod, _) = score.max(by: {$0.value &lt; $1.value}){<br>            resultDemigod = demigod<br>        }else{<br>            resultDemigod = DemigodInfo.Nickname.godrickTheGrafted<br>        }<br>    }<br><br><br>    // Increases the score of the demigod associated with the selected tag by 1 each time it&#39;s called.<br>    mutating func trackingScore(_ tags: String){<br>        guard let selectedTag = DemigodInfo.Nickname(rawValue: tags) else { return }<br>        <br>        //Increment the corresponding score<br>        score[selectedTag] = (score[selectedTag] ?? 0) + 1<br>        <br>        //Print out the result for debugging purposes<br>        for demigod in DemigodInfo.Nickname.allCases {<br>            print(&quot;\(demigod.rawValue) \(score[demigod] ?? 0)&quot;)<br>        }<br>    }<br>}<br><br></pre><h3>Sending data with segue action</h3><p>I once asked Peter a very naive question. Why do we need a segue action when we can just create files for all our data a share them with all the controllers?</p><p>And he said that transmitting data by using segue action allows data to be stored inside the ram memory. And it’s faster for other controllers to reach and access the data. While storing data in a file means the data is stored in the hard drive. And accessing data from a hard drive is relatively slower than from ram memory.</p><pre>    //---SEGUE FUNCTIONS----<br>    @IBSegueAction func sendResult(_ coder: NSCoder) -&gt; FinalViewController? {<br>        let controller =  FinalViewController(coder: coder)<br>        //Track the score of selected option<br>        scoreTracker.trackingScore(tags)<br>        //Identify the highest score<br>        scoreTracker.getHighestScore()<br><br>        // Assign the result to &#39;resultDemigod&#39; of &#39;FinalViewController&#39;.<br>        controller?.resultDemigod = scoreTracker.resultDemigod<br>        <br>        return controller<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdLdpmKt_uYomM8qqLtB9Q.png" /><figcaption>Use segue action to send data from one controller to another.</figcaption></figure><h3>Git/Conclusion</h3><p><a href="https://github.com/JimmyChao90196/Trial-of-tarnished.git">GitHub - JimmyChao90196/Trial-of-tarnished</a></p><p>There is still much to learn. At this point, I’m pretty glad that I can use switch and enum or dictionary to structure and organize my code. But I still don’t understand some of the mechanisms of closure and how to properly read a document. I guess I’ll write articles about them in the future as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=846600f1705" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/16-enum-switch-struct-psychological-test-846600f1705">#16 Enum/Switch/Struct (psychological test)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#35 Convert anything(The beautiful of proceduralism)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/convert-anything-the-beautiful-of-proceduralism-bbb7895a7618?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb7895a7618</guid>
            <category><![CDATA[unit]]></category>
            <category><![CDATA[converting]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 09:57:22 GMT</pubDate>
            <atom:updated>2023-08-12T04:47:14.933Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foreword</h3><p>The unit converter app I’m going to introduce to you today is able to convert a variety of measurements. There are a few tricks and tips I’d like to share. Let’s go ahead and check it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*1XUUdCSprfpaJoHG3ZhrTw.gif" /><figcaption>You can convert anything into its corresponding measurements.</figcaption></figure><h3>Topics</h3><ul><li>Initialize convert type</li><li>Measurement method</li><li>Realtime result computation</li><li>Click empty space to fold the keyboard</li></ul><h3>Initialize popup button</h3><p>In our measurement converting app, we wanted to create an interactive way for users to select the type of measurement they want to convert. To achieve this, we implemented a pop-up button using UIAction and UIMenu classes from Apple&#39;s UIKit framework.</p><p>First, we defined action items for each measurement category. For example, we created an action item for “Distance,” another for “Mass,” one for “Temperature,” and one for “Time.” Each action item contains a title and an image to represent the category (e.g., a ruler icon for “Distance,” a scale for “Mass,” etc.).</p><p>These action items will be available and appear in the pop-up button. For each action item, we specified a closure that gets executed when the user selects it. What is closure you ask? We’ll talk later about this topic.</p><p>Next, we created a UIMenu by grouping all the action items together. The UIMenu represents the entire pop-up button with the different measurement category choices. We gave it a title, &quot;Measurement,&quot; to give users an idea of what&#39;s inside the menu.</p><p>And finally, we assign our menu to the button.</p><pre> func initializePopupButton() {<br>    // Creating action item for &quot;Distance&quot;<br>    let distanceItem = UIAction(title: &quot;Distance&quot;, image: UIImage(systemName: &quot;ruler&quot;)) { (action) in<br>        // When &quot;Distance&quot; action item is selected, set the selectedUnitTypeIndex to 0 (representing Distance category)<br>        self.selectedUnitTypeIndex = 0<br>        <br>        // Update the title of the main button to &quot;Distance&quot;<br>        self.convertTypeButton.setTitle(self.convertTypes[self.selectedUnitTypeIndex], for: .normal)<br>    }<br><br>    // Creating action item for &quot;Mass&quot;<br>    let massItem = UIAction(title: &quot;Mass&quot;, image: UIImage(systemName: &quot;scalemass&quot;)) { (action) in<br>        self.selectedUnitTypeIndex = 1<br>        self.convertTypeButton.setTitle(self.convertTypes[self.selectedUnitTypeIndex], for: .normal)<br>    }<br><br>    // Creating action item for &quot;Temperature&quot;<br>    let temperatureItem = UIAction(title: &quot;Temperature&quot;, image: UIImage(systemName: &quot;thermometer.transmission&quot;)) { (action) in<br>        self.selectedUnitTypeIndex = 2<br>        self.convertTypeButton.setTitle(self.convertTypes[self.selectedUnitTypeIndex], for: .normal)<br>    }<br><br>    // Creating action item for &quot;Time&quot;<br>    let timeItem = UIAction(title: &quot;Time&quot;, image: UIImage(systemName: &quot;clock&quot;)) { (action) in<br>        self.selectedUnitTypeIndex = 3<br>        self.convertTypeButton.setTitle(self.convertTypes[self.selectedUnitTypeIndex], for: .normal)<br>    }<br><br>    // Creating the menu with all the action items<br>    let menu = UIMenu(title: &quot;Measurement&quot;, options: .displayInline, children: [distanceItem, massItem, temperatureItem, timeItem])<br>    <br>    // Set the title of the main button to the initial selected category (&quot;Distance&quot; by default)<br>    self.convertTypeButton.setTitle(self.convertTypes[self.selectedUnitTypeIndex], for: .normal)<br><br>    // Assign the menu to the main button<br>    convertTypeButton.menu = menu<br><br>    // Enable the main button to show the menu as the primary action<br>    convertTypeButton.showsMenuAsPrimaryAction = true<br>    <br>    // Button appearance customization<br>    convertTypeButton.clipsToBounds = true<br>    convertTypeButton.backgroundColor = .clear<br>    convertTypeButton.layer.cornerRadius = 20<br>    convertTypeButton.layer.borderWidth = 1.5<br>    convertTypeButton.layer.borderColor = UIColor.darkGray.cgColor<br>}</pre><h3>Measurement class</h3><p>The class is available in the framework — Foundation. It contains all kinds of measurement types. From degree to mass, or temperature to distance.</p><p>When you enter a value and select a measurement unit, our app calls upon the Measurement class to handle the heavy lifting. It takes your input and converts it to the desired output unit. For example, if you want to convert 10 meters into miles. It’ll spit out a shockingly accurate result for you immediately.</p><p>We’ve also got a formatting trick using the formatted method. It dresses up your input and output measurements, so you can see them in a neat, clear format.</p><p><a href="https://developer.apple.com/documentation/foundation/measurement/">Measurement | Apple Developer Documentation</a></p><pre>.<br>.<br>.<br><br><br>// An array that holds different units for each measurement category<br>let unitTypes = [<br> <br>    [UnitLength.meters, UnitLength.kilometers, UnitLength.feet, UnitLength.yards, UnitLength.miles],<br> <br>    [UnitMass.grams, UnitMass.kilograms, UnitMass.ounces, UnitMass.pounds],<br> <br>    [UnitTemperature.celsius, UnitTemperature.fahrenheit, UnitTemperature.kelvin],<br><br>    [UnitDuration.hours, UnitDuration.minutes, UnitDuration.seconds]<br>]<br><br>.<br>.<br>.<br><br>// Function to perform the measurement conversion and display the result<br>func calculation() {<br>    // Create a Measurement instance from the input value and input unit<br>    let inputMeasurement = Measurement(value: inputValue, unit: inputUnit)<br>    <br>    // Convert the input measurement to the desired output unit<br>    let outputMeasurement = inputMeasurement.converted(to: outputUnit)<br>    <br>    // Format the input measurement as a string with a wide format<br>    let inputString = inputMeasurement.formatted(.measurement(width: .wide))<br>    <br>    // Format the output measurement as a string with a wide format<br>    let outputString = outputMeasurement.formatted(.measurement(width: .wide))<br>    <br>    // Display the formatted input and output measurements in the result label<br>    result.text = inputString + &quot;\n is \n&quot; + outputString<br>}</pre><h3>Realtime calculation</h3><p>Well. This one is easy, no more brain-hurting exercises like closure and stuff…</p><p>I simply use didSet to do the job. didSet is just like a value observer. Whenever value has changed or altered. It’ll execute the code within its belly. It can be used in lots of circumstances like alert showing and in this case — real-time feedback.</p><pre>    var selectedUnitTypeIndex = 0{<br>        didSet{<br>//Initialize segment parameter when value changed<br>            initializeSeg(inputSeg, outputSeg)<br>//Update uniteType when value chagned<br>            updateUnit()<br>//Do the calculation ...<br>            calculation()<br>//Update the result....<br>            updateTextField()<br>        }<br>    }</pre><h3>Folding the keyboard</h3><p>When the mouse cursor or hand gesture touches to empty space on the screen, the following function will be triggered. Not much isn’t it? Well, there are more ways to achieve the same effect. Read Peters&#39;s aritcle instead!</p><pre>    //When the mouse cursor or hand gesture touch to empty space on screen, this function will be triggered<br>    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        view.endEditing(true)<br>    }</pre><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/uitextfield-%E9%BB%9E%E9%81%B8-return-%E9%8D%B5%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-f99769370d46">UITextField 點選 return 鍵收鍵盤的方法</a></p><h3>GIT/Conclusion</h3><p>I face many obstacles during the process. And to be honest there are still things that I don’t fully understand. Like closure, I’m seriously considering subscribing to gpt4 to ask more in-depth questions.</p><p><a href="https://github.com/JimmyChao90196/UnitConverter.git">GitHub - JimmyChao90196/UnitConverter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb7895a7618" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/convert-anything-the-beautiful-of-proceduralism-bbb7895a7618">#35 Convert anything(The beautiful of proceduralism)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#203/154 Tapping game(Whack a Mole)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/tapping-game-whack-a-mole-f96da9e5c1e7?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96da9e5c1e7</guid>
            <category><![CDATA[sekiro]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[whack-a-mole]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 06:00:20 GMT</pubDate>
            <atom:updated>2023-08-12T04:48:51.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rules</h3><p>The project I’m gonna show you today is a tapping game. Two players tap on each end of the phone. You have to be fast and accurate to score. The shape and position of the symbol will change each round. Just like the game whack-a-mole.</p><h3>Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AZZBcQno0FFtUC215S8dBA.gif" /><figcaption>Sekiro vs genichiro with…. sf symbol….</figcaption></figure><h3>Topics</h3><p>Below are the challenges that I encountered during the process.</p><ul><li><strong>Swap and mirror the images</strong></li><li><strong>Generate button without using IBOutlet</strong></li><li><strong>Animate the symbol</strong></li><li><strong>Destroy the symbol afterward</strong></li></ul><h3><strong>Swap and mirror the images</strong></h3><p>Again, it sounds pretty easy. But somehow I managed to spend an hour on this task. Let’s break down some code.</p><p>The switchPosition function handles the switch button press in our Whack-a-mole game. First, we swap the scores of the left (LScore) and right (RScore)using a temporary variable tempScore. Next, we toggle the mirro flag to control image mirroring.</p><p>We have two image views: sekiro and genichiro, representing the left and right players. When the button is pressed and mirro is true, we mirror the images by flipping them horizontally (upMirrored orientation). This creates the illusion that the players have switched positions.</p><pre>    @IBAction func switchPosition(_ sender: UIButton) {<br>        // Function to handle the switch button press<br>        <br>        // Swap the scores of left and right players<br>        let tempScore = LScore<br>        LScore = RScore<br>        RScore = tempScore<br>        <br>        // Update the score labels<br>        leftScore.text = &quot;Score: \(LScore)&quot;<br>        rightScore.text = &quot;Score: \(RScore)&quot;<br>        <br>        // Toggle the mirroring of player images<br>        mirro.toggle()<br>        var sekiroImage = UIImage(named: &quot;Se&quot;)!<br>        var mSekiroImage = UIImage(cgImage: (sekiroImage.cgImage)!, scale: 1, orientation: .upMirrored)<br>        var genichiroImage = UIImage(named: &quot;Gan&quot;)!<br>        var mGenichiroImage = UIImage(cgImage: (genichiroImage.cgImage)!, scale: 1, orientation: .upMirrored)<br>        var imageHolder = UIImage(named: &quot;Se&quot;)!<br>        <br>        // Switch and mirror the image views based on the mirro flag<br>        if mirro {<br>            // Swap the images when mirro is true<br>            sekiro.image = mGenichiroImage<br>            genichiro.image = mSekiroImage<br>        } else {<br>            // Reset to the original images when mirro is false<br>            sekiro.image = sekiroImage<br>            genichiro.image = genichiroImage<br>        }<br>    }</pre><h3><strong>Generate button without using IBOutlet</strong></h3><p>I’m not sure if there’s a better way to do this. But as far as I know. If a button is generated from pure code(without the participation of the interface builder), then we must use a little bit of objective c to define the button.</p><p>To handle button presses, we use the addTarget method on buttonView. We specify that when the button is touched up inside (for: .touchUpInside), the tappedLeft function should be called. This function handles what happens when the button is pressed, checking if the name of the symbol attached to the button (selectedNames[sender.tag]) matches the correct answer (ansName).</p><p>And as for #selector , what does it means? Well, It acts as a bridge between Swift and Objective-C, allowing Swift code to interact with Objective-C runtime.</p><pre><br><br>.<br>.<br>.<br>.<br>.<br>.<br><br>let buttonView = UIButton()<br>         buttonView.frame = tempPos[id]<br>         buttonView.backgroundColor = .orange<br>         buttonView.layer.opacity = 0.9<br>         buttonView.clipsToBounds = true<br>         buttonView.layer.cornerRadius = 95/2<br>         buttonView.addSubview(mySymbol)<br><br>         // Add a target and action to the button so that when it is touched up inside, the `tappedLeft` function is called<br>         buttonView.addTarget(self, action: #selector(tappedLeft), for: .touchUpInside)<br>         buttonView.tag = id   <br>.<br>.<br>.<br>.<br>.<br>.<br><br><br>// The `@objc` attribute is used to indicate that this function can be called from Objective-C code<br> @objc private func tappedLeft(sender:UIButton){<br>        <br>// The `@objc` attribute is used to indicate that this function can be called from Objective-C code<br>        let tappedName = selectedNames[sender.tag]<br>        <br>        print(tappedName)<br>        <br>        if tappedName == ansName {<br>            //update round<br>            counts += 1<br>            round.text = &quot;Round \(counts)&quot;<br>            <br>            //update score<br>            LScore += 1<br>            leftScore.text = &quot;Score: \(LScore)&quot;<br>            <br>            print(counts)<br>        }<br>    }</pre><h3><strong>Animate the symbol</strong></h3><p>Now this one is relatively easy. Just follow the instruction in the official introduction of SFsymbol animation and you be fine.</p><p><a href="https://developer.apple.com/videos/play/wwdc2023/10258/">Animate symbols in your app - WWDC23 - Videos - Apple Developer</a></p><pre>// Apply an animation effect to make `mySymbol` appear on the screen<br>mySymbol.addSymbolEffect(.appear, animated: true)<br><br>// Apply an animation effect to make the color of `mySymbol` change over time<br>mySymbol.addSymbolEffect(.variableColor, animated: true)<br><br>// Apply an animation effect to scale up the size of `mySymbol`<br>mySymbol.addSymbolEffect(.scale.up, animated: true)<br><br>// Apply an animation effect to make `mySymbol` bounce repeatedly<br>mySymbol.addSymbolEffect(.bounce, options: .repeating)</pre><h3>Destroy the symbol afterward</h3><p>The function destroyedSymbol() allows us to remove symbols from the screen and clear related arrays. We have to iterate through each symbol in the symbols array and apply an animation effect to make them disappear. After the animation, we remove the symbols from their superviews to ensure they are no longer visible. Additionally, we clear the selectedNames array to reset the symbols&#39; names.</p><p>We also need to remove buttons related to the right and left players, stored in buttonRights and buttonsLefts arrays. At the end, we animate and remove the instance of anSymbolInstance. Now our game is ready for a new round.</p><h3>Overall source code</h3><pre>import UIKit<br>import Foundation<br><br>class ViewController: UIViewController {<br>    <br>    // Button bounds<br>    struct buttonBounds {<br>        static var scale: Double = 1<br>        static var height: Double = 95 * scale<br>        static var width: Double = 95 * scale<br>    }<br>    <br>    // Screen size<br>    let width = UIScreen.main.bounds.size.width<br>    let height = UIScreen.main.bounds.size.height<br>    <br>    // Positions for the buttons<br>    var positionA: CGRect = CGRect()<br>    var positionB: CGRect = CGRect()<br>    var positionC: CGRect = CGRect()<br>    var positions: [CGRect] = [CGRect]()<br>    <br>    // Scores and rounds<br>    var counts = 0 {<br>        didSet {<br>            // When counts change, update the game<br>            destroyedSymbol()<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 1.55) {<br>                self.initializerPlayerLeft()<br>                self.initializerPlayerRight()<br>                self.initializeAnswer()<br>                print(self.ansName)<br>            }<br>        }<br>    }<br>    var LScore = 0 // Left player&#39;s score<br>    var RScore = 0 // Right player&#39;s score<br>    <br>    // SymbolNames<br>    var ansName = &quot;&quot; // Correct symbol&#39;s name for the round<br>    var selectedNames = [String]() // Array to store the selected symbol names for each round<br>    var symbolNames = [&quot;wifi.exclamationmark&quot;, &quot;antenna.radiowaves.left.and.right&quot;, &quot;dot.radiowaves.left.and.right&quot;, &quot;square.grid.3x3.middle.filled&quot;, &quot;circle.grid.cross&quot;]<br>    <br>    // Arrays to store UI elements<br>    var symbols = [UIImageView]() // Array to store the symbol image views<br>    var buttonsLefts = [UIButton]() // Array to store the left player&#39;s buttons<br>    var buttonRights = [UIButton]() // Array to store the right player&#39;s buttons<br>    var anSymbolInstance = UIImageView() // Image view to display the correct symbol for each round<br>    <br>    // Mirror toggle value<br>    var mirro = false // Flag to determine if the images should be mirrored or not<br>    <br>    //-------------------------------INTERFACE BUILDER ELEMENT-----------------------<br>    @IBOutlet var leftScore: UILabel! // Label to display left player&#39;s score<br>    @IBOutlet var rightScore: UILabel! // Label to display right player&#39;s score<br>    @IBOutlet var round: UILabel! // Label to display the current round number<br>    @IBOutlet var sekiro: UIImageView! // Image view for left player<br>    @IBOutlet var genichiro: UIImageView! // Image view for right player<br>    @IBOutlet var AnswerSection: UIView! // View to display the correct symbol for each round<br>    <br>    @IBAction func switchPosition(_ sender: UIButton) {<br>        // Function to handle the switch button press<br>        <br>        // Swap the scores of left and right players<br>        let tempScore = LScore<br>        LScore = RScore<br>        RScore = tempScore<br>        <br>        // Update the score labels<br>        leftScore.text = &quot;Score: \(LScore)&quot;<br>        rightScore.text = &quot;Score: \(RScore)&quot;<br>        <br>        // Toggle the mirroring of player images<br>        mirro.toggle()<br>        var sekiroImage = UIImage(named: &quot;Se&quot;)!<br>        var mSekiroImage = UIImage(cgImage: (sekiroImage.cgImage)!, scale: 1, orientation: .upMirrored)<br>        var genichiroImage = UIImage(named: &quot;Gan&quot;)!<br>        var mGenichiroImage = UIImage(cgImage: (genichiroImage.cgImage)!, scale: 1, orientation: .upMirrored)<br>        var imageHolder = UIImage(named: &quot;Se&quot;)!<br>        <br>        // Switch and mirror the image views based on the mirro flag<br>        if mirro {<br>            // Swap the images when mirro is true<br>            sekiro.image = mGenichiroImage<br>            genichiro.image = mSekiroImage<br>        } else {<br>            // Reset to the original images when mirro is false<br>            sekiro.image = sekiroImage<br>            genichiro.image = genichiroImage<br>        }<br>    }<br>    <br>    //--------------------------------OBJECTIVE C FUNCTIONS----------------------------<br>    <br>    // Function to handle the left player&#39;s button tap<br>    @objc private func tappedLeft(sender: UIButton) {<br>        let tappedName = selectedNames[sender.tag]<br>        print(tappedName)<br>        if tappedName == ansName {<br>            // If the tapped symbol name matches the correct symbol name<br>            // Update the round count<br>            counts += 1<br>            round.text = &quot;Round \(counts)&quot;<br>            <br>            // Update the left player&#39;s score<br>            LScore += 1<br>            leftScore.text = &quot;Score: \(LScore)&quot;<br>            print(counts)<br>        }<br>    }<br>    <br>    // Function to handle the right player&#39;s button tap<br>    @objc private func tappedRight(sender: UIButton) {<br>        let tappedName = selectedNames[sender.tag]<br>        print(tappedName)<br>        if tappedName == ansName {<br>            // If the tapped symbol name matches the correct symbol name<br>            // Update the round count<br>            counts += 1<br>            round.text = &quot;Round \(counts)&quot;<br>            <br>            // Update the right player&#39;s score<br>            RScore += 1<br>            rightScore.text = &quot;Score: \(RScore)&quot;<br>            print(counts)<br>        }<br>    }<br>    <br>    //-----------------------------MANNUAL FUNCTIONS-------------------------<br>    <br>    // Function to destroy symbols and update the game for the next round<br>    func destroyedSymbol() {<br>        // Iterate through each symbol and make them disappear with animation<br>        for symbol in symbols {<br>            symbol.addSymbolEffect(.disappear, animated: true)<br>            UIView.animate(withDuration: 1.5, animations: {<br>                symbol.alpha = 0.0 // Set the alpha to 0 to make it disappear with animation<br>            }, completion: { _ in<br>                symbol.removeFromSuperview() // Remove the symbol from its superview once the animation completes<br>            })<br>        }<br>        <br>        // Clear the selectedNames array for the next round<br>        selectedNames.removeAll()<br>        <br>        // Remove buttons from their superviews<br>        for buttonR in buttonRights {<br>            buttonR.removeFromSuperview()<br>        }<br>        <br>        for buttonL in buttonsLefts {<br>            buttonL.removeFromSuperview()<br>        }<br>        <br>        // Animate and remove the anSymbolInstance<br>        UIView.animate(withDuration: 1.5, animations: {<br>            self.anSymbolInstance.alpha = 0.0 // Set the alpha to 0 to make it disappear with animation<br>        }, completion: { _ in<br>            self.anSymbolInstance.removeFromSuperview()<br>        })<br>    }<br>    <br>    // Function to initialize the correct symbol for each round<br>    func initializeAnswer() {<br>        let anSymbol: UIImageView = {<br>            let imageView = UIImageView()<br>            imageView.contentMode = .scaleAspectFit<br>            return imageView<br>        }()<br>        <br>        var tempNames = selectedNames<br>        tempNames.shuffle()<br>        <br>        // Set the image and name of the correct symbol for the round<br>        anSymbol.image = UIImage(systemName: tempNames[0])<br>        ansName = tempNames[0]<br>        <br>        // Add animating effects to the correct symbol<br>        let bound = AnswerSection.bounds.size<br>        anSymbol.frame = CGRect(x: -35 + bound.width/2, y: -35 + bound.height/2, width: 70, height: 70)<br>        anSymbol.addSymbolEffect(.appear, animated: true)<br>        anSymbol.addSymbolEffect(.variableColor, animated: true)<br>        anSymbol.addSymbolEffect(.scale.up, animated: true)<br>        anSymbol.addSymbolEffect(.bounce, options: .repeating)<br>        <br>        // Store the correct symbol in the instance variable<br>        anSymbolInstance = anSymbol<br>        <br>        // Add the correct symbol to the answer section<br>        AnswerSection.addSubview(anSymbol)<br>        <br>        // Log the correct symbol name for debugging purposes<br>        print(ansName)<br>    }<br>    <br>    // Function to initialize the left player&#39;s buttons and symbols<br>    func initializerPlayerLeft() {<br>        // Define the positions for the left player&#39;s buttons<br>        positionA = CGRect(x: (width/4) - (buttonBounds.width/2) + 50, y: (height/2) - (buttonBounds.height/2), width: buttonBounds.width, height: buttonBounds.height)<br>        positionB = CGRect(x: (width/4) - (buttonBounds.width/2) - 80, y: (height/2) - (buttonBounds.height/2)-80, width: buttonBounds.width, height: buttonBounds.height)<br>        positionC = CGRect(x: (width/4) - (buttonBounds.width/2) - 80, y: (height/2) - (buttonBounds.height/2)+80, width: buttonBounds.width, height: buttonBounds.height)<br>        <br>        // Store the button positions in an array and shuffle them<br>        positions = [positionA, positionB, positionC]<br>        var tempPos = positions.shuffled()<br>        <br>        var tempSymbolNames = symbolNames<br>        <br>        // Create three buttons for the left player with random symbols<br>        for id in 0...2 {<br>            // Randomly select a symbol name from the remaining ones<br>            let length = tempSymbolNames.count<br>            let randId = Int.random(in: 0...length - 1)<br>            <br>            // Declare the symbol image view<br>            let mySymbol: UIImageView = {<br>                let imageView = UIImageView()<br>                imageView.image = UIImage(systemName: tempSymbolNames[randId])<br>                imageView.contentMode = .scaleAspectFit<br>                return imageView<br>            }()<br>            <br>            // Randomize the selected symbol names<br>            selectedNames.append(tempSymbolNames[randId])<br>            tempSymbolNames.remove(at: randId)<br>            <br>            // Set the symbol image view&#39;s position and add animating effects<br>            mySymbol.frame = CGRect(x: -20 + (buttonBounds.width/2), y: -20 + (buttonBounds.height/2), width: 40, height: 40)<br>            mySymbol.addSymbolEffect(.appear, animated: true)<br>            mySymbol.addSymbolEffect(.variableColor, animated: true)<br>            mySymbol.addSymbolEffect(.scale.up, animated: true)<br>            mySymbol.addSymbolEffect(.bounce, options: .repeating)<br>            mySymbol.tag = id<br>            <br>            // Create the button view, add the symbol image view, and set up the target action<br>            let buttonView = UIButton()<br>            buttonView.frame = tempPos[id]<br>            buttonView.backgroundColor = .orange<br>            buttonView.layer.opacity = 0.9<br>            buttonView.clipsToBounds = true<br>            buttonView.layer.cornerRadius = 95/2<br>            buttonView.addSubview(mySymbol)<br>            buttonView.addTarget(self, action: #selector(tappedLeft), for: .touchUpInside)<br>            buttonView.tag = id<br>            <br>            // Store the button and symbol image view in their respective arrays<br>            buttonsLefts.append(buttonView)<br>            symbols.append(mySymbol)<br>            <br>            // Add the button view to the main view<br>            view.addSubview(buttonView)<br>        }<br>    }<br>    <br>    // Function to initialize the right player&#39;s buttons and symbols<br>    func initializerPlayerRight() {<br>        // Define the positions for the right player&#39;s buttons<br>        positionC = CGRect(x: (width*0.75) - (buttonBounds.width/2) - 50, y: (height/2) - (buttonBounds.height/2), width: buttonBounds.width, height: buttonBounds.height)<br>        positionA = CGRect(x: (width*0.75) - (buttonBounds.width/2) + 80, y: (height/2) - (buttonBounds.height/2)-80, width: buttonBounds.width, height: buttonBounds.height)<br>        positionB = CGRect(x: (width*0.75) - (buttonBounds.width/2) + 80, y: (height/2) - (buttonBounds.height/2)+80, width: buttonBounds.width, height: buttonBounds.height)<br>        <br>        // Store the button positions in an array and shuffle them<br>        positions = [positionA, positionB, positionC]<br>        var tempPos = positions.shuffled()<br>        <br>        // Create three buttons for the right player with symbols from the selectedNames array<br>        for id in 0...2 {<br>            // Declare the symbol image view<br>            let mySymbol: UIImageView = {<br>                let imageView = UIImageView()<br>                imageView.image = UIImage(systemName: selectedNames[id])<br>                imageView.contentMode = .scaleAspectFit<br>                return imageView<br>            }()<br>            <br>            // Set the symbol image view&#39;s position and add animating effects<br>            mySymbol.frame = CGRect(x: -20 + (buttonBounds.width/2), y: -20 + (buttonBounds.height/2), width: 40, height: 40)<br>            mySymbol.addSymbolEffect(.appear, animated: true)<br>            mySymbol.addSymbolEffect(.variableColor, animated: true)<br>            mySymbol.addSymbolEffect(.scale.up, animated: true)<br>            mySymbol.addSymbolEffect(.bounce, options: .repeating)<br>            mySymbol.tag = id<br>            <br>            // Create the button view, add the symbol image view, and set up the target action<br>            let buttonView = UIButton()<br>            buttonView.frame = tempPos[id]<br>            buttonView.backgroundColor = .brown<br>            buttonView.layer.opacity = 0.9<br>            buttonView.clipsToBounds = true<br>            buttonView.layer.cornerRadius = 95/2<br>            buttonView.addSubview(mySymbol)<br>            buttonView.addTarget(self, action: #selector(tappedRight), for: .touchUpInside)<br>            buttonView.tag = id<br>            <br>            // Store the button and symbol image view in their respective arrays<br>            buttonRights.append(buttonView)<br>            symbols.append(mySymbol)<br>            <br>            // Add the button view to the main view<br>            view.addSubview(buttonView)<br>        }<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        <br>        // Initialize the left player&#39;s buttons and symbols<br>        initializerPlayerLeft()<br>        <br>        // Initialize the right player&#39;s buttons and symbols<br>        initializerPlayerRight()<br>        <br>        // Initialize the correct symbol for the first round<br>        initializeAnswer()<br>        <br>        // Set up rounded corners for the round label<br>        round.clipsToBounds = true<br>        round.layer.cornerRadius = 20<br>    }<br>}</pre><h3>Conclusion/git</h3><p>There is still plenty I can do to optimize the app, like divide the code into smaller functions or extensions to make it more modular and maintainable. Or, instead of using string array names, use an enum to define the symbol names. that’ll improve code readability and prevent errors and stuff…</p><p><a href="https://github.com/JimmyChao90196/Whack-a-mole.git">GitHub - JimmyChao90196/Whack-a-mole</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96da9e5c1e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/tapping-game-whack-a-mole-f96da9e5c1e7">#203/154 Tapping game(Whack a Mole)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#38 Game introduction with theme song]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/game-introduction-with-theme-song-e2119fd5af7e?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2119fd5af7e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[themsong]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 05:47:28 GMT</pubDate>
            <atom:updated>2023-08-12T04:50:14.483Z</atom:updated>
            <content:encoded><![CDATA[<p>This app is by far the most complex one I’ve ever done. Of course, I’ll be making things even more complicated in the future. But I think this is the first milestone for me. Again… let’s dive into it.</p><p>Let’s delve into the challenges I encountered during this project. I’ll list each one below. To be honest, they were a bit overwhelming for me, but I’m glad to say that I managed to overcome them successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*PdEZkUT3d478kEKnk76gzw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cuHXRC4WLfa5OniWxR_I9A.png" /></figure><h4>- The techniques that were used in this app</h4><h4>- What is CMTime and where to use it</h4><h4>- What is NaN and infinity</h4><h4>- music slider control</h4><h4>- How to prevent music from being reloaded</h4><h4>- How to prevent array index from out-of-range / ternary operator</h4><h4>- The tricks of view compositing</h4><h3>Technique used</h3><p>I used the following techniques to complete the project. It looks not much, and even simple for some people. Yet they are pretty important for settling the fundamentals as a rookie engineer.</p><ul><li>IBOutlet, IBAction</li><li>Use code to create views and add subviews with code</li><li>Use the AVFoundation framework</li><li>Get seconds from the music player</li><li>Set the desired time for the music player</li><li>Time observer</li><li>Create gradient layer</li></ul><h3>What is CMTime and where to use it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wroJtg9WsbtmqVoNPF81Q.png" /><figcaption>CMTime definition</figcaption></figure><p>Now to wrap it up. The CMTime struct is commonly used in media-related tasks, such as handling video and audio timestamps, synchronization, seeking, and frame rates. It provides a powerful and flexible way to represent and manipulate time values in media contexts.</p><p>It let us measure time in a very precise way.</p><p>I use it in a time observer, in the function addPeriodicTimeObserver requires a time interval. And the interval is a CMTime type.</p><pre>// This function sets up an observer to call every 0.5 seconds.<br>func playerObserver() {<br>    var dur: Float = 0.0  // Variable to store the duration of the music in seconds.<br>    var sec: Float = 0.0  // Variable to store the current playback time in seconds.<br><br>    // Create a time interval of 0.5 seconds using CMTime.<br>    let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))<br><br>    // Add a periodic time observer to the musicPlayer.<br>    // This block of code will be executed every 0.5 seconds as specified by the interval.<br>    musicPlayer.addPeriodicTimeObserver(forInterval: interval, queue: .main) { CMTime in<br>        <br>        // Get the duration of the currently playing item in seconds and store it in &#39;dur&#39;.<br>        dur = Float(self.musicPlayer.currentItem?.duration.seconds ?? 0)<br>        <br>        // Get the current playback time in seconds and store it in &#39;sec&#39;.<br>        sec = Float(self.musicPlayer.currentTime().seconds)<br>        <br>        // Calculate the remaining time in seconds.<br>        var rem = (dur - sec)<br><br>        // Calculate the current playback time as a fraction of the total duration.<br>        let val = sec / dur<br>        <br>        // Check if &#39;rem&#39; is NaN (Not a Number) or Infinite. If so, set it to 0.<br>        guard !(rem.isNaN || rem.isInfinite) else {<br>            return rem = 0<br>        }<br>        <br>        // Update the musicSliderView&#39;s value to represent the progress of the playback.<br>        self.musicSliderView.value = val<br>        <br>        // Format the current time and remaining time as minutes and seconds with leading zeros.<br>        let currentSecText = String(format: &quot;%.2d&quot;, Int(sec) % 60)<br>        let currentMinText = String(Int(sec) / 60)<br>        let remainSecText = String(format: &quot;%.2d&quot;, Int(rem) % 60)<br>        let remainMinText = String(Int(rem) / 60)<br>        <br>        // Update the labels to display the current and remaining time in the format &quot;mm:ss&quot;.<br>        self.currentTime.text = currentMinText + &quot;:&quot; + currentSecText<br>        self.duration.text = remainMinText + &quot;:&quot; + remainSecText<br>    }<br>}</pre><h4>What is NaN and infinity?</h4><p>This error is killing me, cause I have no idea what’s that all about.</p><pre>34404: Fatal error: Float value cannot be converted to Int becauses<br>it is either infinite or NaN</pre><p>It happened when I was trying to convert a float value to an integer. It’s a simple task for most circumstances.</p><pre>            let currentSecText = String(format: &quot;%.2d&quot;, Int(sec)%60)<br>            let currentMinText = String(Int(sec)/60)//Error<br>            let remainSecText = String(format: &quot;%.2d&quot;, Int(rem)%60)//Error<br>            let remainMinText = String(Int(rem)/60)<br>NaN (Not a Number): NaN stands for “Not a Number.” It’s a special value that represents something that is not a valid number. It’s like saying, “I don’t know what this number is.” For example, if you try to do something that doesn’t make sense with numbers, the result might be NaN. Like the result of dividing zero by zero.</pre><p><strong>NaN </strong>stands for “Not a Number.” It’s a special value that represents something that is not a valid number. It’s like saying, “I don’t know what this number is.” For example, if you try to do something that doesn’t make sense with numbers, the result might be NaN. Like dividing zero by zero.</p><p><strong>Infinity:</strong> Infinity is like a super big number that goes on forever.</p><p><strong>Solution: </strong>We need to add some prevention mechanism to prevent the value from being too big or makes no sense.</p><pre>            guard !(rem.isNaN || rem.isInfinite) else {<br>                return rem = 0<br>            }</pre><p><strong>The cause:</strong> Since I couldn’t solve the problem on my own, I decided to seek help from Peter. When I approached him, he immediately pointed out that the issue might be occurring because the duration property and second property are indefinite <strong>before the player item gets loaded</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*EOCXq9VgQL2Od-qhSZ7mNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*nBZnvcggXNqtZzElLYukIA.png" /></figure><p><strong>Optional solution: </strong>If the condition is not met (i.e., the AVPlayerItem is not ready to play), the code block inside the guard statement is executed, and the return statement is encountered, causing the playerObserver() function to exit immediately.</p><pre><br> guard self.musicPlayer.currentItem?.status == .readyToPlay else {<br>         return <br> }</pre><h3>Slider control(Set time)</h3><pre>    @IBAction func musicSlider(_ sender: UISlider) {<br>        var val:Float = Float(sender.value)<br>        let dur:Float = Float(self.musicPlayer.currentItem?.duration.seconds ?? 0)<br>        <br>        val = dur*val<br>        let time = CMTimeMake(value: Int64(val), timescale: 1)<br>        musicPlayer.seek(to: time)<br>    }</pre><p>This one is slightly easier than the previous challenge. Just a few lines of code. Nothing to worry about! Let’s go.</p><p>First, we retrieve the value from the slider. <strong>But noted that the range of value is 0–1.</strong> We need it to be second.</p><p>So we multiply the value by the total duration of the music which can be obtained with self.musicPlayer.currentItem? .duration.second ?? 0 . And now our value is converted to seconds.</p><p>But <strong>seek </strong>function requires a <strong>CMTime</strong> in order to set the player time. So again, we are going to use <strong>CMTimeMake </strong>to convert the value from second to <strong>CMTime.</strong></p><p>And that’s how you set the time for the music player.</p><p>Wait. You are still wondering what that ?? represents right? It’s called nil-coalescing. <strong>A different way to unwrap an “optional”</strong>.</p><h3>How to prevent music from being reloaded</h3><pre>@IBAction func playButton(_ sender: UIButton) {<br>    if musicPlayer.timeControlStatus == .playing {<br>        // The music is already playing, so pause it and change the button icon.<br>        sender.setBackgroundImage(UIImage(systemName: &quot;play.circle&quot;), for: .normal)<br>        musicPlayer.pause()<br>    } else {<br>        // If the music player doesn&#39;t have a currently playing item, then load the music.<br>        if musicPlayer.currentItem == nil {<br>            let url = Bundle.main.url(/service/forresource: songs[index], withExtension: &quot;mp3&quot;)<br>            let playItem = AVPlayerItem(url: url!)<br>            musicPlayer.replaceCurrentItem(with: playItem)<br>        }<br>        <br>        // Now, the music player either has the item loaded or it already had an item.<br>        // So, we can start or resume playing the music and change the button icon.<br>        sender.setBackgroundImage(UIImage(systemName: &quot;pause.circle&quot;), for: .normal)<br>        musicPlayer.play()<br>    }</pre><p>To prevent the music from being reloaded every time the user presses the play button, we can simply add an if statement to see if the music player already has a currently playing item. If it does, then there’s no need to reload the music, and you can simply resume playback. If it doesn’t have a currently playing item (meaning it’s empty), then <strong>you can load the new music according to the current index and start playing it.</strong></p><h3>How to prevent array index from out-of-range</h3><pre>    @IBAction func SwipeLeft(_ sender: Any) {<br>        index = (index + 1) % 3<br>        //logger.info(&quot;\(self.index)&quot;)<br>        PageControl.currentPage = index<br>        updateUI()<br>    }<br>    <br>    @IBAction func SwipeRight(_ sender: Any) {<br>        index -= 1<br>        index = index &lt; 0 ?  2 : index<br>        <br>        //logger.info(&quot;\(self.index)&quot;)<br>        PageControl.currentPage = index<br>        updateUI()<br>    }</pre><p>The index is used to switch between songs and UI elements, when it’s out of range. The app will likely crash or be unable to display certain information.</p><p>We can use % to loop over the index from 0 to 2. No matter how big the input value is.</p><p>We can also use the <strong>ternary operator </strong>to do so. The ternary operator is just a fancy name for the <strong>simplified if statement</strong>. It has a simple structure. Place a <strong>bool</strong> and an ? at the beginning and place the result of <strong>true and false separate</strong> by : .</p><pre>//If the index is smaller than 0, the index is set to 2, else do nothing<br>index = index &lt; 0 ?  2 : index</pre><h3>The tricks of view compositing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8BtWO_IgMj6P9qVHQDiUg.png" /><figcaption>The view is being referenced. But its original position is out of bound</figcaption></figure><pre>func scrollInitializer(){<br>        //Scroll view section, willbe wrapped to function later<br>        introView.frame = CGRect(x: 0, y: 0, width: 393, height: 235)<br>        introScrollView.contentSize = CGSize(width: introScrollView.frame.width*2, height: introScrollView.frame.height)<br>        introScrollView.isPagingEnabled = true<br>        <br>        <br>        //Theme song view<br>        themeSongView.layer.cornerRadius = 20<br>        <br>        //Merge themeSongView and introView to scrollView<br>        introScrollView.addSubview(introView)<br>        introScrollView.addSubview(themeSongView)<br>        view.addSubview(introScrollView)<br>    }</pre><p>Theme song view is actually a subview of the scroll view. I’ve noticed that it’s much more efficient to start by creating a subview in Interface Builder, and then simply add it to the scroll view using code. This approach gives me a better overview of your design before you start placing elements with pure code.</p><h3>Overall Source code</h3><pre>import UIKit<br>import OSLog<br>import AVFoundation<br>import AVKit<br><br>class ViewController: UIViewController {<br>    let logger = Logger()<br><br>    // Arrays holding introduction contents and titles for different topics.<br>    let introContents = [&quot;...&quot;, &quot;...&quot;, &quot;...&quot;]<br>    let introTitles = [&quot;Life is strange 1&quot;, &quot;Life is strange 2&quot;, &quot;Hollow knight&quot;]<br><br>    // Arrays holding poster images and songs for different topics.<br>    let posters = [&quot;...&quot;, &quot;...&quot;, &quot;...&quot;]<br>    let songs = [&quot;01&quot;, &quot;02&quot;, &quot;03&quot;]<br>    var song = &quot;02&quot;<br><br>    // Use &#39;index&#39; to switch between different topics.<br>    var index: Int = 0<br><br>    // Views and layers for gradient backgrounds.<br>    let gradientLayer = CAGradientLayer()<br>    let gradientLayer02 = CAGradientLayer()<br><br>    // Declare scrollView with code to prevent it from being killed.<br>    var introScrollView = UIScrollView(frame: CGRect(x: 0, y: 575, width: 393, height: 235))<br><br>    // Music player.<br>    let musicPlayer = AVPlayer()<br><br>    // Outlet variables connected to the Interface Builder.<br>    // These are views and UI elements displayed on the screen.<br>    @IBOutlet var poster: UIImageView!<br>    @IBOutlet var introContent: UITextView!<br>    @IBOutlet var introTitle: UILabel!<br>    @IBOutlet var PageControl: UIPageControl!<br>    @IBOutlet var gradientView: UIView!<br>    @IBOutlet var themeSongView: UIView!<br>    @IBOutlet var introView: UIView!<br>    @IBOutlet var duration: UILabel!<br>    @IBOutlet var currentTime: UILabel!<br>    @IBOutlet var musicSliderView: UISlider!<br>    @IBOutlet var backWardButton: UIButton!<br>    @IBOutlet var forwardButton: UIButton!<br>    @IBOutlet var playButtonView: UIButton!<br><br>    // IBActions triggered by user interactions.<br>    @IBAction func SwipeLeft(_ sender: Any) {<br>        // Move to the next topic using modulo to loop back to the first topic when reaching the end.<br>        index = (index + 1) % 3<br>        PageControl.currentPage = index<br>        updateUI()<br>    }<br><br>    @IBAction func SwipeRight(_ sender: Any) {<br>        // Move to the previous topic using modulo to loop back to the last topic when reaching the beginning.<br>        index -= 1<br>        index = index &lt; 0 ? 2 : index<br>        PageControl.currentPage = index<br>        updateUI()<br>    }<br><br>    @IBAction func buttonNext(_ sender: UIButton) {<br>        // Move to the next topic using modulo to loop back to the first topic when reaching the end.<br>        index = (index + 1) % 3<br>        PageControl.currentPage = index<br>        updateUI()<br>    }<br><br>    @IBAction func buttonPrevious(_ sender: UIButton) {<br>        // Move to the previous topic using modulo to loop back to the last topic when reaching the beginning.<br>        index -= 1<br>        index = index &lt; 0 ? 2 : index<br>        PageControl.currentPage = index<br>        updateUI()<br>    }<br><br>    @IBAction func segmentControl(_ sender: UISegmentedControl) {<br>        // Change the visible section of the scrollView based on the selected segment.<br>        if sender.selectedSegmentIndex == 0 {<br>            let currentRect = introView.frame<br>            introScrollView.scrollRectToVisible(currentRect, animated: true)<br>        } else {<br>            let currentRect = themeSongView.frame<br>            introScrollView.scrollRectToVisible(currentRect, animated: true)<br>        }<br>    }<br><br>    @IBAction func PageUpdate(_ sender: UIPageControl) {<br>        // Update &#39;index&#39; to match the currently selected page on the UIPageControl.<br>        index = PageControl.currentPage<br>        updateUI()<br>    }<br><br>    @IBAction func musicSlider(_ sender: UISlider) {<br>        // Adjust the music player&#39;s playback time based on the position of the slider.<br>        var val: Float = Float(sender.value)<br>        let dur: Float = Float(self.musicPlayer.currentItem?.duration.seconds ?? 0)<br>        val = dur * val<br>        let time = CMTimeMake(value: Int64(val), timescale: 1)<br>        musicPlayer.seek(to: time)<br>    }<br><br>    @IBAction func playButton(_ sender: UIButton) {<br>        if musicPlayer.timeControlStatus == .playing {<br>            // If music is playing, pause it and change the button icon.<br>            sender.setBackgroundImage(UIImage(systemName: &quot;play.circle&quot;), for: .normal)<br>            musicPlayer.pause()<br>        } else {<br>            // If music is paused or stopped, check if the current item is empty (nil).<br>            // If it&#39;s empty, load the music for the current topic and start playing.<br>            if musicPlayer.currentItem == nil {<br>                let url = Bundle.main.url(/service/forresource: songs[index], withExtension: &quot;mp3&quot;)<br>                let playItem = AVPlayerItem(url: url!)<br>                musicPlayer.replaceCurrentItem(with: playItem)<br>            }<br>            // Change the button icon to pause and start playing the music.<br>            sender.setBackgroundImage(UIImage(systemName: &quot;pause.circle&quot;), for: .normal)<br>            musicPlayer.play()<br>        }<br>    }<br><br>    // Function to add a gradient to the views.<br>    func grad() {<br>        // Add a gradient to &#39;gradientView&#39;.<br>        gradientLayer.frame = gradientView.bounds<br>        gradientLayer.colors = [<br>            UIColor.clear.cgColor,<br>            UIColor.black.cgColor<br>        ]<br>        gradientLayer.locations = [0, 0.3, 1]<br>        gradientView.layer.addSublayer(gradientLayer)<br>    }<br><br>    func grad02() {<br>        // Add a gradient to &#39;themeSongView&#39;.<br>        gradientLayer02.frame = themeSongView.bounds<br>        gradientLayer02.colors = [<br>            UIColor.darkGray.cgColor,<br>            UIColor.black.cgColor,<br>            UIColor.black.cgColor,<br>            UIColor.darkGray.cgColor<br>        ]<br>        gradientLayer02.locations = [0, 0.25, 0.75, 1]<br>        themeSongView.layer.insertSublayer(gradientLayer02, at: 0)<br>    }<br><br>    // Function to update the UI when switching between topics.<br>    func updateUI() {<br>        // Update content, poster image, and music for the current topic.<br>        let title: String = introTitles[index]<br>        let content: String = introContents[index]<br>        poster.image = UIImage(named: posters[index])<br>        introTitle.text = title<br>        introContent.text = content<br><br>        // Load the music for the current topic.<br>        let url = Bundle.main.url(/service/forresource: songs[index], withExtension: &quot;mp3&quot;)<br>        let playItem = AVPlayerItem(url: url!)<br>        musicPlayer.replaceCurrentItem(with: playItem)<br><br>        // Reinitialize gradients for the views.<br>        grad()<br>        grad02()<br>    }<br><br>    // Function to initialize the scrollView and its subviews.<br>    func scrollInitializer() {<br>        // Set up the scrollView and add &#39;introView&#39; and &#39;themeSongView&#39; as subviews.<br>        introView.frame = CGRect(x: 0, y: 0, width: 393, height: 235)<br>        introScrollView.contentSize = CGSize(width: introScrollView.frame.width * 2, height: introScrollView.frame.height)<br>        introScrollView.isPagingEnabled = true<br>        introScrollView.addSubview(introView)<br>        introScrollView.addSubview(themeSongView)<br>        view.addSubview(introScrollView)<br>    }<br><br>    // Function to observe and update the music player&#39;s progress every 0.5 seconds.<br>    func playerObserver() {<br>        var dur: Float = 0.0<br>        var sec: Float = 0.0<br>        let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))<br>        musicPlayer.addPeriodicTimeObserver(forInterval: interval, queue: .main) { CMTime in<br>            // Get the current duration and current time of the music player.<br>            dur = Float(self.musicPlayer.currentItem?.duration.seconds ?? 0)<br>            sec = Float(self.musicPlayer.currentTime().seconds)<br><br>            // Calculate the remaining time and the music slider value (current time / duration).<br>            var rem = (dur - sec)<br>            let val = sec / dur<br><br>            // Ensure that &#39;rem&#39; is a finite value (not NaN or infinite).<br>            // If it&#39;s not, set it to 0.<br>            guard !(rem.isNaN || rem.isInfinite) else {<br>                return rem = 0<br>            }<br><br>            // Update the music slider&#39;s value and labels showing the current time and remaining time.<br>            self.musicSliderView.value = val<br>            let currentSecText = String(format: &quot;%.2d&quot;, Int(sec) % 60)<br>            let currentMinText = String(Int(sec) / 60)<br>            let remainSecText = String(format: &quot;%.2d&quot;, Int(rem) % 60)<br>            let remainMinText = String(Int(rem) / 60)<br>            self.currentTime.text = currentMinText + &quot;:&quot; + currentSecText<br>            self.duration.text = remainMinText + &quot;:&quot; + remainSecText<br>        }<br>    }<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Update UI at the beginning.<br>        updateUI()<br><br>        // Initialize the scrollView and set up player observer.<br>        scrollInitializer()<br>        playerObserver()<br>    }<br>}</pre><h3>Conclusion/ Git</h3><p>I must admit, the process of making this app with only a few functionality is a lot harder than I thought. But I certainly learned a lot from it.</p><p><a href="https://github.com/JimmyChao90196/StreamingApp.git">GitHub - JimmyChao90196/StreamingApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2119fd5af7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/game-introduction-with-theme-song-e2119fd5af7e">#38 Game introduction with theme song</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UIBezier path 與 IBAction的應用]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/uibezier-path-%E8%88%87-ibaction%E7%9A%84%E6%87%89%E7%94%A8-c27029fa124b?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27029fa124b</guid>
            <category><![CDATA[ibaction]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uibezierpath]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 14:42:04 GMT</pubDate>
            <atom:updated>2023-07-22T14:42:04.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>The traffic of value</h3><p>In todays topic, we’ll be discussing how to sent value to view controller and how pie chart works in swift. The goal is to let user interact with the chart and value, and get real-time feedback. Let’s dive into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*kHFUvCcxnH8hngtGpbliVA.gif" /></figure><h4>Slider and stepper</h4><p>In the interface builder window, we can easily add any view to the view controller. For this example, we’ll use a slider and stepper view. Now, let’s open the assistant manager. From here, we can simply control-click and drag our slider and stepper into the view controller. A pop-up window will appear.</p><p>Make sure the<strong> outlet</strong> is set to <strong>“action”</strong> and we’re almost there! Now, we can receive data from the slider and stepper.</p><p>Just keep a one things in mind:</p><ul><li>We’ll need a <strong>computed property</strong> to redraw the pie-chart whenever the value has been altered. This way, we’ll get real-time feedback, just as I mentioned earlier.</li></ul><h4>Stepper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EURSEoU3pRIiIFjumyvRTw.png" /><figcaption>Stepper view</figcaption></figure><pre>    //Receive value from stepper<br>    @IBAction func stepDidStep(_ sender: UIStepper) {<br>        let value = sender.value<br>        division = Int(value)<br>        print(division)<br>    }<br>    <br>    //This computed property will call the pieFunc when ever the value has been altered<br>    var division:Int = 5{<br>        didSet{<br>            pieFunc(view, division)<br>        }<br>    }</pre><h4>Slider</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw2pfxiudJfo-bBYpQZA7Q.png" /><figcaption>Slider view</figcaption></figure><pre>    //This line recieves data from the slider<br>    @IBAction func sliderDidSlide(_ sender:UISlider){<br>        let value = sender.value<br>        progress = value<br>        print(&quot;\(progress)&quot;)<br>    }<br>    <br>    <br>    //This property is a computed property, it calls &quot;iterChart&quot; when the value is altered<br>    var progress:Float = 0.2{<br>        didSet{<br>            iterChart()<br>            updateLabel()<br>        }<br>    }</pre><h4>Circular progress chart</h4><p>Nothing special here, the circular progress chart is just a function that consists of two smaller functions and loops over 5 to 10 times. But still, let’s take a closer look at these two sub-functions.</p><ul><li>Background circle function: This one represents the grey default area of the chart.</li><li>Progress chart function: This one is fed with the value from the slider and is called whenever the value of the slider (progress) changes. In other words, the parameter value pushes the progress chart further and further as the slider moves.</li></ul><pre> <br>    //We wrap two main functions in here so we can call both of them when evert the value changes<br>    func iterChart(loops:Int=5){<br>        for i in 0..&lt;loops{<br>            <br>            let radius = 300 / Double(loops) * Double(i+1)<br>            let offset = 0.5 / Float(loops) * Float(i+1)<br>            let colorOffset:CGFloat = 1/CGFloat(loops) * CGFloat(i)<br>            <br>            //Add background circle<br>            let bgCircleLayer = backgroundCircle(radius)<br>            bgView.layer.addSublayer(bgCircleLayer)<br>            <br>            <br>            //Add progress to circleView<br>            let progressLayer = progressChart(radius, offset)<br>            progressLayer.strokeColor = CGColor(red: colorOffset, green: 0, blue: 1-colorOffset, alpha: 1)<br>            bgView.layer.addSublayer(progressLayer)<br>        }<br>    }<br>    <br>    <br>    //Create background circle layer<br>    func backgroundCircle(_ radius:Double = 300) -&gt; CAShapeLayer {<br><br>        //Create pie chart layer<br>        let rect = CGRect(x: (-radius/2)+150, y: (-radius/2)+150, width: radius, height: radius)<br>        let bgCirclePath = UIBezierPath(ovalIn: rect)<br>        let bgCircleLayer = CAShapeLayer()<br>        <br>        //Define property of layer, and assign path to it<br>        bgCircleLayer.path = bgCirclePath.cgPath<br>        bgCircleLayer.fillColor = UIColor.clear.cgColor<br>        bgCircleLayer.lineWidth = 10.0<br>        bgCircleLayer.strokeColor = UIColor.gray.cgColor<br>        return bgCircleLayer<br>        }<br><br>    <br>    //Progress chart layer<br>    func progressChart(_ radius:Double = 300, _ charOffset:Float) -&gt; CAShapeLayer {<br>        <br>        //Create instance of CAShapeLayer and UIBezierPath<br>        let rect = CGRect(x: (-radius/2)+150, y: (-radius/2)+150, width: radius, height: radius)<br>        let progressLayer = CAShapeLayer()<br>        var progressPath = UIBezierPath(ovalIn: rect)<br>        <br>        //Define property of layer, and assign path to it<br>        progressPath = UIBezierPath(ovalIn: rect)<br>        progressLayer.path = progressPath.cgPath<br>        progressLayer.fillColor = UIColor.clear.cgColor<br>        progressLayer.lineWidth = 10.0<br>        progressLayer.strokeEnd = CGFloat(progress+charOffset)<br>        progressLayer.strokeColor = CGColor.init(red: 0, green: 0, blue: 1, alpha: 1)<br>        progressLayer.lineCap = .round<br>        return progressLayer<br>        <br>        }</pre><h4>Pie chart</h4><p>Just like circular progress chart. But this one is slightly easier, it’s only a for loop that draw each section of the chart.</p><pre>    func pieFunc(_ superView:UIView, _ divideNum:Int = 5) {<br>        for _ in 1...divideNum{<br>            let percentageLayer = CAShapeLayer()<br>            let endDegree = startDegree + 360.0/Double(divideNum)<br>            let percentagePath = UIBezierPath(arcCenter: .init(x: centerX, y: centerY), radius: 200, startAngle: unitRadians * startDegree, endAngle: unitRadians * endDegree, clockwise: true)<br>            percentageLayer.path = percentagePath.cgPath<br>            percentageLayer.strokeColor  = UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1).cgColor<br>            percentageLayer.lineWidth = 60<br>            percentageLayer.fillColor = UIColor.clear.cgColor<br>                        <br>            superView.layer.addSublayer(percentageLayer)<br>            startDegree = endDegree<br>        }<br>        <br>    }</pre><h4>Overall source code</h4><p>Some comments are added by GPT. And it’s been doing to great job.</p><pre>import UIKit<br>import SwiftUI<br><br>class ViewController: UIViewController {<br>    <br>    // These attributes are for the pie chart<br>    <br>    // A constant to convert degrees to radians<br>    let unitRadians = Double.pi/180.0<br>    <br>    // The starting degree for drawing the pie chart segments<br>    var startDegree: Double = 270<br>    <br>    <br>    // Function to draw the pie chart<br>    func pieFunc(_ superView: UIView, _ divideNum: Int = 5) {<br>        // Loop through the specified number of divisions to draw each segment<br>        for _ in 1...divideNum {<br>            let percentageLayer = CAShapeLayer()<br>            // Calculate the ending degree for the current segment<br>            let endDegree = startDegree + 360.0 / Double(divideNum)<br>            // Create a Bezier path for the pie chart segment<br>            let percentagePath = UIBezierPath(arcCenter: .init(x: centerX, y: centerY), radius: 200, startAngle: unitRadians * startDegree, endAngle: unitRadians * endDegree, clockwise: true)<br>            // Set the path and appearance properties for the segment&#39;s layer<br>            percentageLayer.path = percentagePath.cgPath<br>            percentageLayer.strokeColor = UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1).cgColor<br>            percentageLayer.lineWidth = 60<br>            percentageLayer.fillColor = UIColor.clear.cgColor<br>            <br>            // Add the segment&#39;s layer to the superView&#39;s layer<br>            superView.layer.addSublayer(percentageLayer)<br>            // Update the starting degree for the next segment<br>            startDegree = endDegree<br>        }<br>    }<br>    <br>    // Receive value from the stepper<br>    @IBAction func stepDidStep(_ sender: UIStepper) {<br>        // Get the current value from the stepper<br>        let value = sender.value<br>        // Convert the value to an integer and assign it to the &#39;division&#39; variable<br>        division = Int(value)<br>        // Print the &#39;division&#39; value to the console<br>        print(division)<br>    }<br>    <br>    // This computed property will call &#39;pieFunc&#39; whenever the value of &#39;division&#39; has been altered<br>    var division: Int = 5 {<br>        didSet {<br>            pieFunc(view, division)<br>        }<br>    }<br>    <br>    //-----------below this line is the circular progress chart--------------------<br>    <br>    // Screen size and view size<br>    <br>    // Calculate the x-coordinate of the center of the screen<br>    let centerX = UIScreen.main.bounds.width/2.0<br>    // Calculate the y-coordinate of the center of the screen<br>    let centerY = UIScreen.main.bounds.height/2.0<br>    // Define the size of the circular progress chart<br>    let size = 300.0<br>    // Calculate the offset for centering the circular progress chart<br>    var offset: Double { size / -2.0 }<br>    <br>    // View initialize<br>    <br>    // Create a view to be used as the background for the circular progress chart<br>    let bgView = UIView()<br>    // Create a label to display the progress percentage<br>    let label = UILabel(frame: CGRect(x: 0 , y: 0, width: 300, height: 300))<br>    <br>    // This line receives data from the slider<br>    @IBAction func sliderDidSlide(_ sender: UISlider) {<br>        // Get the current value from the slider<br>        let value = sender.value<br>        // Assign the value to the &#39;progress&#39; variable<br>        progress = value<br>        // Print the &#39;progress&#39; value to the console<br>        print(&quot;\(progress)&quot;)<br>    }<br>    <br>    // This property is a computed property, it calls &#39;iterChart&#39; and &#39;updateLabel&#39; when the value of &#39;progress&#39; has been altered<br>    var progress: Float = 0.2 {<br>        didSet {<br>            // Call &#39;iterChart&#39; to update the circular progress chart<br>            iterChart()<br>            // Call &#39;updateLabel&#39; to update the label displaying the progress percentage<br>            updateLabel()<br>        }<br>    }<br>    <br>    // Label function<br>    func updateLabel() {<br>        // Set the frame and appearance properties for the label displaying the progress percentage<br>        label.frame = CGRect(x: -75 + centerX, y: -25 + 130, width: 150, height: 50)<br>        label.textAlignment = .center<br>        label.font = .systemFont(ofSize: 40)<br>        // Display the progress percentage as an integer<br>        label.text = &quot;\(Int(progress * 100)) % &quot;<br>    }<br>    <br>    // We wrap two main functions in here so we can call both of them whenever the value changes<br>    func iterChart(loops: Int = 5) {<br>        // Loop through the specified number of iterations to draw the circular progress chart<br>        for i in 0..&lt;loops {<br>            // Calculate the radius for the current circle segment<br>            let radius = 300 / Double(loops) * Double(i + 1)<br>            // Calculate the offset for the current circle segment<br>            let offset = 0.5 / Float(loops) * Float(i + 1)<br>            // Calculate the color offset for the current circle segment<br>            let colorOffset: CGFloat = 1 / CGFloat(loops) * CGFloat(i)<br>            <br>            // Add background circle<br>            <br>            // Create a background circle layer with the specified radius<br>            let bgCircleLayer = backgroundCircle(radius)<br>            // Add the background circle layer to the &#39;bgView&#39;<br>            bgView.layer.addSublayer(bgCircleLayer)<br>            <br>            // Add progress to circleView<br>            <br>            // Create a progress chart layer with the specified radius and offset<br>            let progressLayer = progressChart(radius, offset)<br>            // Set the stroke color for the progress chart layer based on the color offset<br>            progressLayer.strokeColor = CGColor(red: colorOffset, green: 0, blue: 1 - colorOffset, alpha: 1)<br>            // Add the progress chart layer to the &#39;bgView&#39;<br>            bgView.layer.addSublayer(progressLayer)<br>        }<br>    }<br>    <br>    // Create background circle layer<br>    func backgroundCircle(_ radius: Double = 300) -&gt; CAShapeLayer {<br>        // Create a rectangular frame for the background circle<br>        let rect = CGRect(x: (-radius/2) + 150, y: (-radius/2) + 150, width: radius, height: radius)<br>        // Create a Bezier path for the background circle<br>        let bgCirclePath = UIBezierPath(ovalIn: rect)<br>        // Create a CAShapeLayer to represent the background circle<br>        let bgCircleLayer = CAShapeLayer()<br>        <br>        // Define properties of the layer and assign the path to it<br>        bgCircleLayer.path = bgCirclePath.cgPath<br>        bgCircleLayer.fillColor = UIColor.clear.cgColor<br>        bgCircleLayer.lineWidth = 10.0<br>        bgCircleLayer.strokeColor = UIColor.gray.cgColor<br>        return bgCircleLayer<br>    }<br>    <br>    // Progress chart layer<br>    func progressChart(_ radius: Double = 300, _ charOffset: Float) -&gt; CAShapeLayer {<br>        // Create a rectangular frame for the progress chart<br>        let rect = CGRect(x: (-radius/2) + 150, y: (-radius/2) + 150, width: radius, height: radius)<br>        // Create a CAShapeLayer to represent the progress chart<br>        let progressLayer = CAShapeLayer()<br>        var progressPath = UIBezierPath(ovalIn: rect)<br>        <br>        // Define properties of the layer and assign the path to it<br>        progressPath = UIBezierPath(ovalIn: rect)<br>        progressLayer.path = progressPath.cgPath<br>        progressLayer.fillColor = UIColor.clear.cgColor<br>        progressLayer.lineWidth = 10.0<br>        progressLayer.strokeEnd = CGFloat(progress + charOffset)<br>        progressLayer.strokeColor = CGColor.init(red: 0, green: 0, blue: 1, alpha: 1)<br>        progressLayer.lineCap = .round<br>        return progressLayer<br>    }<br>    <br><br>  //----------This line below is viewDidLoad function-----------------------<br><br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // Define views property<br>        // Set the frame and background color for the &#39;bgView&#39;<br>        bgView.frame = CGRect(x: centerX + offset, y: centerY + offset, width: size, height: size)<br>        bgView.backgroundColor = UIColor(red: 0.75, green: 0.6, blue: 0.01, alpha: 1)<br>        <br><br>        // Add &#39;bgView&#39; and &#39;label&#39; as subviews of the main view<br>        view.addSubview(bgView)<br>        view.addSubview(label)<br>        <br>        // Call function to make the pie chart<br>        pieFunc(view)<br>        <br>        // Call function to initialize the circular progress chart<br>        iterChart()<br>        // Call function to update the label displaying the progress percentage<br>        updateLabel()<br>    }<br>}</pre><h4>Conclusion/Git</h4><p><a href="https://github.com/JimmyChao90196/PieChart.git">GitHub - JimmyChao90196/PieChart</a></p><p>I’ve had a very challenging experience this time. Of course, there were a few bumps along the way that could be a bit frustrating, but the feeling of accomplishment after solving each problem is rewarded.</p><p>I’m having a great time! I love creating interactive things. There’s this unique sense of fulfillment that comes with it, which makes all the hard work feel incredibly satisfying.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27029fa124b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/uibezier-path-%E8%88%87-ibaction%E7%9A%84%E6%87%89%E7%94%A8-c27029fa124b">UIBezier path 與 IBAction的應用</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#5 Practice: function/class/enum]]></title>
            <link>https://medium.com/@myname90196/5-practice-function-class-enum-3162d2c921e2?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/3162d2c921e2</guid>
            <category><![CDATA[songs]]></category>
            <category><![CDATA[practice]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 03:27:46 GMT</pubDate>
            <atom:updated>2023-07-22T14:20:06.791Z</atom:updated>
            <content:encoded><![CDATA[<h4>First assignment: Try to construct a class with property and methods.</h4><p>Condition:</p><ul><li>Create two class with property and method</li><li>Use the concept of inheritance</li><li>Override function in the sub-class</li><li>Access property and method form object(instance of class)</li></ul><pre>//Class assignment<br>enum gender{<br>    case male<br>    case female<br>}<br><br>//Super class<br>class Animal {<br>    var race:String<br>    var name: String<br>    var sound:String = &quot;Bark! Bark!&quot;<br>    var sex:gender<br>    var legs:Int = 4<br>    var tammable:Bool = true<br>    var furry:Bool = true<br>    var coldBlood:Bool<br>    <br>    init(name: String, sex:gender, coldBlood:Bool, race:String) {<br>        self.name = name<br>        self.sex = sex<br>        self.coldBlood = coldBlood<br>        self.race = race<br>    }<br>    <br>    //Method of super-class<br>    func makeSound() {<br>        print(sound)<br>    }<br>}<br><br><br>//Sub class<br>class Human: Animal {<br>    <br>    static let isIntelegent = true<br>    <br>    func saySomething(word:String){<br>        print(&quot;\(word)&quot;)<br>    }<br>    override func makeSound() {<br>        print(&quot;da da&quot;)<br>    }<br>}<br><br>//Access property and method through object<br>let peter = Human(name: &quot;Peter&quot;, sex: .male, coldBlood: false, race: &quot;Mammals&quot;)<br>let peterGender = peter.sex<br>peter.saySomething(word: &quot;I&#39;m starving mommy!&quot;)<br><br>let buddy = Animal(name: &quot;buddy&quot;, sex: .female, coldBlood: false, race: &quot;Mammals&quot;)<br>let buddyGender = buddy.sex<br>buddy.makeSound()</pre><h4>Second Assignment: Try to use function to print a song that you like</h4><p>I’m gonna choose enjoy, I love the song. It’s lyrics are full of sorrow and regression, disturb and enlightenment. And that moved me deep years ago… Yes, it’s pretty short but that not the reason I choose the song.</p><p>Condition:</p><ul><li>Make each paragraph a function</li><li>Make a big function that contains all the small ones</li></ul><pre>//Function assignment enjoy<br>//Paragraph one<br>func sarrowAway()-&gt;Void{<br>    print(&quot;&quot;&quot;<br>    快把我的悲傷都帶走<br>    不要讓我擁有得太多<br>    知足常樂的那些年頭<br>    擁有無限的自由<br>    <br>    &quot;&quot;&quot;)<br>}<br><br>//Paragraph two<br>func youAndI()-&gt;Void{<br>    print(&quot;&quot;&quot;<br>    你看著我的臉蛋放空<br>    以為我已經擁有得足夠<br>    知足常樂的那些年頭<br>    有你和我<br>    <br>    &quot;&quot;&quot;)<br>}<br><br>//Paragraph three<br>func noNeedToHide()-&gt;Void{<br>    print(&quot;&quot;&quot;<br>    在快樂與悲傷 都寫在我們臉上的那些時代裡<br>    我們不需要去隱藏我們的情緒<br>    <br>    &quot;&quot;&quot;)<br>}<br><br>//Overrall lyrics<br>func enjoy() -&gt;Void{<br>    //First time<br>    sarrowAway()<br>    youAndI()<br>    noNeedToHide()<br>  <br>    //Repeat second time<br>    sarrowAway()<br>    youAndI()<br>    noNeedToHide()<br>    <br>    //Repeat third time<br>    noNeedToHide()<br>    noNeedToHide()<br>}<br><br>//Call function<br>enjoy()</pre><h4>Third Assignment: Use AI as virtual teacher</h4><p>Condition:</p><ul><li>Make an trigonometric converter</li><li>Input: degrees, and trigonometry functions</li><li>Output: radians</li></ul><pre>//AI assignment<br>//題目：寫一個 Swift 函數，接受一個角度（以度數為單位）作為輸入，並計算並輸出該角度的正弦值、餘弦值和正切值。<br><br>//Trigonometric functions<br>enum trigs{<br>    case sine<br>    case cosine<br>    case tangent<br>}<br><br>//Main function<br>func trigConvert( trig:trigs, of degree:Double) -&gt; Double{<br>    let radians = degree * CGFloat.pi/180<br>    let result:Double<br>    <br>    //Use switch as if statement<br>    switch trig{<br>    case .sine: result = sin(radians)<br>    case .cosine: result = cos(radians)<br>    case .tangent: result = tan(radians)<br>    }<br>    <br>    return result<br>}<br><br>//Call function<br>trigConvert(trig: .cosine, of: 360)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3162d2c921e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#142 迷因與費波納其數的應用]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/142-%E8%BF%B7%E5%9B%A0%E8%88%87%E8%B2%BB%E6%B3%A2%E7%B4%8D%E5%85%B6%E6%95%B8%E7%9A%84%E6%87%89%E7%94%A8-abfb8bf447d2?source=rss-1814435be66------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfb8bf447d2</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[mème]]></category>
            <category><![CDATA[fibonacci-sequence]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jimmy chao]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 07:38:22 GMT</pubDate>
            <atom:updated>2023-07-20T07:38:22.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>奇怪的知識增加了(加上動態)</h3><p>在開始之前我們先來看看這個我做的迷因吧～ 因為我覺得轉成gif 檔後實在還蠻好笑的，我覺得今天這篇文章還是寫中文好了，比較有迷因的韻味！或許其實沒那麼好笑，但是也歡迎分享gif file 喔！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4Tq6zL6PwPJd4eixBlheGw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*flEtKPAQBtGTXKcIMQQ-zQ.png" /></figure><h4>背後的原理</h4><p>其實這樣的排列有主要兩個大重點</p><ul><li>如何做出費波納期數列</li><li>如何做出sine wave 的效果</li></ul><p>就讓我們一一來解析吧！</p><h4>如何做出fibonacci flower</h4><p>既然是向外擴張的形狀，我們就姑且稱他為花吧！<br>在這個function 中，有調整Translation的 Transform，也有調整Rotation的Transform。<br>而這些變形的工具呢，都被輸入了 angle or coordX and coordY 的參數。藉由angle中的magic number(137.5) 我們可以將圖型旋轉及擺放到類似太陽花種子排列的樣子。</p><pre>func fibFlower(centerX: Double, centerY: Double, amp:Double = 0.025, freq:Double = 15, offset:Double = 0.0,  radius: Double, scale:Double ,num: Int){<br>    <br>    //Use for loop to calculate fibonacci flower petal position<br>    for i in 0..&lt;num {<br>        <br>        //Calculate fibonacci angle in radian<br>        let angle = 137.5 * Double(i)<br>        let coordX = cos(angle) * Double(i)<br>        let coordY = sin(angle) * Double(i)<br>        <br>        // Draw shape<br>        let path = UIBezierPath()<br>        path.move(to: CGPoint(x: 0, y: 0))<br>        path.addLine(to: CGPoint(x: 0, y: 100))<br>        path.addLine(to: CGPoint(x: 200, y: 30))<br>        path.close()<br><br>     <br>        <br>        //Get center<br>        let centerX = centerX<br>        let centerY = centerY<br>        <br>        //Initialize transform<br>        var transform = CGAffineTransform()<br>        <br><br><br>        //Create sine wave<br>        let amp:Double = amp<br>        let freq:Double = freq<br>        let offset:Double = offset<br>        <br>        //Initial scale<br>        var scale = scale<br><br>        //Store normalize distance double<br>        let dist = Double(i) / Double(num) - 1.0<br>        <br>        //PostEdit scale<br>        var pScale = sin(dist*freq+offset)<br>        //Normalize value<br>        pScale = (pScale + 1) / 2<br>        scale *= pScale<br>        scale += amp<br>        <br>        transform = CGAffineTransform(scaleX: scale, y: scale)<br>        path.apply(transform)<br>        <br>        <br>        //Apply direction to path<br>        transform = CGAffineTransform(translationX: 0, y: path.bounds.midY * -1)<br>            .concatenating(CGAffineTransform(rotationAngle: CGFloat(angle)))<br>        <br>        var newTransform = CGAffineTransform(rotationAngle: CGFloat(angle))<br>        path.apply(transform)<br><br>        <br>        //Apply fibonacci position to path<br>        transform = CGAffineTransform(translationX: coordX, y: coordY)<br>            .concatenating(CGAffineTransform(translationX: centerX, y: centerY))<br>        path.apply(transform)<br>        <br>        <br>        <br>        //Assign path to layer and render layer to view<br>        let triangleLayer = CAShapeLayer()<br>        <br>        <br>        //Add path to layer and add layer to bgView as subview<br>        triangleLayer.path = path.cgPath<br>        triangleLayer.fillColor = .init(red: 0.35, green: 0.1, blue: 1, alpha: 1)<br>        triangleLayer.shadowColor = .init(red: 0, green: 0, blue: 0, alpha: 1)<br>        triangleLayer.opacity = 1<br>        triangleLayer.shadowOffset = CGSize(width: -1, height: 1)<br>        triangleLayer.shadowRadius = CGFloat(20)<br>        <br>        bgView.layer.addSublayer(triangleLayer)<br>      <br>    }<br>}</pre><h4>如何做出Sine wave 的效果</h4><p>做出Sinewave 有幾個參數是十分重要的</p><ul><li>Amplitude- 強度</li><li>Frequency- 頻率</li><li>Offset- 位移</li></ul><p>如下面的code所示，利用離中心點由遠到近的關係，做出一個從value 0 到 1 的 Range。然後這個Range 再配合了frequency and offset 並被置入 sin function 中時，會被轉換成 -1 到 1 的值，所以 +1 並且 /2 的動作也是為了 normalize這個 value 喔！</p><p>最後在配合amplitude和 scale 就可以有氣功波大小差異啦！當然還是要透過 offset 來做出有波動的感覺。</p><pre>//Create sine wave<br>        let amp:Double = amp<br>        let freq:Double = freq<br>        let offset:Double = offset<br>        <br>        //Initial scale<br>        var scale = scale<br><br>        //Store normalize distance double<br>        let dist = Double(i) / Double(num) - 1.0<br>        <br>        //PostEdit scale<br>        var pScale = sin(dist*freq+offset)<br>        //Normalize value<br>        pScale = (pScale + 1) / 2<br>        scale *= pScale<br>        scale += amp<br>        <br>        transform = CGAffineTransform(scaleX: scale, y: scale)<br>        path.apply(transform)</pre><h4>加上背景</h4><p>呼叫function，加上圖案背景。總算是完成啦！</p><pre><br>//Call fibFlower function<br>fibFlower(centerX: centerWidth, centerY: centerHeight, amp: 0.035, freq: 10, offset: 8, radius: 1.5, scale: 0.08, num: 200)<br><br><br>//Post production<br>let heart = UILabel(frame: CGRect(x: 20, y: 30, width: 50 , height: 50))<br>let heart02 = UILabel(frame: CGRect(x: 40, y: 40, width: 50 , height: 50))<br><br><br>heart.font = UIFont.systemFont(ofSize: 50)<br>heart02.font = UIFont.systemFont(ofSize: 40)<br>heart.text = &quot;💖&quot;<br>heart02.text = &quot;💞&quot;<br><br><br>bgView.addSubview(heart)<br>bgView.addSubview(heart02)</pre><h4>全部Source code</h4><pre>import UIKit<br>import Foundation<br>import PlaygroundSupport<br><br><br>//Create background<br>let bgRect = CGRect(x: 0, y: 0, width: 300, height: 300)<br>let bgView = UIImageView(image: UIImage(named: &quot;Meme.jpg&quot;))<br><br>bgView.frame = bgRect<br>bgView.contentMode = .scaleAspectFill<br>bgView.layer.borderWidth = 10<br>bgView.layer.borderColor = .init(red: 1, green: 0.5, blue: 0.1, alpha: 1)<br>bgView.layer.cornerRadius = 12.5<br>bgView.clipsToBounds = true<br><br><br><br>//Get screen size<br>let bgBounds = bgView.bounds<br>let screenWidth = bgView.bounds.width<br>let screenHeight = bgView.bounds.height<br>let centerWidth = screenWidth/2<br>let centerHeight = screenHeight/2<br><br><br>// Calculate fibonacci number<br>func fibFlower(centerX: Double, centerY: Double, amp:Double = 0.025, freq:Double = 15, offset:Double = 0.0,  radius: Double, scale:Double ,num: Int){<br>  <br>  <br>    <br>    //Use for loop to calculate fibonacci flower petal position<br>    for i in 0..&lt;num {<br>        <br>        //Calculate fibonacci angle in radian<br>        let angle = 137.5 * Double(i)<br>        let coordX = cos(angle) * Double(i)<br>        let coordY = sin(angle) * Double(i)<br>        <br>        // Draw shape<br>        let path = UIBezierPath()<br>        path.move(to: CGPoint(x: 0, y: 0))<br>        path.addLine(to: CGPoint(x: 0, y: 100))<br>        path.addLine(to: CGPoint(x: 200, y: 30))<br>        path.close()<br><br>        <br>        <br>        //Store normalize distance double<br>        var nDists = [Double]()<br>        let dist = Double(i) / Double(num) - 1.0<br>        nDists.append(dist)<br>        <br>        <br>        //Create size wave<br>        let amp:Double = amp<br>        let freq:Double = freq<br>        let offset:Double = offset<br>        <br>        <br>        <br>        //Get center<br>        let centerX = centerX<br>        let centerY = centerY<br>        <br>        //Initialize transform<br>        var transform = CGAffineTransform()<br>        <br>        <br>        //Initial scale<br>        var scale = scale<br>        <br>        //PostEdit scale<br>        var pScale = sin(dist*freq+offset)<br>        //Normalize value<br>        pScale = (pScale + 1) / 2<br>        scale *= pScale<br>        scale += amp<br>        <br>        transform = CGAffineTransform(scaleX: scale, y: scale)<br>        path.apply(transform)<br>        <br>        <br>        //Apply direction to path<br>        transform = CGAffineTransform(translationX: 0, y: path.bounds.midY * -1)<br>            .concatenating(CGAffineTransform(rotationAngle: CGFloat(angle)))<br>        <br>        var newTransform = CGAffineTransform(rotationAngle: CGFloat(angle))<br>        path.apply(transform)<br><br>        <br>        //Apply fibonacci position to path<br>        transform = CGAffineTransform(translationX: coordX, y: coordY)<br>            .concatenating(CGAffineTransform(translationX: centerX, y: centerY))<br>        <br>        path.apply(transform)<br>        <br>        <br>        <br>        //Assign path to layer and render layer to view<br>        let triangleLayer = CAShapeLayer()<br>        triangleLayer.path = path.cgPath<br>        triangleLayer.fillColor = .init(red: 0.35, green: 0.1, blue: 1, alpha: 1)<br>        triangleLayer.shadowColor = .init(red: 0, green: 0, blue: 0, alpha: 1)<br>        triangleLayer.opacity = 1<br>        triangleLayer.shadowOffset = CGSize(width: -1, height: 1)<br>        triangleLayer.shadowRadius = CGFloat(20)<br>        <br>        bgView.layer.addSublayer(triangleLayer)<br>    }<br>}<br><br><br>//Call fibFlower function<br>fibFlower(centerX: centerWidth, centerY: centerHeight, amp: 0.035, freq: 10, offset: 8, radius: 1.5, scale: 0.08, num: 200)<br><br><br>//Post production<br>let heart = UILabel(frame: CGRect(x: 20, y: 30, width: 50 , height: 50))<br>let heart02 = UILabel(frame: CGRect(x: 40, y: 40, width: 50 , height: 50))<br><br><br>heart.font = UIFont.systemFont(ofSize: 50)<br>heart02.font = UIFont.systemFont(ofSize: 40)<br>heart.text = &quot;💖&quot;<br>heart02.text = &quot;💞&quot;<br><br><br>bgView.addSubview(heart)<br>bgView.addSubview(heart02)<br><br></pre><h4>Conclusion</h4><p>這次的作業很有趣，不經讓我期待之後的課程，若是有動態甚至是shader的課程，我ㄧ定會學好學滿的！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfb8bf447d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/142-%E8%BF%B7%E5%9B%A0%E8%88%87%E8%B2%BB%E6%B3%A2%E7%B4%8D%E5%85%B6%E6%95%B8%E7%9A%84%E6%87%89%E7%94%A8-abfb8bf447d2">#142 迷因與費波納其數的應用</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>