转发声明一个 Swift 类以在 Objective-C 头文件中使用它

Shl*_*san 6 types objective-c swift objective-c-swift-bridge

我正在尝试将 Swift 类导入到 Objective-C 头文件中。我知道Project-Swift.h桥只能导入到实现文件 (.m) 中,但我有一个 Objective-C 头文件,需要声明一个在 Swift 中定义的属性。

我在某处读到这可以通过在头文件中向前声明类并导入Project-Swift.h到实现文件中来完成。当我这样做时,错误得到解决,但我无法访问任何类属性。

例子:

// Square.swift

@objc class Square: NSObject {
  var width: Int?
  var height: Int?
}

// Shapes.h

@class Square;

@interface Shapes: NSObject {
  @property(nonatomic, strong) Square *square;
}

// Shapes.m

#import "Shapes.h"
#import "Product-Swift.h"

@implementation Shape

@end

// Somewhere else in the code

Shapes *shapes = [Shapes new];
NSLog(@"%@", @(shapes.square.width)); <-- Property 'width' not found on object of type 'Square *'
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供有关如何访问 Swift 类及其属性的建议?

Dar*_*ust 0

多年过去了,苹果似乎仍然没有提供这样的前瞻性声明的解决方案。不过,有一个解决方法:在 Swift 扩展中声明 Objective-C 类的属性,并使用关联的对象。

例如:

import ObjectiveC

// Only the _address_ of this variable is going to be needed.
private var squareHandle: UInt8 = 0

extension Shapes {
    var square: Square {
        get {
            if let instance = objc_getAssociatedObject(self, &squareHandle) as? Square {
                // Already have an instance, use that.
                return instance
            }

            // Here, we want a non-optional can use default initialization.
            // Create a new instance.
            let instance = Square()
            objc_setAssociatedObject(self, &squareHandle, instance, .OBJC_ASSOCIATION_RETAIN)
            return instance
        }

        set {
            objc_setAssociatedObject(self, &squareHandle, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)