I'm converting some code from Objective-C to Swift and I have a very simple function that reads text from a file into a string.
@implementation DecodeFile
- (NSString * _Nullable)readFile:(nonnull NSURL *)selectedFile {
NSString *utf8 = [[NSString alloc] initWithContentsOfURL:selectedFile encoding:NSUTF8StringEncoding error:nil];
if (utf8) { return utf8; }
NSString *ascii = [[NSString alloc] initWithContentsOfURL:selectedFile encoding:NSASCIIStringEncoding error:nil];
if (ascii) { return ascii; }
return nil;
}
@end
If utf8 fails, it attempts ascii. This works perfectly fine, but my Swift implementation fails with an ASCII file that succeeds using Obj-C!
print(try? String(contentsOf: selectedFile, encoding: .utf8)) <-- nil
print(try? String(contentsOf: selectedFile, encoding: .ascii)) <-- nil
print(String(data: data, encoding: .utf8)) <-- nil
print(String(data: data, encoding: .ascii)) <-- nil
// Obj-C implementation
print(DecodeFile().read(selectedFile)) <-- WORKS
Why would this fail, and how can I get the same behaviour from Swift as Obj-C?
try?. Usetry/catchand printerrorin thecatchso you can see why it fails..windowsCP1252. So when UTF fails, the ASCII also fails but falls back to WinCP.