Give your simulator superpowers

RocketSim: An Essential Developer Tool
as recommended by Apple

ChatGPT for Swift: Top 5 code generation prompts

Using ChatGPT for Swift code generation can drastically increase your productivity. While I’m uncertain whether AI will take over our jobs as developers, I’m certain developers without knowledge of using AI to their advantage will become much slower in writing code.

Today, we will look at a few of my favorite ways of using ChatGPT to speed up my development process. By asking the right questions, you’ll be able to get code output close to what you’re likely looking for. Even though the output isn’t always perfect, it’s certainly a step in the right direction. Let’s dive in!

General tips for using ChatGPT with Swift

Before we dive into my top 5 favorite prompts for ChatGPT, it’s important to go over the basics. ChatGPT is an AI chatbot that will try to answer questions that you have. A question is called a prompt and can be anything. I’m often surprised to see a qualitative answer while I thought beforehand, “There’s no way it can answer this.”

You can start by going to chatgpt.com and creating an account. Once logged in, you can start asking questions by typing your prompt. For example, we can ask, “When did Apple announce Swift?”.

You can use ChatGPT for code generation questions to increase productivity.
You can use ChatGPT for code generation questions to increase productivity.

You can see it did a great job answering the question!

For code-related questions, I have a few rules to follow that will help you get useful answers:

  • Mention you’re writing code in Swift
  • Provide any context you have (e.g., background story, related code, protocol or enum definitions, etc.)
  • Don’t doubt, and always ask. It’s better to try and get a wrong answer than predict beforehand whether it will be able to answer your prompt. You’ll often be surprised.
  • Always check the output code for mistakes. AI does a great job, but it often comes with either mistakes or outdated code.

With those in mind, let’s dive into my top 5 favorite prompts when developing Swift applications.

1. Creating structs for a given JSON

The first prompt helps you generate code for a given JSON. The prompt looks as follows:

Can you write a Swift struct called Person for the following JSON [JSON]

The output will be a useful struct that conforms to the Codable protocol. If you’re new to JSON decoding in Swift, read JSON Parsing in Swift explained with code examples. The answer will even include sample code to try the code generation using a JSON decoder. It’s a great example of using ChatGPT for Swift code generation to speed up your development process.

How do you stay current as a Swift developer?

Let me do the hard work and join 19,136 developers that stay up to date using my weekly newsletter:

2. Writing unit tests for a given piece of code

This one often generates the most code from all the prompts. It’s also likely to be output that does not follow your coding style for tests, but it is a way to get started with tests quickly. The idea is to let ChatGPT generate unit tests for a given piece of code.

The prompt looks as follows:

Can you write unit tests in Swift for the following piece of code: [CODE]

For example, we could ask it to write tests for the following piece of code:

extension StringProtocol {
    func uppercasedFirst() -> String {
        prefix(1).uppercased() + dropFirst()
    }
}

The output is pretty detailed, with a total of five different unit tests:

class StringProtocolExtensionsTests: XCTestCase {

    func testUppercasedFirst_withEmptyString() {
        let emptyString = ""
        XCTAssertEqual(emptyString.uppercasedFirst(), "")
    }

    func testUppercasedFirst_withSingleCharacter() {
        let singleCharacter = "a"
        XCTAssertEqual(singleCharacter.uppercasedFirst(), "A")
        
        let singleCharacterUpper = "A"
        XCTAssertEqual(singleCharacterUpper.uppercasedFirst(), "A")
    }

    func testUppercasedFirst_withMultipleCharacters() {
        let multipleCharacters = "hello"
        XCTAssertEqual(multipleCharacters.uppercasedFirst(), "Hello")
        
        let multipleCharactersMixed = "hELLO"
        XCTAssertEqual(multipleCharactersMixed.uppercasedFirst(), "HELLO")
        
        let multipleCharactersUpper = "HELLO"
        XCTAssertEqual(multipleCharactersUpper.uppercasedFirst(), "HELLO")
    }

