简体   繁体   中英

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 CI cannot use String.Encoding ?

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM