Article's main picture
  • #ChatGPT
  • #SwiftUI

• 10 min read

Coding With ChatGPT

How good is ChatGPT in coding animations, to-do-lists, and tables in Swift? Is Stack Overflow becoming obsolete?

In this article, I explain how developers can use the AI language model created by OpenAI in their work.

Features & limitations of ChatGPT

Before starting, I want to talk about the limitations of the most popular neural language model. Some are outright stated by OpenAI and others you get with the experience.

Wrong answers. Let's start with limitations that are mentioned in the official documentation first. ChatGPT may give wrong answers. The model was primarily conceived as a chat simulator. Hence its name. The main task is to maintain a conversation, guess the next word, not to know everything.

So beware, the AI can invent false information. Nevertheless, the generated code is often compilable, a huge achievement by itself. Whether the code produces the desired behavior remains an open question we set out to explore.

Heavy demand on a prompt. ChatGPT was designed to communicate about everything, meaning it's trained for all areas of knowledge and doesn’t specialize in coding. To get a more relevant answer in coding, you need to provide more input data.

There are many examples of people forming queries in multiple sentences. If you're interested in mastering queries, google "prompt engineering" or read the article by my colleague on how to write high-quality prompts for generating AI images in DALL·E 2.

Limited data. The next important point is that ChatGPT was trained until 2021. The time limitation makes it unlikely for users to generate code using the API for iOS 16. For example, it didn’t knew about “live activity.” Yet, increased capabilities of CPT-4 may allow you to input new documentation data and generate sufficient answers.

Long response time. Finally, ChatGPT can take a long time to reply or be unavailable due to high demand – something I’ve experienced a lot.

Finally, sometimes ChatGPT doesn’t keep the context of the conversation, but more on that later. Now, let’s move to coding.

By the way, you can find out the results of all the following challenges in a video featuring all the prompts and responses:

Coding challenges for ChatGPT

Network requests

Simple network request. I ask ChatGPT to make a request to the network with the following prompt: “How to make a network request on iOS?”

ChatGPT correctly informs us about various methods to make network requests on iOS, including using URLSession, Alamofire, or other third-party libraries. URLSession is a powerful API provided by Apple, while Alamofire is a popular third-party library offering a more convenient way to make requests. ChatGPT suggests choosing the approach that best fits our needs, ensuring that errors and responses are handled safely and appropriately. Good to know.

Add POST request. Before getting into the task, I want to praise a big advantage of ChatGPT – remembering what was previously said. Instead of making a completely new request, we build on top of the existing context. So when we request “to change it to POST,” the neural network knows what we refer to. As a result, the AI model takes the previous code and sets request.httpMethod to “POST”.

Add authorization token. We submit the next prompt: “add an authorization token”. Our companion creates a new variable for “token” adding “Authorization” to forHTTPHeaderField.

Adjust to async/await. Let’s increase the difficulty with the prompt: “Change the API to using async await.” ChatGPT first tells us these keywords were introduced in Swift 5.5, so thankfully it has learned them.

This time, the language model uses the “fetchData()” method, but for some reason it created “GET”, thereby forgetting about our previous requests for POST and authorization. The result is quite strange because it differs too much from what we've built so far.

However, let’s not lose trust in AI just yet. When we again ask it to “change to POST request”, ChatGPT modifies the previous example with async/await retaining all the parameters and authorization token.

func sendAsyncData() async throws {
    let urlString = "https://example.com/data"
    guard let url = URL(string: urlString) else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let parameters: [String: Any] = [
        "key1": "value1",
        "key2": "value2"
    ]

    request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let authToken = "YOUR_AUTHORIZATION_TOKEN"
    request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")

    let (data, response) = try await URLSession.shared.data(for: request)

    guard let httpResponse = response as? HTTPURLResponse,
          httpResponse.statusCode == 200 else {
        throw NSError(domain: "Invalid response", code: -1, userInfo: nil)
    }
    print("Response: \(data)")
}

I think the tool did a good job in just a few minutes, so let's move on.

Add a Codable entity.

Now, it would be great to add Codable with the prompt: “Make the method to accept a Codable entity”. ChatGPT added the necessary generic functions. It also provided an example of the appropriate use of the Codable type. It remembered the async/await, authorization token, but again missed the previous parameters of “key1” and “key2”.

func sendAsyncData<T: Codable>(entity: T)

Add tests. Let’s see what it can do when asked to “add unit tests”. ChatGPT created a simple request using XCTestExpectation adding the “person” object and waiting for the fulfillment.

Wrap it into a service. Finally, I want to turn this code into something self-sufficient asking to “wrap into a service”. ChatGPT created a “NetworkService” that receives a baseURL. It also remembered our token and Codable. However, our sendData doesn’t return anything.

Return response. We ask it to adjust the method to return the response as Codable. It added two entities, request and response, with decoding.

In my honest opinion, ChatGPT did a fairly good job. It successfully created our network request, changed it, added Codeable, wrapped into a service, and provided explanations along the way. This quick exercise would be beneficial for beginner programmers who are new to writing requests.

Create a table in SwiftUI

