【问题标题】:iOS Swift "Extra argument in 'type' call" error when creating and calling a function创建和调用函数时iOS Swift“'type'调用中的额外参数”错误
【发布时间】:2015-03-14 22:11:35
【问题描述】:

我无法理解为什么在创建和调用以下函数时出现错误。我使用了两个字符串类型的参数。为什么这会产生错误?

import UIKit
import AVFoundation

class PlaySoundsViewController: UIViewController {

    func prepareAudio(sound: String, type: String) -> AVAudioPlayer {
        var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: type)!)

        var error:NSError?

        return AVAudioPlayer(contentsOfURL: sound, error: &error)
    }

    var audioPlayer = prepareAudio(sound: "movie_quote", type: "mp3")

在尝试将 audioPlayer 变量设置为 prepareAudio 函数的结果时,我在“type”调用错误中收到 Extra 参数。

控制器的其余部分如下。最终,我试图打开 mp3 文件“movie_quote”并以较慢的速度播放。

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func slowSpeed(sender: UIButton) {
        audioPlayer.enableRate = true
        audioPlayer.rate = 0.5
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }

【问题讨论】:

  • 在实例化之前,您不能将类上的变量设置为从该类中的方法派生的值。尝试使它成为一个惰性变量:)
  • 'lazy var' 是什么意思?
  • 在var audioPlayer前面添加lazy,确保只有在调用时才会实例化

标签: function swift


【解决方案1】:

为了使代码按照您的方式工作,您需要将prepareAudio 设为类方法,而不是实例方法。所以生成的代码应该是这样的:

class PlaySoundsViewController: UIViewController {

    class func prepareAudio(sound: String, type: String) -> AVAudioPlayer {
        var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: type)!)

        var error:NSError?

        return AVAudioPlayer(contentsOfURL: sound, error: &error)
}

    var audioPlayer: AVAudioPlayer = PlaySoundsViewController.prepareAudio("movie_quote", type: "mp3")
}

还请注意,我将函数调用更改为prepareAudio("movie_quote", type: "mp3"),因为默认情况下第一个参数没有外部名称。要改变这一点,你可以在定义方法时写class func prepareAudio(#sound: String, type: String)

【讨论】:

  • 它不是“必须”成为类变量。也可以惰性实例化
猜你喜欢
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
相关资源
最近更新 更多