Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression resolves to an unused function

Tags:

swift

First of all let me say that I am very new to programming. What I'm trying to do is add a button that when pressed plays music, and when pressed again the music stops. Ideally when the button is pressed for a third time the music will have reset. Whilst trying to achieve this I'm getting the error message "Expression resolves to an unused function", as I am very new all the help I find online doesn't make any sense to me.

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}
}
}
like image 640
lucambd Avatar asked Apr 09 '15 20:04

lucambd


3 Answers

Swooping in here after Martin R's comment ...

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

On this line, you are not calling the stop and play functions, but simply accessing them. Resolving to an unused function is trying to tell you that you have an expression that is returning a function type, but you are never calling it (audioPlayer.stop and audioPlayer.play are the expressions in question here).

To rid yourself of this error, and probably produce the correct behavior, try calling the functions.

if audioPlayer.playing { 
    audioPlayer.stop()
} else {  
    audioPlayer.play()
}
like image 146
Brian Tracy Avatar answered Oct 31 '22 20:10

Brian Tracy


Swift 4: Just add the braces '()' next to the method name

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

func addView(){
}

Solution:

override func viewWillAppear(_ animated: Bool) {
   addView()
}
like image 38
Naishta Avatar answered Oct 31 '22 21:10

Naishta


Here's a simplified version of Brian's answer:

audioPlayer.playing
    ? audioPlayer.stop()
    : audioPlayer.play()
like image 5
Rudolf Adamkovič Avatar answered Oct 31 '22 21:10

Rudolf Adamkovič