Short answer

A review of three small Swift exercises from 2018 finds the bugs a quick manual test misses: a power function that keeps its last result and crashes on an exponent of 0, a form that crashes on an empty field, and a contact app whose Edit screen reads the ID before it is saved, so it opens the contact from the previous tap. The fixes are small: no shared state, no force unwraps on outside data, IDs passed in through the initializer, and a test for each bug before you ask for the fix.

Open SoalNo3, swipe a contact, tap Edit, and the screen can load somebody else. Change a phone number, save, and the PUT request goes to the contact you opened the time before. The list looks right, nothing crashes, and the whole bug comes down to the order of two lines.

SoalNo3 is one of three small Swift exercises I pushed to GitHub in July 2018. "Soal" is Indonesian for "question", so the names read as Question 1, Question 2 and Question 3. The repos don't say who set the questions, and none of them has a README or a test target. All three are short enough to read over a coffee, which makes them good practice for code review. 100 Days of SwiftUI: A 2026 Roadmap From Intermediate to Expert is a modern counterpart if you are working through exercises today.

This post goes through them the way a reviewer would: what the code does, where it breaks, and how to fix it. The last section turns the findings into searches you can run on your own Swift project, including one an AI tool wrote for you. Force unwraps, shared state and silent failures are as easy to write today as they were in 2018, and only the API names in these repos have aged.

A note on method. Every finding below comes from reading the source. The projects target Swift 4 with 2018 pods, so I did not build them for this post. The fixes are sketches for current Swift. The ones that stand on their own were later compiled and tested on a Mac, as described before the last section; the ones that depend on UIKit screens and Alamofire were not, so run those through Xcode before you paste them anywhere.

SoalNo1: a power function that remembers its last answer

SoalNo1 computes 2 to the power of 20, splits the result into digits and adds the digits up. All of it happens in one view controller, and the answers go to the console. Here is the core:

var total: Int = 1

func kuadrat(nilai: Int, kuadrat: Int) -> Int {
    for k in 1...kuadrat {
        total = total * nilai
    }
    return total
}

The app calls it once, and for that one call the arithmetic is right: 2^20 is 1,048,576 and its digits add up to 31. A reviewer should still stop here, because the function only works for the exact input the screen happens to use.

The first problem is the instance variable. total lives on the view controller and is never reset, so the function carries its old result into the next call. Call kuadrat(nilai: 2, kuadrat: 3) after the first call and you get 8,388,608, which is 2^23. A function that returns a different answer for the same arguments is hard to trust and harder to test.

The second problem is the range. A ClosedRange can't be empty, as Apple's documentation says, and building 1...0 stops the app at runtime. Any number to the power of 0 should be 1, yet here an exponent of 0 crashes. A negative exponent crashes the same way.

The third is overflow. Int on a 64-bit device tops out at 9,223,372,036,854,775,807, so 2^63 doesn't fit, and Swift stops the program on integer overflow instead of wrapping around. With a fixed input of 20 this never fires. Connect the function to a text field and it will.

The rest is smaller but worth a comment in review. multiple and sum are declared and never used, and the loop variable k should be _. "Kuadrat" means "squared", while this function raises to any power, and the same word names both the function and its parameter. The digit helper uses String(self).characters.flatMap, which is Swift 3 style. SE-0163 made String a collection in Swift 4, and SE-0187 gave this use of flatMap the name compactMap in Swift 4.1.

The fix is two free functions with no state and no UIKit:

enum PowerError: Error {
    case negativeExponent
    case overflow
}

func power(_ base: Int, _ exponent: Int) throws -> Int {
    guard exponent >= 0 else { throw PowerError.negativeExponent }

    var result = 1
    for _ in 0..<exponent {
        let (next, didOverflow) = result.multipliedReportingOverflow(by: base)
        if didOverflow { throw PowerError.overflow }
        result = next
    }
    return result
}

func digitSum(_ value: Int) -> Int {
    String(value).compactMap(\.wholeNumberValue).reduce(0, +)
}

Because 0..<0 is a valid empty range, the zero case now returns 1 with no special handling. Moving the math out of the view controller also means it can be tested without launching a screen:

import Testing

@Test func powerHandlesEdges() throws {
    #expect(try power(2, 20) == 1_048_576)
    #expect(try power(2, 0) == 1)
    #expect(throws: PowerError.overflow) { try power(2, 63) }
}

