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

时间:2015-08-19 23:05:59

标签: ios swift dictionary struct

我有这个结构:

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

从此我得到了这个错误

  

无法分配此表达式的结果

但是......为什么!?

1 个答案:

答案 0 :(得分:1)

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
}