[英]Expose a constant variable from Objective-C to Swift
I have to do a bitwise operation that is for some reason only possible in swift so I am looking to initialize some constants with Objective-C to be used within my application. 我必须执行按位操作,由于某种原因,该操作只能迅速完成,因此我希望使用Objective-C初始化一些常量以在我的应用程序中使用。
I am not that great with objective-c yet so the only way I knew how to do this was to create a class and give it a method that returns the value but I figure that there is a more efficient value. 我对Objective-C的了解还不是很好,所以我知道如何做到这一点的唯一方法是创建一个类,并为其提供一个返回值的方法,但是我认为还有一个更有效的值。
There must be a more succinct way to achieve this. 必须有一个更简洁的方法来实现这一目标。 Currently I am doing the following: 目前,我正在执行以下操作:
Header: 标题:
#import <Foundation/Foundation.h>
#include <simd/simd.h>
#import <MetalKit/MetalKit.h>
#import <Metal/Metal.h>
@interface Bridge:NSObject
@property NSString *url;
- (MTLTextureUsage)readAndWrite;
@end
Implementation: 执行:
#import "MPS-Bridging-Header.h"
@implementation Bridge
- (MTLTextureUsage)readAndWrite {
return MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite;
}
@end
Swift Usage: 迅捷用法:
let bridge = Bridge()
Texture.usage = bridge.readAndWrite()
It would be great if this could be simplified to like MTLTexReadAndWrite
as if it were a constant or perhaps have it so that I can do Bridge().readAndWrite()
so it is all on one line? 如果可以将其简化为像MTLTexReadAndWrite
那样,就像它是一个常量一样,或者有一个常量,这样我就可以执行Bridge().readAndWrite()
以便将它们全部放在一行上,那就Bridge().readAndWrite()
!
If you wanted to expose this to Swift, I'd define a class property: 如果您想将其公开给Swift,我将定义一个class属性:
// Bridge.h
@import Foundation;
@import Metal;
@interface Bridge : NSObject
@property (class, nonatomic, readonly) MTLTextureUsage readAndWrite;
@end
And 和
// Bridge.m
#import "Bridge.h"
@implementation Bridge
+ (MTLTextureUsage)readAndWrite {
return MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite;
}
@end
And you could then use it like so: 然后您可以像这样使用它:
let readAndWrite = Bridge.readAndWrite
But I wonder why you don't just define this constant in Swift: 但我想知道为什么您不只是在Swift中定义此常量:
let readAndWrite: MTLTextureUsage = [.shaderRead, .renderTarget, .shaderWrite]
If you need the same constant in both Objective-C and Swift, use the above bridging pattern, but if you only need it in Swift, then I'd just define it there and eliminate Bridge
altogether. 如果您在Objective-C和Swift中都需要相同的常量,请使用上面的桥接模式,但是如果您仅在Swift中需要它,那么我就在那里定义它并完全消除Bridge
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.