@Test func digitSumMatchesTheExercise() {
    #expect(digitSum(1_048_576) == 31)
}

SoalNo2: two text fields and three ways to crash

SoalNo2 takes two numbers and fills a table. Multiples of both 3 and 4 show "Yeay!", multiples of 3 or 4 show the number, and everything else is skipped. For the range 1 to 12 the output is 3, 4, 6, 8, 9, Yeay!. The button handler is one busy line:

items = []
itemss.append((test(first: Int(input1.text!)!, second: Int(input2.text!)!)))
self.listView.reloadData()

Leave a field empty and Int("") returns nil, and the second ! crashes the app. Type "12a" and the same thing happens. Type 10 in the first field and 1 in the second and first...second crashes inside the loop, for the same reason as SoalNo1. A reviewer can find all of this in the time it takes to read the line, and a tester can find it by tapping the button with the fields blank. Guideline 2.1 Rejection: Why Your AI-Built App Crashed in App Review shows how often a crash like this ends a review.

There is a quieter design problem as well. The method named test writes to the items property and also returns it. The table reads the property, while the returned array goes into itemss, a second property with one extra letter. That second array gains one nested array per tap and is only ever printed. Both are typed [Any] because a row can be a number or a string, and that type means the compiler can't help with anything that reads them.

Last, nobody can tell from the repo whether skipping the other numbers is correct. The original question isn't in the repo, and neither is a test that states the expected output. Reviewers ask for that because without it they can only compare the code with itself.

A small enum removes the Any, and i % 3 == 0 && i % 4 == 0 turns into a pattern match that can't fall through:

enum Row: Equatable {
    case number(Int)
    case yeay

    var text: String {
        switch self {
        case .number(let value): return String(value)
        case .yeay: return "Yeay!"
        }
    }
}

func rows(in range: ClosedRange<Int>) -> [Row] {
    range.compactMap { value -> Row? in
        switch (value % 3 == 0, value % 4 == 0) {
        case (true, true): return .yeay
        case (true, false), (false, true): return .number(value)
        case (false, false): return nil
        }
    }
}

Input parsing gets its own function, so bad text becomes a message on screen and never reaches a force unwrap:

import Foundation

func parseRange(_ low: String?, _ high: String?) -> ClosedRange<Int>? {
    let allowed = 0...1_000_000

    func number(_ text: String?) -> Int? {
        guard let text else { return nil }
        return Int(text.trimmingCharacters(in: .whitespaces))
    }

    guard let first = number(low), let second = number(high),
          allowed.contains(first), allowed.contains(second),
          first <= second else {
        return nil
    }
    return first...second
}

The allowed limit is a choice you should make for your own app. Without a limit, someone can type a two-billion-wide range and rows(in:) will build that array on the main thread, freezing the screen. The button handler then shrinks to a guard, an assignment to a [Row] property and one reloadData().

SoalNo3: the contact app where Edit opens the wrong person

SoalNo3 is the largest of the three: a contact list with add, edit and delete against a REST API on a plain HTTP development server, using Alamofire, SwiftyJSON and Kingfisher. Most of what's worth reviewing is here.

The two lines in the wrong order

The swipe action in the list does this:

self.navigationController?.pushViewController(EditListViewController(), animated: true)
UserDefaults.standard.set(self.id[indexPath.row], forKey: "dataId")

And the edit screen builds its URL in a property:

let url = "http://.../api/v1/person/\(UserDefaults.standard.string(forKey: "dataId") ?? "")"

A stored property's initial value is computed when the object is created. EditListViewController() runs on the first line, so the URL reads dataId before the second line writes it. On a fresh install the first Edit tap reads an empty ID and calls the collection path /person/. The tap on contact B then stores B. Tap Edit on contact C and the screen opens with B's URL, loads B's details and sends the PUT to B when you press the button.

UserDefaults survives a relaunch, so the stale ID does too. Swapping the two lines would fix the symptom. The better fix removes the shared global, because a screen that needs an ID should receive one:

final class EditListViewController: UIViewController {
    private let contactID: String

    init(contactID: String) {
        self.contactID = contactID
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) is not supported")
    }
}

// In the list:
let screen = EditListViewController(contactID: contact.id)
navigationController?.pushViewController(screen, animated: true)

