Swift 字典字面量问题

问题描述 投票:0回答:1

XCode 给我这个错误:

Cannot convert value of type 'Match?' to expected element type 'Array<Match>.ArrayLiteralElement' (aka 'Match')

在上线预览中:

Match(dictionary: ["initiator": "a", "performer": "b"]),

当我尝试将这些匹配类类型的家伙插入预览时:

import Foundation

class Match: Identifiable {
    public let id = UUID()
    public var initiator : String?
    public var performer : String?
    
    required public init?(dictionary: NSDictionary) {

        initiator = dictionary["initiator"] as? String
        performer = dictionary["performer"] as? String
    }
}

在我的视图预览中,我有这个:

#Preview {
    LatestMatchesView(matches: [

        Match(dictionary: ["initiator": "a", "performer": "b"]),
        Match(dictionary: ["initiator": "c", "performer": "d"])
    ])
}

这是上述预览的查看代码:

import SwiftUI

struct LatestMatchesView: View {
    @State var matches = [Match]()
    
    var body: some View {
        Text("LATEST MATCHES:")
            
        List(matches) { match in
            
            MatchListingView(match: match)
        }
        .onAppear {
            if ApiUtility.sharedInstance.isConnectedToNetwork() {
                let param : NSDictionary = [:]
                ApiUtility.sharedInstance.httpGet(url: WS_URL(url: LatestMatchesAPI), parameters:param) { (response, error) in
                    //self?.hideLoading()
                    if (error == nil) {
                        
                        self.manageResponse(r: response!)
                        
                    } else {
                        
                    }
                }
            }
        }
             
        Spacer()
            
    } // END var body
}

我在这里错过了什么?我尝试了一些方法,但没有一个起作用......

swift xcode dictionary preview
1个回答
0
投票

问题在于

Match
的初始化器是一个“失败”初始化器,这意味着如果无法使用提供的参数初始化实例,它将返回
nil
。您可以通过
init
后的问号判断初始化程序是否失败。

这意味着您传递给

ListMatchView
的数组文字是
Array<Match?>
而不是
Array<Match>
。您可以通过紧凑映射数组来快速修复它,这会创建一个仅包含非可选值的数组。例如:

LatestMatchesView(matches: [
    Match(dictionary: ["initiator": "a", "performer": "b"]),
    Match(dictionary: ["initiator": "c", "performer": "d"])
].compactMap({ $0 }))
© www.soinside.com 2019 - 2024. All rights reserved.