简体   繁体   English

可选的 <String> 到Int64为零,对其进行硬编码

[英]Optional<String> to Int64 is nil, hardcoded it works

I have a function: 我有一个功能:

func setId(id: Int64?) {
    self._id = id
}

This function is called here: 此功能在这里称为:

let defaults = UserDefaults.standard
let id = defaults.object(forKey: "userId") as? String
if (id != nil) {
    setId(id: Int64(id!))
}

In the function setId() the value of id always seems to be nil. 在函数setId()中, id的值始终似乎为nil。 When debugging and stepping one call up in the stack, to the caller (2nd piece of code) the value of id is 在调试并逐步执行堆栈中的一个调用时,对于调用方(第二段代码), id值为

po id : po id

Optional<String>
  - some : "Optional(350350002)"

When I check it as Int64 : 当我将其检查为Int64

po Int64(id!) : nil po Int64(id!)nil

When I check it with a hardcoded value: 当我用硬编码值检查它时:

po Int64(Optional("350350002")!) : po Int64(Optional("350350002")!)

Optional<Int64>
  - some : 350350002

Also po Int64((id as NSString)) : nil po Int64((id as NSString))nil

What is going on here? 这里发生了什么? How does the hardcoded value differ from the actual variable? 硬编码值与实际变量有何不同?

Thanks. 谢谢。

The problem was that the following was saved to UserDefaults: String(describing: self._userId) , of course saving the actual word 'Optional(...' with it, as String. 问题在于,以下内容已保存到UserDefaults: String(describing: self._userId) ,当然,将实际的单词“ Optional(...)”与它一起另存为String。

I thought the debugger was showing me an Optional with value 350350002 instead of an actual string: "Optional(350350002)" + the saving to UserDefaults code was not written by me, why I didn't notice this. 我以为调试器向我显示了一个值为350350002的Optional而不是一个实际的字符串:“ Optional(350350002)” +我没有编写保存到UserDefaults代码的代码,为什么我没有注意到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM