Greetings, traveler!
Many developers have encountered this compiler error in Xcode:
No exact matches in call to initializer
What exactly does that mean? Consider this example.
class MyClass {
let id: Int
init(id: Int) {
self.id = id
}
}
let object = MyClass(id: "1") // ❌
The initializer of this class expects an Int value. So we can’t pass a String value there.
Initializers in Swift are essential for setting up class, struct, or enum instances. They ensure that all properties have values and that the instance is ready to be used. Since Swift is a type-safe programming language, you should use concrete types.
Note
However, there is a tool to improve interoperability with inherently dynamic languages like Javascript, Python, Ruby, etc. The @dynamicMemberLookup was designed for this purpose. You can read more about it here.
For this reason, the ‘No exact matches in call to initializer’ error can occur in SwiftUI. For example, the Text view expects a String value to be passed through its initializer. So, if you will pass an Int, the compiler will throw an error.
struct MyView: View {
let id: Int
var body: some View {
Text(id) // ❌ No exact matches in call to initializer
}
}
However, this error will also occur because of Ambiguous Calls. In some cases, when multiple initializers are available, and the caller is ambiguous, the compiler may have difficulty deciding which one to use.
Optionals
Did you know that Optional in Swift is basically an enum?
@frozen
enum Optional<Wrapped> where Wrapped : ~Copyable
Since that is the case, optional String is another type compared with String. This code won’t compile too.
struct MyView: View {
let id: String?
var body: some View {
Text(id) // ❌
}
}
This also applies to the ForEach view.
struct MyView: View {
let array: [String]? = []
var body: some View {
ForEach(array, id: \.self) { item in // ❌
Text(item)
}
}
}
Conclusion
While we didn’t cover all the cases, I hope the primary idea is clear. You will receive an error when the compiler cannot find a proper initializer.