Now the compiler refuses to create the screen without an ID, and the wrong order can't be written.

Six parallel arrays and one crash for every null

The list keeps id, imagePicture, users, alamat, phone and email as six separate string arrays, filled inside a loop with a force unwrap on every field. One contact with a null value stops the whole app, so a single bad row in the database takes down the screen for every user.

That risk is close to home here, because the add screen sends name, address, phone and email and never sends a picture, and imageProfile is an outlet nothing writes to. If the server stores a null for a contact added this way, the next list load hits imageI! and crashes. I can't confirm what the server returns, and the client shouldn't depend on it either way.

Before each load the code empties five of the arrays. imagePicture isn't one of them. This does no harm yet because the fetch only runs in viewDidLoad, once. Move it into a pull-to-refresh and the pictures keep their old entries while the names start over, so every row shows the wrong photo. Parallel arrays allow this kind of drift, and one array of structs doesn't. Assuming result is an array, which is how the list code reads it:

struct Contact: Decodable {
    let id: String
    let name: String
    let address: String?
    let phone: String?
    let email: String?
    let picture: String?
}

struct ContactListResponse: Decodable {
    let result: [Contact]
}

Optionals on the fields that can be missing move the decision into the cell, where a placeholder image is an easy answer. If you'd rather drop a broken row than crash, decode each element on its own and log the failures.

Delete that doesn't say what happened

Alamofire.request(urlDelete, method: .delete)
print("Delete tapped")

No response handler, no array update, no reload. If the delete succeeds, the row stays on screen until the list is created again. If it fails, the person never finds out. The add and edit screens have a softer version of the same problem: they print the response and stay where they are, and the list doesn't refresh when you come back, since it only fetches in viewDidLoad.

The swipe API has also moved. UITableViewRowAction is listed as available through iOS 13. The replacement carries a completion handler that fits this job, because the row can stay until the server answers:

func tableView(_ tableView: UITableView,
               trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath)
    -> UISwipeActionsConfiguration? {
    let contact = contacts[indexPath.row]
    let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in
        Task { @MainActor in
            guard let self else { return done(false) }
            do {
                try await self.api.delete(contact.id)
                self.contacts.removeAll { $0.id == contact.id }
                self.tableViewList.reloadData()
                done(true)
            } catch {
                self.showError(error)
                done(false)
            }
        }
    }
    return UISwipeActionsConfiguration(actions: [delete])
}

The closure removes by ID and not by the old indexPath, since the rows may have changed while the request was running. api and showError are yours to write.

The Info.plist line App Review will ask about

The server is plain HTTP, so Info.plist sets NSAllowsArbitraryLoads to true. That turns off App Transport Security for every domain. Apple's documentation says you must supply a justification during App Store review if you set this key, and it recommends upgrading the server or at least using a narrower exception.

This is fine for a local exercise and a real problem in a shipped app, since names, addresses, phone numbers and emails would travel unencrypted. The same data also goes to the console: print("dataList\(data)") logs the full response. If you start from a template or generated project, look for this key before you submit. A tool may have added it to get a demo working.

Dependencies that are one update away from breaking

The Podfile lists its pods with no version constraints, and Podfile.lock holds Alamofire at 4.7.2. Pods aren't committed, so everything rests on that lock file. Run pod update and CocoaPods is free to move to Alamofire 5, where the migration guide replaces the global Alamofire namespace with AF, so every Alamofire.request here stops compiling. responseJSON was deprecated in Alamofire 5.5 in favor of responseDecodable, which pairs well with the Contact struct above.

IQKeyboardManagerSwift is in the Podfile, and no Swift file in the repo mentions it. Unused pods cost build time and add one more thing to update. LsitContactViewController has a typo in its class name, the kind of thing a reviewer should mention once, politely, and then let go.

The fixes, compiled and run

The parts of this review that do not depend on the apps' screens were checked with Xcode 26.2 on a Mac. First the original kuadrat function, copied as it is, built as a small command-line tool:

  • kuadrat(nilai: 2, kuadrat: 20) printed 1048576, and a second call, kuadrat(nilai: 2, kuadrat: 3), printed 8388608. That is 2 to the power of 23, because total carried the first result into the second call.
  • kuadrat(nilai: 5, kuadrat: 0) stopped with "Fatal error: Range requires lowerBound <= upperBound".
  • kuadrat(nilai: 2, kuadrat: 63) stopped with exit code 133, a trap, and printed no message at all, in both a debug build and an optimized one. A crash report would be the only clue.

