gpt4 book ai didi

swift - 从字典中删除可选字符串

转载 作者:行者123 更新时间:2023-11-30 13:14:59 24 4
gpt4 key购买 nike

我需要将一些参数传递给网络服务,但可选参数也随之而来

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 的对象属性(property)字面上是"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/

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