2

I'm converting a swift project to objective c, but i get some trouble because i don't know how to convert follow code. Please help me. Thanks!

   public enum UPCarouselFlowLayoutSpacingMode {
    case fixed(spacing: CGFloat)
    case overlap(visibleOffset: CGFloat)
}

and

fileprivate var currentPage: Int = 0 {
    didSet {
        let character = self.items[self.currentPage]
        self.infoLabel.text = character.name.uppercased()
        self.detailLabel.text = character.movie.uppercased()
    }
}
2
  • 2
    The first snippet cannot be converted to Objective-C because an enum with associated types is not available in ObjC. The second snippet can be converted by implementing the explicit setter of the property.
    – vadian
    Commented Jan 20, 2017 at 5:38
  • 1
    Converting Objective-C to Swift is a much easier task than trying to do a one-to-one conversion from Swift to Objective C. Swift's enums are unique and powerful, I doubt you'll find a simple way to convert it to Swift Commented Jan 20, 2017 at 5:38

1 Answer 1

5

The first (an enum with associated values) has no direct equivalent in Objective-C. For your particular example, you could use something like this:

typedef NS_ENUM(NSInteger, UPCarouselFlowLayoutSpacingMode) {
    UPCarouselFlowLayoutSpacingModeFixed,
    UPCarouselFlowLayoutSpacingModeOverlap
};

typedef struct {
    UPCarouselFlowLayoutSpacingMode mode;
    CGFloat amount;
} UPCarouselFlowLayoutSpacing;

You would just pass around values of type UPCarouselFlowLayoutSpacing. You could create helper functions to make these easier to create, e.g.

UPCarouselFlowLayoutSpacing UPCarouselFlowLayoutSpacingMakeFixed(CGFloat spacing) {
    UPCarouselFlowLayoutSpacing value;
    value.mode = UPCarouselFlowLayoutSpacingModeFixed;
    value.amount = spacing;
    return value;
}

UPCarouselFlowLayoutSpacing UPCarouselFlowLayoutSpacingMakeOverlap(CGFloat visibleOffset) {
    UPCarouselFlowLayoutSpacing value;
    value.mode = UPCarouselFlowLayoutSpacingModeOverlap;
    value.amount = visibleOffset;
    return value;
}

For the second, you can override the setter method of your Objective-C class's currentPage property:

- (void)setCurrentPage:(NSInteger)page {
    _page = page;

    MovieCharacter *character = self.items[page];
    self.infoLabel.text = character.name.localizedUppercaseString;
    self.detailLabel.text = character.movie.localizedUppercaseString;
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.