Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

swift - SwiftUI Simple ForEach multiple errors does not conform to View

I'm trying to wrestle SwiftUI and either something is corrupt with my version of Xcode or I'm doing something wrong. I'm trying to loop through an array of social networks and it's not looping through. The error messages I get are:

Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'SocialNetwork' conform to 'View'

Generic struct 'List' requires that 'SocialNetwork' conform to 'View'

struct SocialNetwork: Identifiable {
let id = UUID()
let type: NetworkType
let url: String
let icon: String

}

struct ChartView: View {
    
var networks = [SocialNetwork(type: .Instagram, url: "", icon: "")]

var body: some View {
    GeometryReader { geometry in
        VStack {
            List {
                ForEach(networks) { net in
                    net
                }
            }
        }
    }
}

}

I'm confused as to why a simple struct would need to conform to View when it's just an array of identifiable?

question from:https://stackoverflow.com/questions/66052730/swiftui-simple-foreach-multiple-errors-does-not-conform-to-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ForEach is a view container, so inside it there should be some view, but your net is a model (instance of SocialNetwork). Put there some list row view presenting one network, like

        List {
            ForEach(networks) { net in
                Label(net.url, image: net.icon)
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...