【问题标题】:Expression resolves to an unused function表达式解析为未使用的函数
【发布时间】:2015-06-15 09:38:56
【问题描述】:

首先让我说我对编程很陌生。我想要做的是添加一个按钮,按下时播放音乐,再次按下时音乐停止。理想情况下,当第三次按下按钮时,音乐将重置。在尝试实现这一点时,我收到错误消息“表达式解析为未使用的函数”,因为我很新,我在网上找到的所有帮助对我来说都没有任何意义。

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @IBOutlet weak var janitor: UIImageView!
    var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a")!)
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
        audioPlayer.prepareToPlay()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


        @IBAction func PianoC(sender: AnyObject) {

        audioPlayer.play()

            if audioPlayer.playing { audioPlayer.stop} else {  audioPlayer.play}
}
}

【问题讨论】:

  • stop --> stop(), play --> play() ...

标签: swift


【解决方案1】:

斯威夫特 4: 只需在方法名称旁边添加大括号'()'

override func viewWillAppear(_ animated: Bool) {
   addView //error: Expression resolves to an unused function
}

func addView(){
}

解决方案:

override func viewWillAppear(_ animated: Bool) {
   addView()
}

【讨论】:

    【解决方案2】:

    if audioPlayer.playing { audioPlayer.stop} else { audioPlayer.play} 只是访问成员变量。它没有任何事情。

    我确定您的意图是执行 audioPlayer.stop() 和 audioPlayer.start()。

    但是只是为了解释错误而不是解决您的问题: 你做过类似的事情吗

    if audioPlayer.playing { self.playerStatus= audioPlayer.stop} else {  self.playerStatus = audioPlayer.play}
    

    那么你实际上是在一些你是setting参数的事情。 访问或只是getting一个参数在编译器眼中是愚蠢的:)

    【讨论】:

      【解决方案3】:

      这是布赖恩回答的简化版本:

      audioPlayer.playing
          ? audioPlayer.stop()
          : audioPlayer.play()
      

      【讨论】:

      • @Fr4nc3sc0NL 为什么会这样?
      • @RudolfAdamkovic 你不解释这段代码在做什么
      • @grooveplex 这是一个三元表达式。如果音频播放器正在播放,它将停止。如果没有,它将开始播放。
      • 它基本上是 if else 条件的简写。代码转换为 - If audioPlayer.playing audioPlayer.stop() else audioPlayer.play()
      【解决方案4】:

      在 Martin R 的评论之后突然出现在这里......

      if audioPlayer.playing { audioPlayer.stop} else {  audioPlayer.play}
      

      在这一行中,您没有调用stopplay 函数,而只是访问它们。 Resolving to an unused function 试图告诉您,您有一个返回函数类型的表达式,但您从未调用它(audioPlayer.stopaudioPlayer.play 是这里有问题的表达式)。

      要摆脱此错误并可能产生正确的行为,请尝试调用函数。

      if audioPlayer.playing { 
          audioPlayer.stop()
      } else {  
          audioPlayer.play()
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-30
        • 2016-04-22
        • 2015-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多