我正在尝试将 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 *'
任何人都可以提供有关如何访问 Swift 类及其属性的建议吗?
多年过去了,苹果似乎仍然没有提供这样的前瞻性声明的解决方案。不过,有一个解决方法:在 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)
}
}
}