Nslog Is Unavailable

NSLog' is unavailable: Variadic function is unavailable in swift

If you declare var myString: NSString? as an optional then you need to make sure it has a value before you pass it to the NSLog.

So you could do it like this then NSLog("%@" , myString!). If myString is nil and you put ! the program will crash and you will get

fatal error: unexpectedly found nil while unwrapping an Optional value.

But if it has a value the program will continue as normal and print out

2016-10-03 10:26:25.077 Swift3.0[65214:1579363] Test

I wrote myString = "Test".

Another example as @Grimxn mentioned is the coalescing operator.

NSLog("%@", myString ?? "<nil>")

NSLog is unavailable

Similar as in C, you cannot pass a variable argument list directly
to another function. You have to create a CVaListPointer (the Swift
equivalent of va_list) and pass that to the NSLogv variant:

func myNSLog(_ givenFormat: String, _ args: CVarArg..., _ function:String = #function) {
let format = "\(function): \(givenFormat)"
withVaList(args) { NSLogv(format, $0) }
}

(Swift 3 code.)

Issue with NSLog with Swift 3

The problem, despite the "variadic" red herring, is that we no longer get automatic bridging to an Objective-C type; you have to cross the bridge explicitly, yourself. Write saveError as NSError to get an Objective-C style object.

Treat using NSLog as a build error

Try this,

#define NSLog_UNAVAILABLE __attribute__((unavailable("NSLog is treated as Error.")))
FOUNDATION_EXPORT void NSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2) NSLog_UNAVAILABLE;

shm_open Gives Variadic function is unavailable in swift

Turned out that shm_open works fine, it is just that swift can't use Variadic C functions.

I solved the problem by creating a new c file with the function:

int shmopen(const char *path) {
return shm_open(path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
}

Place the function in the "Project-Bridging-Header.h" file:

int shmopen(const char *path);

Call the function from swift:

var fd = shmopen("/myregion")
print(fd)

And now it works fine.

Disallow NSLog to be used

If you re-declare NSLog (and perhaps also NSLogv) as

void NSLog(NSString *format, ...) UNAVAILABLE_ATTRIBUTE;
void NSLogv(NSString *format, va_list args) UNAVAILABLE_ATTRIBUTE;

in your precompiled header file, you get a nice error message:


main.m:199:3: error: 'NSLog' is unavailable
NSLog(@"%@", s1);
^

You can even provide a custom error message (found in Messages on deprecated and unavailable Attributes of the Clang documentation):

void NSLog(NSString *format, ...) __attribute__((unavailable("You should not do this!")));


main.m:202:3: error: 'NSLog' is unavailable: You should not do this!
NSLog(@"%@", s1);
^


Related Topics



Leave a reply



Submit