Search code examples
swiftxcodeswift4xcode9

"Extensions may not contain stored properties" unless your are Apple? What am I missing?


How come Apple can do this:

import CoreGraphics
import GameplayKit
import simd

/**
 @header


 SceneKit framework category additions related to GameplayKit integration.


 @copyright 2017 Apple, Inc. All rights reserve.

 */

extension SCNNode {


    /**
     * The GKEntity associated with the node via a GKSCNNodeComponent.
     *
     * @see GKEntity
     */
    @available(OSX 10.13, *)
    weak open var entity: GKEntity?
}

/**
 * Adds conformance to GKSceneRootNodeType for usage as rootNode of GKScene 
 */
extension SCNScene : GKSceneRootNodeType {
}

... and I cannot do this:

extension SCNNode {
    weak open var ntity: GKEntity?
}

and get two errors:

  • 'weak' may only be applied to class and class-bound protocol types, not '<<error type>>'
  • Extensions may not contain stored properties

What I would like to actually do is to provide an entity property on OSX versions before 10.13, so additional suggestions for that are also welcome.


Solution

  • This is currently not possible in Swift. As noted by Sulthan this is an Objective-C category for which you see the Swift version, which is generated by Xcode.

    Now, Objective-C does not easily support adding properties in categories (extensions are called categories in Objective-C), but you can use associated objects to get what you want.

    Mattt Thompson has a great article about associated objects on his NSHipster blog: Associated Objects - NSHipster