    func testUppercasedFirst_withWhitespaceAndSpecialCharacters() {
        let stringWithWhitespace = " hello"
        XCTAssertEqual(stringWithWhitespace.uppercasedFirst(), " hello")
        
        let stringWithSpecialCharacter = "$hello"
        XCTAssertEqual(stringWithSpecialCharacter.uppercasedFirst(), "$hello")
        
        let stringWithNumber = "1hello"
        XCTAssertEqual(stringWithNumber.uppercasedFirst(), "1hello")
    }

    func testUppercasedFirst_withUnicodeCharacters() {
        let unicodeString = "éclair"
        XCTAssertEqual(unicodeString.uppercasedFirst(), "Éclair")
        
        let unicodeStringUpper = "Éclair"
        XCTAssertEqual(unicodeStringUpper.uppercasedFirst(), "Éclair")
    }
}

As you can see, you can perfectly use ChatGPT for Swift unit test generation.

2b. Bonus: generating mocks

This little bonus tip also relates to tests and asks ChatGPT for Swift code generation for a given protocol. The prompt looks as follows:

Generate a Swift mock for the following protocol: [CODE]

For example, generating a mock for the following protocol:

protocol AppVersionProviding {
    var currentVersion: String { get }
}

Results in the following mock:

class MockAppVersionProvider: AppVersionProviding {
    var currentVersion: String

    init(currentVersion: String) {
        self.currentVersion = currentVersion
    }
}

Pretty basic, but often useable and good enough for unit tests.

3. Ask for specific code questions

Using ChatGPT for Swift code generation is useful for many different cases. The third prompt isn’t a specific prompt but rather a general tip to ask ChatGPT any programming questions you might have.

For example, I’ve recently asked ChatGPT how to generate a 95th percentile for a given array of time intervals to use in RocketSim’s Xcode Build Insights:

I have an array of timeintervals in Swift. How can I generate the 95th percentile?

The generated code looks as follows:

import Foundation

extension Array where Element == TimeInterval {
    func percentile95() -> TimeInterval? {
        guard !self.isEmpty else { return nil }
        
        let sortedArray = self.sorted()
        let index = Int(Double(sortedArray.count) * 0.95)
        
        // Ensure the index is within bounds
        let percentileIndex = min(index, sortedArray.count - 1)
        
        return sortedArray[percentileIndex]
    }
}

// Usage example
let timeIntervals: [TimeInterval] = [1.0, 2.0, 0.5, 1.5, 2.5, 3.0, 0.25]
if let percentile95 = timeIntervals.percentile95() {
    print("95th percentile is \(percentile95)")
} else {
    print("Array is empty")
}

And it’s joined by a detailed description of the code:

Explanation:

- The percentile95 method is an extension on Array where the element type is TimeInterval.
- It first checks if the array is empty and returns nil if so.
- The array is sorted in ascending order.
- The index for the 95th percentile is calculated as 95% of the total count.
- We use min(index, sortedArray.count - 1) to ensure the index is within the bounds of the array.
- Finally, the value at the calculated index is returned.

This function correctly handles arrays of TimeInterval values and calculates the 95th percentile. Note that if the array length is small, the 95th percentile may be the highest value due to rounding.

In other words, ChatGPT can be your knowledgeable colleague who’s always available for questions. The output code might not always satisfy your standards, but it’s a great starting point to continue. First, make it work, then make it shine!

4. Add documentation

We developers love writing code, but we often dislike writing detailed documentation. This is a pity since it’s a great way to level up your codebase and make it accessible to colleagues who will visit your code.

While we’ve used ChatGPT for Swift code generation in other prompts, we will now use it to generate documentation instead:

The following code does [EXPLANATION]. Can you write documentation for the following piece of Swift code: [CODE]

Providing some explanation is recommended so ChatGPT knows what your code is doing. However, I hear you thinking: “In that case, It will probably be faster just to write the documentation myself.”

You’re right, so you might want to try the following prompt and see if the result is satisfying enough:

