我需要将一些参数传递给Web服务,但也可以随附
BindingSource
petDict
的控制台if let birthYear = objPet?.birthYear {
petDict = ["name": (objPet!.name!),
"birth_year": birthYear,
"gender": 1,
"breed": "test"]
}
我想" birth_year" =" 2000" 。我怎么能这样做。
类
{
"birth_year" = "Optional(\"2000\")";
breed = test;
gender = 1;
name = 2323;
}
答案 0 :(得分:0)
将其更改为:
if let pet = objPet {
if let birthYear = pet.birthYear {
petDict = ["name": (pet.name!),
"birth_year": birthYear,
"gender": 1,
"breed": "test"]
}
}
应该帮助
编辑:你应该安全地解开pet.name
答案 1 :(得分:0)
您的问题不在于如何解开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
的方式。