UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.