Search code examples
iosswiftfunctionsyntaxavplayer

Cannot access a function member using dot notation swift


I cannot access the playerAv() function's elements outside of the function. How can I access it?

And also I tried to remove the function and use these lines outside of any function and I got an error in the second line. Why I couldn't assign audioLink value outside of a function?

var audioLink = "somewebpage.com/abc.pls"
var player:AVPlayer = AVPlayer(URL: NSURL(string: audioLink))

I tried

let pa = playerAv()
pa.player.volume = currentValue //I got an error here:(
println(currentValue)

A part of code:

 func playerAv(){
        
        var audioLink = "somewebpage.com/abc.pls"
        var player:AVPlayer = AVPlayer(URL: NSURL(string: audioLink))
    }
@IBAction func sliderValueChanged(sender: UISlider) {
        var currentValue = Float(sender.value)
        println(currentValue)
        player.volume = currentValue
    }

Thanks


Solution

  • You're very confused.

    You are mixing up classes and functions.

    A function's local variables are not accessible outside the function by design. They only exist inside the scope of the function, and cease to exist as soon as the function returns. Thus your playerAv() function doesn't do anything useful.

    It looks to me like you want playerAv to be a class, with instance variables:

    class PlayerAv
    {
      let audioLink: String = "http://somewebpage.com/abc.pls"
      var player: AVPlayer
      init()
      {
        player = AVPlayer(URL: NSURL(string: self.audioLink))
      }
    }
    

    Now you can create a PlayerAv object and use it:

    let pa = playerAv()
    pa.player.volume = currentValue