4

I'm trying to bring some Swift code into my older obj-c project. Swift class is accessible from obj-c class, but not all of it's properties though. For example

public var menuTitleColor: UIColor!

works perfectly fine, but

public var cellHeight: CGFloat!

is not found. I think it's because CGFloat is not an object. Is there a way to access this property without changing Swift file?

NKorotkov
  • 3,591
  • 1
  • 24
  • 38

2 Answers2

4

Primitive types in Objective-C

Look at this Swift class

@objc class Foo: NSObject {
    var myCGFloatOptional: CGFloat? = 1
    var myCGFloat: CGFloat = 1
}

If I use it in Objective-C only the myCGFloat property is available.

Foo * foo = [Foo new];
foo.myCGFloat;
foo.myCGFloatOptional; // Compile Error

This because in Objective-C CGFloat is a primitive type (like float). And Objective-C does not allow nil values for a primitive type.

Just like you cannot write this in Objective-C

float number = 1;
number = nil; // compile error

References to instances of classes

In your Objective-C code you are able to see a property of type UIColor! declared in Swift because UIColor is a class. So you are declaring a pointer that could reference an instance of UIColor or nothing.

And in Objective-C the same concept does exist.

Note

You could note that int is a primitive type as well in Objective-C but, "unexpectedly", the compiler does allow you to write

int number = 1;
number = nil;

However in this case nil is simply interpreted as the integer 0 (still a value, not really nil).

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Great explanation, thanks a lot! I accepted your answer instead of the first one, since it provides a lot more info on the subject and will be a lot more useful to anyone stumbling upon same issue. – NKorotkov Dec 04 '15 at 09:06
1

You can try this code:

public var cellHeight: CGFloat = 0 //(or some other number)

Sushil Sharma
  • 2,321
  • 3
  • 29
  • 49
Earl Grey
  • 7,426
  • 6
  • 39
  • 59
  • I never bridged Swift stuff to ObjC but it might have something to do with the property being a primitive value type. And it is unable to treat it as a force unwrapped reference type. – Earl Grey Dec 03 '15 at 12:15
  • Primitives can't be nil in ObjC, so optional primitive properties are not imported. See https://stackoverflow.com/a/26366289/72176 for a more detailed discussion. – William Denniss Jul 24 '17 at 14:21