gpt4 book ai didi

ios - 将字符串附加到字典时出错

转载 作者:行者123 更新时间:2023-11-28 07:00:47 26 4
gpt4 key购买 nike

我有这个结构:

public struct GIReservation{
var name: String!
var mobile: String!
var datetime: String!
var people: Int!
var info: String?
var id: String?
}

另一个类实现了:

public class GIReservationCalendarViewModel {

public func newReservation(reservation: GIReservation) {
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue(Authenticator.getAccessToken(), forHTTPHeaderField: API_HEADER_ACCESSTOKEN)
var parameters = ["name": reservation.name, "mobile": reservation.mobile, "datetime" : reservation.datetime, "people" : reservation.people]

if let safeInfo = reservation.info {
parameters["info"] = safeInfo
}
manager.POST(self.reservationsURL, parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
println("saved!")
}) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println("OPS!")
}

}
}

但是在这条线上:

parameters["info"] = safeInfo

然后我得到了这个错误

cannot assign to the result of this expression

但是……为什么!?

最佳答案

parameters 被推断为 NSDictionary,因为您使用的是 String!Int! 等混合类型。

public struct GIReservation{
var name: String!
var mobile: String!
var datetime: String!
var people: Int!
var info: String?
var id: String?
}

// Here an immutable NSDictionary is inferred as type by the compiler
// because you are mixing reservation.people witch is an Int! with
// other String! types
var parameters = ["name": reservation.name, "mobile": reservation.mobile, "datetime" : reservation.datetime, "people" : reservation.people]

if let safeInfo = reservation.info {
parameters["info"] = safeInfo
}

但是您不能向 NSDictionary 添加任何内容,它是不可变的。因此错误“无法分配给该表达式的结果”。您将需要 NSMutableDictionary:

var parameters: NSMutableDictionary = ["name": reservation.name, "mobile": reservation.mobile, "datetime" : reservation.datetime, "people" : reservation.people]

if let safeInfo = reservation.info {
parameters["info"] = safeInfo
}

或者 Swift:[String:AnyObject]

var parameters: [String:AnyObject] = ["name": reservation.name, "mobile": reservation.mobile, "datetime" : reservation.datetime, "people" : reservation.people]

if let safeInfo = reservation.info {
parameters["info"] = safeInfo
}

关于ios - 将字符串附加到字典时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32107044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com