TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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

2      

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.

2      

Hi,

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 {
            self.font(.body)
        } else if item.amount < 100 {
            self.foregroundColor(.secondary)
        } else {
            self.background(.red)
        }
    }
}

3      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.