SwiftUI Tutorial - Scrumdinger - mysterious AVPlayer initialization syntax

I've been following the Scrumdinger tutorial and had close to no trouble understanding the concepts, supplementing myself with the Swift guide.

However, in the state and lifecycle lesson, exactly in the complete project, I've found confusing syntax that I cannot decipher with certainty.

private var player: AVPlayer { AVPlayer.sharedDingPlayer }

What does the closure after the AVPlayer type mean?

sharedDingPlayer is a static property extending AVPlayer, so my guess is that it's either some kind of casting to this exact type or assigning the static prop to the player property when it's available.

I would appreciate any help in clearing this out!

Accepted Reply

private var player: AVPlayer { AVPlayer.sharedDingPlayer }

This is how a computed var is defined.

It is equivalent to:

private var player: AVPlayer { 
  get {
     return AVPlayer.sharedDingPlayer
   }
}
  • You are of course right! This one-liner even confused me, though I used many computed vars in Swift already. ;-)

  • Thank you for the elaborate example! I'm just starting to get used to all the shortcuts that Swift has to offer.

  • As a side note - correct me if I'm wrong, but isn't including the type information redundant, since Swift could infer it from the declaration?

Replies

I can not find your quoted code private var player: AVPlayer { AVPlayer.sharedDingPlayer } in the Project Files.

Did you mean private var player: AVPlayer = { AVPlayer.sharedDingPlayer }() ?

This initialises the playervariable of Type AVPlayer with the result of the provided closure, which simply returns AVPlayer.sharedDingPlayer while leaving out the not needed return statement.

  • It was precisely the line I included. It is to be found in the MeetingView.swift file, line 12.

Add a Comment
private var player: AVPlayer { AVPlayer.sharedDingPlayer }

This is how a computed var is defined.

It is equivalent to:

private var player: AVPlayer { 
  get {
     return AVPlayer.sharedDingPlayer
   }
}
  • You are of course right! This one-liner even confused me, though I used many computed vars in Swift already. ;-)

  • Thank you for the elaborate example! I'm just starting to get used to all the shortcuts that Swift has to offer.

  • As a side note - correct me if I'm wrong, but isn't including the type information redundant, since Swift could infer it from the declaration?