J.Doe
J.Doe

Reputation: 1552

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.

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.

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?

Upvotes: 1

Views: 729

Answers (1)

Rob
Rob

Reputation: 437482

If you wanted to expose this to Swift, I'd define a class property:

//  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:

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.

Upvotes: 2

Related Questions