【问题标题】:Cannot call value of non function type SKShapeNode无法调用非函数类型 SKShapeNode 的值
【发布时间】:2017-08-16 12:25:42
【问题描述】:

我一直在尝试修复此错误并尝试使字符包含在将是 int 的行中。

 func isRightTileAt(location:CGPoint) ->Bool {
    //as shape node so we can get fill
    var currentRect = self.atPoint(location) as! SKShapeNode
    //get the 10th character which will contain the row and make it an int
   // let rowOfNode = Int(currentRect.name![10]) //error(tried both of these)
    var rowOfNode = Int(currentRect(name[10])) //error 
    //flip position is used for the row index below the screen to flip it to the top.
    var currentRow = self.flipPosition + 1
    var currentRowOfClick = self.flipPosition

    //we reuse the flip position because it hasn't flipped yet but it normally contains the right row.
    //because flip position happens after this check so it won't be sent back around yet
    if self.flipPosition == 5 {
        currentRowOfClick = 0
    }
    //if they are at least on the right row
    if rowOfNode == currentRowOfClick && currentRect.fillColor.hash == 65536{
        return true
    }
    return false
}

【问题讨论】:

  • 什么是name。你还可以展示atPoint() 方法吗?这真的是返回一个 SKShapeNode 吗?
  • @RyanPoolos atPoint() 是 SKNode 类的实例方法。
  • @Bran currentRect 在最好的情况下是 SKNode 或其子类。您不能将其用作函数。

标签: ios swift swift3 sprite-kit


【解决方案1】:

访问SKNodename 属性或SKNode 子类(例如SKShapeNode)的字符有几个挑战。

首先,由于nameString?,因此需要对其进行解包。

guard let string = self.name else {
    return
}

其次,不能用Int下标访问String的字符;您需要使用String.Index

// Since Swift is zero based, the 10th element is at index 9; use 10 if you want the 11th character.
let index = string.index(string.startIndex, offsetBy: 9)
// The 10th character of the name
let char = string[index]

第三,您不能直接将Character 转换为Int。您需要将字符转换为String,然后将字符串转换为Int

let rowString = String(char)

// Unwrap since Int(string:String) returns nil if the string is not an integer
guard let row = Int(rowString) else {
    return
}

此时,rowname 转换为 Int 的第 10 个字符。

或者,您可以将上述实现为扩展

extension String {
    func int(at index:Int) -> Int? {
        let index = self.index(self.startIndex, offsetBy: index)
        let string = String(self[index])
        return Int(string)
    }
}

并与它一起使用

guard let name = self.name, let row = name.int(at:9) else {
    return
}

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 2021-01-15
    • 2021-03-30
    • 2016-03-10
    • 2016-09-26
    • 2017-06-27
    • 2019-05-05
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多