Shane D
Shane D

Reputation: 884

String.Encoding is not getting translated to NSStringEncoding in swift 3 to objective C conversion

Am converting my existing swift source code base to swift 3 and have a method in a swift class which was earlier returning NSStringEncoding. In swift 3, the compiler asks me to convert NSStringEncoding to String.Encoding. But this method is now not getting reflected in the objective-c's generated interface and now am not able to call this method in my objective-c classes.

This is a sample code snippet :

@objc
open class MyClass: NSObject{
    open var textEncoding: String.Encoding { get { return self.getEncoding() } }

    fileprivate func getEncoding() -> String.Encoding{
        // some conversion code
        return encoding
    }
}

In an objective-c class,

-(void)demoFunc:(MyClass * _Nonnull)response{
(i)  NSStringEncoding responseEncoding = response.textEncoding;
}

The compiler is throwing this error for the above line,

Property 'textEncoding' not found on object of type 'MyClass *'

How do I fix this issue as I cannot declare/use NSStringEncoding in swift file and in Objective C I cannot use String.Encoding ?

Upvotes: 1

Views: 769

Answers (1)

Martin R
Martin R

Reputation: 539805

Foundation defines

typedef NSUInteger NSStringEncoding;
NS_ENUM(NSStringEncoding) {
    NSASCIIStringEncoding = 1,      /* 0..127 only */
    // ...
};

which is mapped to Swift as

extension String {
    public struct Encoding : RawRepresentable {
        public var rawValue: UInt
        // ...
    }
}

So what you can do is to pass the raw value back to Objective-C:

open var textEncoding: UInt { return self.getEncoding().rawValue }

Upvotes: 3

Related Questions