Table view. Let’s try something else. First, I ask “how to create a table view in SwiftUI?” ChatGPT answers that we need the “List” and shows a code example.

struct ContentView: View {
    let data = ["Row 1", "Row 2", "Row 3"] // Your data array

    var body: some View {
        List(data, id: \.self) { item in
            Text(item)
        }
    }
}

Clarification. Assume we need a clarification on something, so we ask “what is some View”? It tells us that this is a type erasure in SwiftUI that lets us return different types.

If it’s your first time working in SwiftUI, or if you don’t understand a construct or a keyword, ChatGPT will explain any question you may have. So it’s a great tool to learn with examples.

To-do list

For now, we only have text in our table. Let’s create a to-do list where each row has a checkbox and a header. Another important tip: to increase the chances of success, try to add context describing what you want. Here, we state our purpose, “creating a TODO list app”.

eState var items = [
...

var body: some View {
  List {
forEach(items.indices,\.self) { index in
  HStack {
Toggle(isOn: $items[index].isChecked) {
  Text(items[index].title)
...

ChatGPT added the item variable which represents the data structure of our list. It created a list, with a horizontal stack for each item and added a checkbox. Looks good!

Add details. Our next prompt: “Open a new screen on the row click. The new screen should display item details.” ChatGPT informs us about the “NavigationLink” view and adds it to the existing code. It also created DetailView, which passes the item.

Add preview. Let’s ask it to add a cool SwiftUI feature – Preview. Within seconds, it created a PreviewProvider with ContentView. Naturally, we also received sufficient theoretical explanations. At this point, I also ask it to “add for detail view”. My prompt was simple (i.e., quite uncomplicated), but ChatGPT once again showed how good it is in catching the context. Even though it duplicated DetailView, we still got a preview function, so it’s a pass.

Another huge benefit of ChatCPT is understanding that people make errors, such as spelling mistakes, when writing prompts. The language model handles them just perfectly with no interruptions to the process.

Overall, the language model is helpful for the beginner-level of SwiftUI.

More challenging tasks

For the next task I was thinking about asking ChatGPT to create animation. However, there’s a huge obstacle. ChatGPT doesn’t take video or gif inputs, so describing animated requests with words would be really difficult as there are just too many parameters needed to get the result you want.

Button click animation. For now, let’s settle on something easier. I want to create a SwiftUI animation to imitate clicking the like button, similar to Twitter iOS app.

In a new conversation, I asked ChatGPT to “Create an animation on SwiftUI. The animation should tap on like button”. We also gave it a little tip: “The animation should look line in Twitter app”.

ChatGPT reminded us about its limitations, telling us it couldn’t create animations or graphics directly “as an AI language model”. However, it was still eager to help. So ChatGPT generated a really simple pop animation, but it was incomparable to Twitter’s animations. At least, the model acknowledged its limits.

Theoretical tasks

How to use a framework? Now let's try to ask more theoretical questions. For example, how to use Combine. Fortunately, the chat remembers that I am an iOS developer and provides answers from the relevant sphere.

Again, this ability is often overlooked and now taken for granted. Yet, without remembering the context, ChatGPT could have easily started explaining how to use an agricultural combine when I need information about Apple frameworks.

Compare two frameworks. Suppose we already know about the alternative, RxSwift. Now, we can ask ChatGPT to compare them. The AI language model informs us about their similarities: event-driven programming and declarative style. Later, it outlines six key differences (language support, learning curve, backward compatibility, etc.)

As a starting point, the answer is decent, but an experienced iOS developer may notice some inaccuracies. For example, ChatGPT states that Combine is more integrated with Apple frameworks, which is not actually the case. RXSwift is widely considered to be better integrated with Apple frameworks.

Specific macOS questions. Our next inquiry “How to use Combine with NSButton” is specific to macOS. After giving us the “PassthroughSubject” publisher, ChatGPT indirectly reveals that there is no support for Combine. We would need to create and control our subject, and add click events.

Additional inquiries. Suppose it’s our first time working with Combine, naturally we would want to ask “What’s Passthrough Subject”. Methodically, ChatGPT provides a well-put answer with a succinct description of the publisher, its main functions, and a small code example.

Of course, it’s nothing new. You can probably get the same information for these questions at online forums, including Stack Overflow. Yet, ChatGPT’s main advantage is combining everything into a single tool and being able to explain things you don’t understand. Having more interactions makes it very helpful.

Finally, ChatGPT may be more convenient for short requests, such as a test json file for push notifications, when you don’t feel like using a search engine for it. The only nuance is time limitation, as ChatGPT doesn’t operate on the freshest data.

Conclusions

That's all for today. In my opinion, ChatGPT did a pretty good job with the challenges, and the big plus is the ability to explain any code. It can be valuable for tech interview preparation. For now, it’s not suitable for animations, but for everything else it can help you achieve your tasks. Again, we don’t yet know what the future holds, so I’ll be definitely keeping my pulse on new AI developments.

If you’re interested in the use of AI for programming or look for regular coverage of tech-related topics from real-world engineers, subscribe to MacPaw’s YouTube channel at https://www.youtube.com/@MacPawTech.

More From engineering

Subscribe to our newsletter