Поиск nil при развертывании node.name.last () - PullRequest
0 голосов
/ 08 сентября 2018

У меня проблема с кодом ниже, мне очень нужна последняя буква имени узла, на котором я нажимаю.

Для этого я перебираю все дочерние узлы моей сцены, пока не найду тот, который разделяет местоположение с моей точкой касания.

Как только я нашел это, я использую охранное состояние:

let nodeName = node.name
            guard let letter = nodeName?.last else { return }

чтобы найти букву, но компилятор не продолжает выполнять функции, так как он находит ноль при попытке извлечь последний символ из имени узла.

СПАСИБО МИЛЛИОНОВ ЗА ПАЦИЕНТ СО МНОЙ И МОЙ КОДЕКС, КАК Я Я НАЧИНАЮЩИЙ

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

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

    for node in scene.children {
        if node.frame.contains(touchPosition) && node.name != "background" {
            let nodeName = node.name
            guard let letter = nodeName?.last else { return }
            handleGuess(letter: letter)
            node.removeFromParent()
            if !(lettersToGuess?.contains(letter))! && letter != "1" && letter != "0" {
                currentStep += 1
            } else if letter == "1" {

            } else if letter == "2" {

            } else if letter == "3" {

            } else if letter == "4" {

            }
        }
    }
}

func setupMenu() {      
    // Load Background and place background image
    let backgroundTexture = SKTexture(imageNamed: "menuBG")
    background.texture = backgroundTexture
    background.zPosition = -1
    background.position = CGPoint(x: frame.midX * 0.25, y: frame.midY)
    let bgSizeFactor = backgroundTexture.size().height / frame.size.height
    background.size = CGSize(width: backgroundTexture.size().width / bgSizeFactor , height: frame.size.height)
    addChild(background)

    animateBackground()
    setupRain()

    // TODO: Add Button center screen displaying current level, clicking this will start a new game.
    let playTexture = SKTexture(imageNamed: "playButton")
    let playButton = SKSpriteNode(texture: playTexture)
    playButton.name = "playbutton2"
    let playButtonFactor = playTexture.size().width / frame.size.width
    playButton.size = CGSize(width: frame.size.width * 0.65, height: (playTexture.size().height / playButtonFactor) * 0.65)
    playButton.position = CGPoint(x: frame.midX, y: frame.midY)
    playButton.zPosition = 1
    addChild(playButton)

    let rateTexture = SKTexture(imageNamed: "rateButton")
    let rateButton = SKSpriteNode(texture: rateTexture)
    rateButton.name = "rateButton3"
    rateButton.size = CGSize(width: playButton.size.height * 0.85, height: playButton.size.height * 0.85)
    rateButton.position = CGPoint(x: frame.midX, y: frame.midY - playButton.size.height)
    rateButton.zPosition = 1
    addChild(rateButton)

    let noAdsTexture = SKTexture(imageNamed: "noAdsButton")
    let noAdsButton = SKSpriteNode(texture: noAdsTexture)
    noAdsButton.name = "noAdsButton4"
    noAdsButton.size = CGSize(width: playButton.size.height * 0.85, height: playButton.size.height * 0.85)
    noAdsButton.position = CGPoint(x: frame.midX - playButton.size.height, y: frame.midY - playButton.size.height)
    noAdsButton.zPosition = 1
    addChild(noAdsButton)

    let zapTexture = SKTexture(imageNamed: "zapButton")
    let zapButton = SKSpriteNode(texture: zapTexture)
    zapButton.name = "zapButton5"
    zapButton.size = CGSize(width: playButton.size.height * 0.85, height: playButton.size.height * 0.85)
    zapButton.position = CGPoint(x: frame.midX + playButton.size.height, y: frame.midY - playButton.size.height)
    zapButton.zPosition = 1
    addChild(zapButton)
}

1 Ответ

0 голосов
/ 08 сентября 2018

Я думаю, что ваша нижняя строка является проблемой

guard let letter = nodeName?.last else { return }

Вы возвращаетесь сюда, который прерывает цикл for и возвращает метод. Вместо этого попробуйте заменить его ниже.

guard let letter = nodeName?.last else { continue }

Выше просто продолжится цикл, если буква равна нулю для текущего узла.

...