我需要将一些参数传递给Web服务,但它们也附带了可选参数

if let birthYear = objPet?.birthYear {
        petDict = ["name": (objPet!.name!),
                   "birth_year": birthYear,
                   "gender": 1,
                   "breed": "test"]
    }


petDict的控制台

{
    "birth_year" = "Optional(\"2000\")";
    breed = test;
    gender = 1;
    name = 2323;
}


我想要“ birth_year” =“ 2000”。我该怎么做。



class Pet: NSObject {
    var name : String?
    var birthYear : String?
    var birthMonth : String?
    var gender : String?
    var breed : String?
}

最佳答案

您的问题不是您如何解包birthYear。您的问题是,存储在String对象中的Pet属性的birthYear实际上是"Optional(2000)"

您在错误的位置寻找问题的根源。您首先需要查看创建Pet对象的代码。

我做了以下操作以在Playground中重新创建您的问题:

class Pet: NSObject {
    var name : String?
    var birthYear : String?
    var birthMonth : String?
    var gender : String?
    var breed : String?
}

let objPet: Pet? = Pet()

objPet?.name = "Fido"

let year: Int? = 2000
objPet?.birthYear = "\(year)"   // you have something like this somewhere

if let birthYear = objPet?.birthYear {
    let petDict = ["name": (objPet!.name!),
               "birth_year": birthYear,
               "gender": 1,
               "breed": "test"]
    print(petDict)
}


输出:


{
    "birth_year" = "Optional(2000)";
    breed = test;
    gender = 1;
    name = Fido;
}



如果将objPet?.birthYear = "\(year)"更改为objPet?.birthYear = "\(year!)",则"Optional"消失。这表明问题出在对象中存储的String,而不是创建String时如何展开petDict

关于swift - 从字典中删除可选字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38325944/

10-09 16:31