Can you write documentation for the following piece of Swift code: [CODE]

As an example, I’ve asked it to generate documentation for the fairly simple uppercase first method we used earlier. The output looks as follows:

extension StringProtocol {
    /// Returns a new string with the first character uppercased and the remaining characters unchanged.
    ///
    /// This method uppercases only the first character of the string and leaves the rest of the characters unchanged.
    /// If the string is empty, it returns an empty string.
    ///
    /// - Returns: A string with the first character uppercased, or an empty string if the original string is empty.
    ///
    /// # Examples:
    /// ```
    /// print("hello".uppercasedFirst()) // "Hello"
    /// print("Hello".uppercasedFirst()) // "Hello"
    /// print("".uppercasedFirst())      // ""
    /// print("a".uppercasedFirst())     // "A"
    /// print("1hello".uppercasedFirst()) // "1hello"
    /// print(" élève".uppercasedFirst()) // " Élève"
    /// ```
    func uppercasedFirst() -> String {
        // Check if the string is empty
        guard let firstCharacter = first else {
            return ""
        }
        
        // Uppercase the first character and concatenate with the rest of the string
        return String(firstCharacter).uppercased() + dropFirst()
    }
}

The output documentation is very detailed and likely much more than you would’ve written. Whether this documentation is too much depends on your preference, but you can always keep the piece you need.

5. Suggest code improvements

The final prompt uses ChatGPT for Swift code improvements. You might have written code that works, but it feels like it could be optimized.

For example, I’ve written the following piece of code to get the first contact in an array for a given query:

extension [Contact] {
    func findFirstContact(for query: String) -> Contact? {
        filter { contact in
            contact.name.contains(query)
        }
        .first
    }
}

The code works and might look good, but I still decided to ask ChatGPT for improvements. The output looks as follows:

extension Array where Element == Contact {
    /// Finds the first contact whose name contains the query string.
    /// The search is case insensitive and ignores leading/trailing whitespace in the query.
    ///
    /// - Parameter query: The query string to search for.
    /// - Returns: The first contact whose name contains the query string, or `nil` if no contact is found.
    func findFirstContact(for query: String) -> Contact? {
        // Trim whitespace from the query and check if it's empty
        let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedQuery.isEmpty else {
            return nil
        }
        
        // Perform a case-insensitive search
        return first { contact in
            contact.name.range(of: trimmedQuery, options: .caseInsensitive) != nil
        }
    }
}

// Assuming Contact is defined like this:
struct Contact {
    let name: String
}

// Usage example
let contacts = [Contact(name: "Alice Johnson"), Contact(name: "Bob Smith"), Contact(name: "Charlie Brown")]
if let contact = contacts.findFirstContact(for: "bob") {
    print("Found contact: \(contact.name)") // Output: Found contact: Bob Smith
}

It improved the code and added documentation and sample code to try out the optimized method. ChatGPT also shared the key improvements it made:

  1. Performance: Using first(where:) stops at the first match.
  2. Case Insensitivity: The search is now case-insensitive.
  3. Whitespace Handling: Trimming the query to prevent issues with accidental spaces.
  4. Documentation: Added comments for clarity.

These changes make the function more robust and efficient and show how to use AI to optimize existing code.

Conclusion

ChatGPT for Swift code generation is a great way to increase productivity. It’s important to provide enough context for the chatbot to provide valuable answers, but if you do, you’ll likely write code much faster.

If you like to improve your Swift knowledge, even more, check out the Swift category page. Feel free to contact me or tweet to me on Twitter if you have any additional tips or feedback.

Thanks!

 
Antoine van der Lee

Written by

Antoine van der Lee

iOS Developer since 2010, former Staff iOS Engineer at WeTransfer and currently full-time Indie Developer & Founder at SwiftLee. Writing a new blog post every week related to Swift, iOS and Xcode. Regular speaker and workshop host.

Are you ready to

Turn your side projects into independence?

Learn my proven steps to transform your passion into profit.