表达式解析为未使用的函数

时间:2015-04-09 20:30:00

标签: swift

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

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}
}
}

4 个答案:

答案 0 :(得分:25)

在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()
}

答案 1 :(得分:5)

这是Brian回答的简化版本:

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

答案 2 :(得分:2)

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

public function formatLinksInText($text)
{
    //Catch all links with protocol      
    $reg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(\/\S*)?/'; 
    $formatText = preg_replace($reg, '<a href="$0" style="font-weight: normal;" target="_blank" title="$0">$0</a>', $formatText);

    //Catch all links without protocol
    $reg2 = '/(?<=\s|\A)([0-9a-zA-Z\-\.]+\.[a-zA-Z0-9\/]{2,})(?=\s|$|\,|\.)/';
    $formatText = preg_replace($reg2, '<a href="//$0" style="font-weight: normal;" target="_blank" title="$0">$0</a>', $formatText);

    //Catch all emails
    $emailRegex = '/(\S+\@\S+\.\S+)/';
    $formatText = preg_replace($emailRegex, '<a href="mailto:$1" style="font-weight: normal;" target="_blank" title="$1">$1</a>', $formatText);
    $formatText = nl2br($formatText);
    return $formatText;
}

<强>解决方案:

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

func addView(){
}

答案 3 :(得分:0)

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

我确信你的意图是做audioPlayer.stop()和audioPlayer.start()。

然而,只是为了解释错误而不解决您的问题: 你做过像

这样的事吗?
if audioPlayer.playing { self.playerStatus= audioPlayer.stop} else {  self.playerStatus = audioPlayer.play}

然后你实际上正在 set ting 一个参数。 访问或只是 get ting 参数在编译器的眼中是愚蠢的:)