Then the fixes. power, digitSum, the Row enum with rows(in:), parseRange and the Contact types went into a Swift package in the Swift 6 language mode, with the post's two Swift Testing tests and four more written for this check. All six passed with no warnings:

  • The post's tests: 2 to the 20th is 1,048,576, any number to the 0th is 1, 2 to the 63rd throws .overflow, and the digits of 1,048,576 add up to 31.
  • rows(in: 1...12) produced "3", "4", "6", "8", "9", "Yeay!", the output the exercise describes.
  • parseRange returned nil for an empty field, for "12a", for 10 then 1, for a missing value, for 2,000,000 and for -1, and returned 3...12 for " 3 " and "12", so surrounding spaces are trimmed as intended.
  • A contact list with a null address, a null picture and a contact with only an id and a name decoded fine. A list where one contact had a null name failed to decode as a whole, with a DecodingError. That is the case the note after the Contact type warns about: one bad row costs you the whole list unless you decode each element on its own.

The edit screen with its new initializer and the swipe action were not compiled, because they need the app's own types and Alamofire. Treat those as the shape of the fix rather than code to paste.

Six searches to run on your own Swift project

Most of the findings above can be located with grep. I ran these from a folder holding the three repos, and the counts in the notes are what came back. They find candidates and each hit still needs a human look.

# 1. Force unwraps in logic, skipping outlets
grep -rnE '\.text!|[a-zA-Z_]!\)|[a-zA-Z_]!$|Int\(.*\)!' --include='*.swift' . | grep -v IBOutlet

# 2. Ranges built from variables
grep -rnE '[0-9a-z]+\.\.\.[a-zA-Z]' --include='*.swift' .

# 3. UserDefaults used to pass data between screens
grep -rn 'UserDefaults' --include='*.swift' .

# 4. Blanket App Transport Security exceptions
grep -rn 'NSAllowsArbitraryLoads' --include='*.plist' .

# 5. Failures and data that only reach the console
grep -rn 'print(' --include='*.swift' .

# 6. Handlers that throw the response away
grep -rnE 'request\(.*\)$' --include='*.swift' .
  1. Search 1 returns 7 lines: the SoalNo2 button line and the six force unwraps in the contact list. Search 2 returns 2 lines, and both are the crashes described above, in SoalNo1 and SoalNo2.
  2. Search 3 returns exactly the 2 lines of the Edit bug. When a key is written in one file and read in another, check which runs first.
  3. Search 4 should come back empty in most production apps. If it doesn't, have a justification ready or replace it with an entry under NSExceptionDomains for the one host you need.
  4. Search 5 returns 10 lines in SoalNo3 alone. Read each one and ask whether the person using the app would learn about that failure, and whether the line logs personal data.
  5. Search 6 is rough, and it's the one that finds the silent delete. Any request with no completion, no await and no handler on the following line deserves a look.

How to use this on code an AI tool wrote

An AI coding tool will gladly produce a screen that runs on the happy path, and a quick manual test will pass, since these bugs need a blank field, a zero, a null or a second tap. So test those on purpose. For each form, submit it empty and with text in a number field. For each list, ask what happens when one record has a missing field. For each screen that receives an ID, open two different items in a row and check that the second one really is the second one.

Then give each bug a test before you ask for the fix. A failing test is a clearer instruction than a paragraph of description, and it stays in the repo afterwards. For the Edit bug it might look like this, once the URL is exposed as a property:

@MainActor @Test func editScreenUsesTheTappedContact() {
    let screen = EditListViewController(contactID: "B")
    #expect(screen.requestURL.lastPathComponent == "B")
}

Ask the tool to make that test pass and to leave the other tests alone. Review the diff the same way you read these three repos: state that outlives a call, force unwraps on outside data, the order of side effects, and what the user sees when the network says no.

If you want a checklist like this applied to every pull request, The Coding Agent Lab is a pack of agent briefs from my Gumroad store. The free edition has 25 agents for Claude Code, Cursor, ChatGPT or your own agent files, and the product page lists iOS, UIKit, SwiftUI, security and testing among them, with a PDF guide and a TXT file of copyable briefs. Larger Max and Ultra editions are sold on the same page.

Sources