I keep trying to fix this error and trying to make the character contain in the row which will be an 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
}
There are several challenges accessing the characters of the name
property of SKNode
or an SKNode
subclass (such as SKShapeNode
).
First, since name
is a String?
, it needs to be unwrapped.
guard let string = self.name else {
return
}
Second, you can't access the characters of a String
with an Int
subscript; you'll need to use a 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]
Third, you can't directly convert a Character
to an Int
. You'll need to convert the character to a String
and then convert the string to an 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
}
At this point, row
is the 10th character of name
converted to an Int
.
Alternatively, you can implement the above as an extension
extension String {
func int(at index:Int) -> Int? {
let index = self.index(self.startIndex, offsetBy: index)
let string = String(self[index])
return Int(string)
}
}
and use it with
guard let name = self.name, let row = name.int(at:9) else {
return
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.