NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Error in extension, yet code still functions

Forums > 100 Days of SwiftUI

I am working on Project 7, the iExpense app, and playing around with making the ExpenseStyling extension do different things. I altered the code to style the expenses with either a foreground color or a background color. I get an error, yet the preview still functions - it works and I can see the styling on the expenses. The app will not build and run in the simulator though.

What am I missing?

extension View {
    func style(for item: ExpenseItem) -> some View {
        if item.amount < 15 {
            return self.font(.body)
        } else if item.amount < 100 {
            return self.foregroundColor(.secondary)
        } else {
            return self.background(.red)

Errror: Function declares an opaque return type 'some View', but the return statements in its body do not have matching underlying types


The problem is that you are returning different types depending on what item.amount is. But some View requires that the type always be the same, even if, as an opaque type, you don't necessarily know what that type is.

For instance, these TextField elements with the modifiers you are using return different types:

TextField("", text: $txt).font(.body)
//ModifiedContent<TextField<Text>, _EnvironmentKeyWritingModifier<Optional<Font>>>

TextField("", text: $txt).foregroundColor(.secondary)
//ModifiedContent<TextField<Text>, _EnvironmentKeyWritingModifier<Optional<Color>>>

TextField("", text: $txt).background(.red)
//ModifiedContent<TextField<Text>, _BackgroundStyleModifier<Color>>

So whatever type self happens to be in your View extension will similarly have different types depending on the value of item.amount.



If you add @ViewBuilder and remove the return key words it'll work,

extension View {
    @ViewBuilder func style(for item: ExpenseItem) -> some View {
        if item.amount < 15 {
        } else if item.amount < 100 {
        } else {


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.