1

Here is my array:

class Storages: ObservableObject {
    let storage = Storage.storage()
    let uid = UserAuth().uid ?? "<uid>"
    
    @Published var photos: [String:String?] = [
        "img1": UserDefaults.standard.string(forKey: "img1"),
        "img2": UserDefaults.standard.string(forKey: "img2"),
        "img3": UserDefaults.standard.string(forKey: "img3"),
    ]

And here is my view:

struct EditProfile: View {
    @ObservedObject var storage = Storages()

    var body: some View {
        VStack {
            Text("Points")
            .font(Font.system(size: 21))
            .fontWeight(.bold)
            HStack {
                ForEach(storage.photos.sorted(by: <), id: \.key){ (key,val) in
                    EditableCircleImage(key: key, imgName: val)
                }
            }

If I change by photos dictionary from [String:String?] to [String:String] (by putting in ?? "" to prevent nil value - then it will work. But I want to keep nil values as I need to know when an array item value is nil.

Here is the struct I pass into my for each:

struct EditableCircleImage: View {
    @ObservedObject var storage = Storages()
    let key: String
    let imgName: String?

Any idea why I can't use a [String:String?]?

3
  • What do you mean by "breaks"? Compiler error? Run-time error? ... Commented Jun 23, 2020 at 12:56
  • There isn't really an informative error. It says: Command CompileSwift failed with a nonzero exit code and error: Segmentation fault: 11 (in target 'App' from project 'App') when I run the app - there is no compile time error, Xcode says an internal error occured. Source editor is limited. Attempting to restore functionality... Commented Jun 23, 2020 at 12:58
  • Xcode 12 gives error for sorted(by: <). Did you overload it? If not, that is the reason. Commented Jun 23, 2020 at 13:06

1 Answer 1

1

Try this variant. Tested with some replicated code on Xcode 12b.

ForEach(storage.photos.sorted(by: { $0.key < $1.key }), id: \.key){ (key,val) in
    EditableCircleImage(key: key, imgName: val)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this fixes the problem - thankyou. PS: What do you mean by "overloading" in this context?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.