5

I'm working on an ios application that has a mix of swift and obj-c code. One of my obj-c model classes defines a struct containing strings to assist in converting to a dictionary and back. I have the bridging header setup and I can access methods defined in my objective-c class in a swift class. What I can't figure out is how to access the static stuct to get at my property strings. Here is a snippet of my .h and .m files:

OrderItem.h

extern const struct OrderItemAttributes {
    __unsafe_unretained NSString *created;
    __unsafe_unretained NSString *created_by_id;
    __unsafe_unretained NSString *device_deleted;
} OrderItemAttributes;

@interface OrderItem : NSManagedObject {}
@property (nonatomic, strong) NSDate* created;
@end

OrderItem.m

const struct OrderItemAttributes OrderItemAttributes = {
    .created = @"created",
    .created_by_id = @"created_by_id",
    .device_deleted = @"device_deleted",
};

@implementation OrderItem
@dynamic created;
@end

I thought I would simply be able to use

OrderItem.OrderItemAttributes.created

to access the attribute strings but swift doesn't accept that syntax. Is there any way to do what I want without major changes to my objective-c code?

3

1 Answer 1

2

The variable OrderItemAttributes isn't part of the OrderItem namespace. It would be accessed directly as:

var foo: NSString = OrderItemAttributes.created.takeUnretainedValue()

The problem you're seeing with autocomplete occurs because OrderItemAttributes is ambiguous; it's both a type name and a variable name. Use different names for the struct type name and the global variable to avoid the ambiguity. E.g., add 'Struct' to the end of the type name:

extern const struct OrderItemAttributesStruct {
    __unsafe_unretained NSString *created;
    __unsafe_unretained NSString *created_by_id;
    __unsafe_unretained NSString *device_deleted;
} OrderItemAttributes;
Sign up to request clarification or add additional context in comments.

2 Comments

Why is it only visible from Swift when the __unsafe_unretained is applied? Without it results in "Cannot reference invalid declaration", same if __weak is used.
@TT-- Swift cannot (yet) safely track object references that are inside of a plain old C Struct, so you have to explicitly declare those references as unmanaged. That feature was only added to ObjC in 2018, and there was/is a proposal to add it to Swift as well: forums.swift.org/t/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.