GameKit and Swift: instance property is not an optional but can be nil?

74 views Asked by At

GKTurnBasedParticipant has a property: player, which has class GKPlayer. The declaration is written as:

var player: GKPlayer { get }

Yet the API documentation says,

The value of this property may be nil if this slot in the match has not yet been filled by an actual player.

So if it can be nil, why isn't the declaration:

var player: GKPlayer?

What am I not understanding here? Is it something with the getter? This is actually important because the player should be nil for automatched games where a second player has yet to join.

When I do conditional unwrapping (after migrating to Swift 4.2)

if let onlineGKPlayer = participant.player {

this now is a compiler error:

Initializer for conditional binding must have Optional type, not 'GKPlayer'

Screenshot from GKTurnBasedParticipant player

https://developer.apple.com/documentation/gamekit/gkturnbasedparticipant/1521037-player

1

There are 1 answers

0
nickcin On

Not sure when it was updated, but the API documentation now lists it as an Optional:

var player: GKPlayer? { get }

It seems you had the right idea