SKSpriteNode 名称为 int

SKSpriteNode name to int

我正在尝试将 SKSpriteNode 项名称转换为 Int...

这是代码:

let item = SKSpriteNode(imageNamed: "enemy")
item.name = "1"

然后,在touchesEnded中:

guard let touch = touches.first else { return }
let location = touch.location(in: self)
let touchedSKSpriteNode = self.atPoint(location)

processItemTouched(node: touchedSKSpriteNode as! SKSpriteNode)

func processItemTouched 尝试提取触摸元素的名称并将其转换为 Int:

func processItemTouched(node: SKSpriteNode) {
    let num: Int =  Int(node.name)  // Error
}

但是出现错误:"Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?"

点击Fix-it后,变成:

let num: Int =  Int(node.name)!   // Error, again

但出现另一个错误:"Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?"

修复后,它终于可以工作了:

let num: Int =  Int(node.name!)!

它有效,但有一个问题:如果我尝试验证 num != nil,Xcode 说 "Comparing non-optional value of type 'Int' to nil always returns true".

有没有办法避免此警报?

这是一个棘手的情况,因为节点名称和对话结果都可以为 nil。

我建议使用 ?? 为名称提供默认值,用 ! 强行解包可选是非常不优雅和危险的(如果节点没有名称,你尝试与它一起使用此功能,您的应用程序将崩溃)。

您应该:

  • num声明为可选(显式或完全省略类型):

    let num = Int(node.name ?? "") //Int?
    
  • num提供默认值:

    let num = Int(node.name ?? "") ?? 0 //Int
    

Learn more about optionals here.

您正在使用 Int 类型构造函数 Int?(String) 这意味着它需要一个 String 和 returns 一个可选的 Int (Int?) .

node.nameSKNode 的可选 属性,因为节点可以没有名称。所以你被建议强制取消引用(但这非常危险)。您可以提供默认值 node.name ?? <default> 或使用 if-let:

if let name = node.name {
   // do something with name in the case it exists!
}

然后您尝试将生成的 Int? 存储在类型为 Int 的变量中,而 IDE 建议您强制取消引用它(这又是一件坏事)。同样,您可以提供默认值 let i : Int = Int(node.name ?? "0") ?? 0 或使用 if-let 模式:

if let name = node.name, let i = Int(name) {
   // do want you want with i and name...
} else {
   // something bad happened
}