What is “No exact matches in call to initializer” error Swift/Swiftui

The ‘No exact matches in call to initializer’ error in Xcode can be confusing for many Swift developers. This common issue happens when the Xcode compiler doesn’t find a perfect match for the initializers in your code. In this blog post, we walk through some of the most typical examples of this error and show you how to fix them. Along the way, you’ll learn more about how the Xcode compiler works and gain a better understanding of initializers in Swift. Whether you’re new to programming or an experienced coder, this guide will help you tackle this error with confidence.

Understanding the “No Exact Matches in Call to Initializer” Error

When you’re coding in Swift and working with Xcode, encountering error messages is a common part of the development process. One such error is the “No exact matches in call to initializer.” This error message is the Swift compiler’s way of telling you that it can’t find an initializer that exactly matches the arguments you’ve provided in your code.

What is an Initializer?

  • Initializers in Swift are crucial for setting up new instances of a class, struct, or enum.
  • They ensure that all properties have values and that the instance is ready for use.

How the Swift Compiler Works in This Context

  • The Swift compiler is designed to enforce type safety and ensure that objects are created and used correctly.
  • When you call an initializer, the compiler checks all the available initializers of that type.
  • It then attempts to match your arguments with the parameters of these initializers.
  • If it finds an exact match, the compiler proceeds; if not, it throws the “No exact matches in call to initializer” error.

Why Does This Error Occur?

  • Mismatched Arguments: The most common reason. You’re trying to create an object but not providing the correct type or number of arguments that the initializer expects.
  • Ambiguous Calls: Sometimes, if there are multiple initializers available and your call is vague, the compiler can’t decide which one to use.

How to Identify the Correct Initializer:

  • Read the Documentation: Always a good start. Swift’s documentation will list all available initializers for a class or struct.
  • Auto-Complete Feature in Xcode: As you type the initializer, Xcode’s auto-complete can suggest the correct form.
  • Error Messages: Pay close attention to Xcode’s error messages. They often give clues about what’s missing or incorrect.

Error Example Scenarios

In this section, I’ll walk you through common scenarios where the “No exact matches in call to initializer” error occurs, along with code snippets to illustrate and solve the problem.

SwiftUI Example: Type Mismatches

The following code will give “No exact matches in call to initializer” error in line 6:

import SwiftUI

struct ContentView: View {
    var body: some View {
        // This might cause an error because Text does not have an initializer that takes an Int
        Text(123)
    }
}

In this SwiftUI example, Text expects a String to initialize, not an Int. To fix the error, you need to convert the Int to a String:

Text("\(123)")

or

Text(String(123))

Remember that the error message “no exact matches in call to initializer” is the compiler’s way of telling you that it can’t find a constructor that matches the arguments you’re providing. 

Non-Optional in Initialisers

Consider the following code snippet where we are trying to convert the text from a UITextField into a Double:

import UIKit

let textField = UITextField()
...
let bill = textField.text
let billTotal = Double(bill) // error

This code results in the “No exact matches in call to initializer” error. The reason is that textField.text returns an optional String?, and the Double initializer expects a non-optional String.

Now, look at the modified code snippet where the text is force-unwrapped:

let bill = textField.text!
let billTotal = Double(bill)

By force unwrapping textField.text using !, we are telling the compiler that we are sure the value is not nil. This resolves the error because the Double initializer can now find a match for a non-optional String.

However, force unwrapping is generally discouraged because if textField.text is nil, the app will crash. A safer approach is to use optional binding or provide a default value.

Solutions Using Optional Binding:

Optional binding is a safer way to unwrap optionals. Here’s how you can use it to safely handle the conversion:

if let bill = textField.text, let billTotal = Double(bill) {
    // Use billTotal safely here
} else {
    // Handle the case where the text is not convertible to Double
}

Providing a Default Value:

Another approach is to provide a default value using the nil-coalescing operator ??:

let bill = textField.text ?? ""
let billTotal = Double(bill) ?? 0.0

In this case, if textField.text is nil, it defaults to an empty string “”, which the Double initializer can handle by returning nil. We then provide a default value of 0.0 for billTotal.

SwiftUI ForEach with Optionals

Let’s take a look at an example where this error might arise. The following code is intended to fetch and display RSS feed items using SwiftUI and the FeedKit library:

import SwiftUI
import FeedKit

let feedURL = URL(string: "http://images.apple.com/main/rss/hotnews/hotnews.rss")!

struct RSSList: View {
    let parser = FeedParser(URL: feedURL) 
    var rssFeed: RSSFeed?

    @State private var items: [RSSFeedItem]? = [RSSFeedItem]() 

    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in // error
                    RSSItem(feed: item)
                }
            }
            .navigationTitle("Feed")
            .onAppear {
                Task {
                    await getRSS()
                }
            }
        }
    }
}

In this snippet, the ForEach view is used to iterate over an optional array, which is not directly supported by SwiftUI’s ForEach.

To resolve these issues, we need to adjust the code to match the expected initializers and correct usage patterns. SwiftUI’s ForEach requires a non-optional collection. You need to safely unwrap the optional array or provide a default value.

List {
    ForEach(items ?? []) { item in
        RSSItem(feed: item)
    }
}

Conclusion

Understanding and resolving the “No exact matches in call to initializer” error is crucial for smooth Swift development. By paying close attention to the initializers and their requirements, you can avoid this common pitfall.

3 thoughts on “What is “No exact matches in call to initializer” error Swift/Swiftui”

  1. Thanks for explaining the ‘No exact matches in call to initializer’ error in Swift/SwiftUI. I’ve been struggling with this issue for a while now, and your post helped me identify the problem and fix it. Great job!

    Reply
  2. Great post! I’m experiencing the same issue and your explanation helped me understand what’s happening. I’m still trying to figure out why this error is happening in my specific use case, but your post gave me a good starting point to investigate further. Thanks for sharing your knowledge!

    Reply
  3. Thank you for sharing this helpful article! I’ve been struggling with this exact error message in my SwiftUI project and couldn’t figure out what was causing it. Your explanation of the issue and the fix was spot on. I’ll make sure to keep this in mind moving forward and avoid this error in the future. Great Job!

    Reply

Leave a Comment

Subscribe to My Newsletter

Want the latest iOS development trends and insights delivered to your inbox? Subscribe to our newsletter now!

Newsletter Form