Reputation: 325
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}
}
}
Upvotes: 30
Views: 30331
Reputation: 12363
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()
}
Upvotes: 10
Reputation: 36287
if audioPlayer.playing { audioPlayer.stop} else { audioPlayer.play}
is just accessing the member variables. It's not doing anything.
I am sure you're intention was to do audioPlayer.stop() and audioPlayer.start().
However just to explain the ERROR and not to solve your issue: had you done something like
if audioPlayer.playing { self.playerStatus= audioPlayer.stop} else { self.playerStatus = audioPlayer.play}
Then you were actually doing something you were set
ting a parameter. accessing or just get
ting a parameter is stupid in the eyes of the compiler :)
Upvotes: 0
Reputation: 31486
Here's a simplified version of Brian's answer:
audioPlayer.playing
? audioPlayer.stop()
: audioPlayer.play()
Upvotes: 5
Reputation: 6831
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()
}
Upvotes: 29