Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

swift - Initializer for conditional binding must have Optional type, not '[String : AnyObject]'

I keep running into this error. I've tried numerous things, could someone tell me where I've gone wrong at? heres my code:

    let receiptFileURL = Bundle.main.appStoreReceiptURL
    let receiptData = try? Data(contentsOf: receiptFileURL!)
    let recieptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    guard let jsonDict: [String: AnyObject] = ["receipt-data" : recieptString! as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject] else {
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "mainVC", sender: nil)
        }
    }
question from:https://stackoverflow.com/questions/65829642/initializer-for-conditional-binding-must-have-optional-type-not-string-anyo

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

1 Answer

0 votes
by (71.8m points)

Since you are initializing the data, the ["receipt-data" : recieptString! as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject] cannot be nil, and thus it makes no sense to wrap it in guard. The only optional you have in this statement is recieptString, which you are force-unwrapping (can be causing crash if recieptString! is nil.

So change your guard statement to

guard let recieptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) else {
    // ...
    return
}

and then initialize the dictionary without guard or force unwrap:

let jsonDict: [String: AnyObject] = ["receipt-data" : recieptString as AnyObject, "password" : IAPProduct.apiID.rawValue as AnyObject]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...