Swift and Objc interoperability - availability not working only in objc - ios

While here Apple states that the Swift available flag should be applied also in objc, it's not working for me. What am I doing wrong?
I've got following declarations in Swift files:
#objc protocol Readable: AnyObject {...}
#available(iOS 10.3, *)
#objc class Reader: NSObject, Readable {...}
So let's check if it produces an error when I try to initialize it in pre-ios-10 project without version check. If I write following code in Swift:
let tmp = Reader()
it returns an error:
'Reader' is only available on iOS 10.3 or newer
What is expected.
However if I write following code in objc:
// if (#available(iOS 10.3, *)) { // commeted out to test if it succeeds without version check
Reader *tmp = [[Reader alloc] init];
// }
The build is finished without any error, while I'd expect the same error as in Swift.
I've tried to mark the class with:
#available(iOS 11, *)
#available(iOS, introduced: 10.3)
Neither of these works (produces an error) in objc. Any help, please?

Objective-C has had __attribute__((availability)) for longer than it has had #available. To make it work, the Objective-C compiler weakly links symbols that are not available on the deployment target. This means that compiling always succeeds, and starting your app succeeds, but the symbol will be NULL at runtime if it is not available.
Depending on what it is, you'll get more or less graceful degradation when you try to use it:
calling a weakly-linked function that is missing is going to crash
reading or writing to a global variable that is missing is going to crash
using a class that is missing will be a no-op and all methods are going to return zero
The old way of testing whether a symbol is found at runtime is just to compare it to NULL:
NS_AVAILABLE_MAC(...) #interface Foo #end
int bar NS_AVAILABLE_MAC(...);
int baz(int frob) NS_AVAILABLE_MAC(...);
if ([Foo class]) { /* Foo is available */ }
if (&bar) { /* bar is available */ }
if (&baz) { /* baz is available */ }
In your case:
Reader *tmp = [[Reader alloc] init];
tmp will be nil, because that would be the same as [[nil alloc] init].
The #available directive has only relatively recently been added to Objective-C. It's now possible to use #available in Objective-C in the same way that you use #available in Swift. However, to preserve backwards compatibility, it possibly never will be a compile-time error (at default error levels) to try to use a symbol that might not be available on the deployment target in Objective-C.

Related

Cannot add #if compiler(>=5.0) in `AppDelegate.m` file:

Trying to add a block in the AppDelegate.m file
#if compiler(>=5.0)
if (#available(iOS 13.0, *)) {
// do something...
}
#endif
The error showed is:
Function-like macro 'compiler' is not defined
The following is a Swift compile-time directive:
#if compiler(>=5.0)
...
#endif
It makes no sense to use this in an Objective-C file, AppDelegate.m. In an Objective-C source, it will result in the “Function-like macro 'compiler' is not defined” error.
So, if you want a runtime check for iOS 13, just remove the #if, e.g.:
if (#available(iOS 13.0, *)) {
...
}
See Marking API Availability in Objective-C.
A couple of observations (given that you tagged this with swift):
In Swift, the compile-time pattern is:
#if swift(>=5.0)
...
#endif
Or
#if compiler(>=5.0)
...
#endif
This pattern is generally only used when writing third-party libraries where you need to offer backward support to developers who are compiling your library with earlier versions of Swift.
See The Swift Programming Language: Compiler Control Statements
The following is an Objective-C runtime check for OS version:
if (#available(iOS 13.0, *)) {
// do something...
}
The equivalent Swift pattern is:
if #available(iOS 13.0, *) {
...
}
These are useful when writing code that is targeting multiple iOS versions, but you want to conditionally run code using iOS 13+ API.
To make it confusing, Swift does have an #available construct, but it is for marking a class, extension, or method as being available only for devices running a particular OS version, but is not used in conjunction with an if test. E.g. let’s say you are defining some function that should only be available to iOS 13 and later:
#available(iOS 13.0, *)
func someMethod() {
...
}
This is compile-time construct is to tell the compiler to not complain about iOS 13 API within this function if your app happens to support earlier iOS versions. You are effectively telling the compiler “hey, I know this has code inside it that only works with iOS 13 and later, but don’t worry, because I’ll only call it when the device in question is running iOS 13 or later.”
There are many things wrong that you did in your code example:
#if is a preprocessor macro. You can only use it outside the scope of anything, just like the import statement. If you are using it the way it should be used, then you can't use that if statement there.
#available cannot be used inside of an if statement. It can only be used to represent if a particular class/struct/func is available for said OS version and up, but not fragments of code. For that, use this instead:
if #available(iOS 13.0, *) {
// Do something.
}
If you want to check the Swift compiler version specifically, you can use #if swift. To check for iOS version during runtime, you need to use #available, the # version if used to mark types/functions only available on said versions.
#if swift(>=5.0)
if #available(iOS 13,*) {
//do something
}
#endif

os_log - use of unresolved identifier error

I'm trying to use the new os_log API, by logging a simple statement:
os_log("Hello")
And I get an error for os_log:
Use of unresolved identifier 'os_log'
I also tried wrapping it in a block, like this
if #available(iOS 10.0, *) {
let foo: StaticString = "Something happened."
os_log(foo)
}
And I still get the same error. I would like to use this in Swift 4.
I looked for possible frameworks that might be required, and found no likely candidates.
I found no solution from these links either:
https://developer.apple.com/documentation/os/logging
https://developer.apple.com/videos/play/wwdc2016/721/
Because you forgot to
import os
at the start of this file.

Using new features while supporting older iOS versions

I am developing an app using SDK 8.1, Apple LLVM 6.0 and Xcode 6.1.1. The deployment target is 6.0. I'm using NSOperationQueue and I want to use QoS whenever it's available.
The code I'm using is:
if ([self.operationQueue respondsToSelector:#selector(setQualityOfService:)]
&& (&NSOperationQualityOfServiceUserInitiated)) {
[self.operationQueue performSelector:#selector(setQualityOfService:) withObject: NSOperationQualityOfServiceUserInitiated];
} else {
//Other stuff not related to the scope of this question
}
The error I get is:
Use of undeclared identifier 'NSOperationQualityOfServiceUserInitiated'
I added the if (&NSOperationQualityOfServiceUserInitiated) part to check if this constant exists. This code worked with older versions of Xcode/Obj-C Compiler.
I am able to use selectors with performSelectorWithIdentifier but what about constants that do not have a defined value in the docs? The value of this constant is set by NSQualityOfServiceUserInitiated but there is no definition for this value that can be hardcoded.
How do I fix that?
There are several things wrong with the code.
NSOperationQualityOfServiceUserInitiated is a native type (NSInteger) so you can't use it the way that you are in either line.
The qualityOfService is a property of type NSQualityOfService. Your attempt to pass an argument to the qualityOfService method (getter method) makes no sense. If you are trying to set the quality of service, you need to call the setter but you can't use performSelector.
You want:
if ([self.operationQueue respondsToSelector:#selector(qualityOfService)]) {
self.operationQueue.qualityOfService = NSOperationQualityOfServiceUserInitiated;
} else {
//Other stuff not related to the scope of this question
}
This code will compile fine as long as your Base SDK is iOS 8.0 or later. The Deployment Target doesn't matter.
If you also want to build this code with Xcode 5 or earlier (a Base SDK of iOS 7 or earlier) then you need to wrap the code with the proper compiler directives to check for the Base SDK.

unable to execute command: Segmentation fault: 11 swift frontend command failed due to signal (use -v to see invocation)

I have an iOS swift program that compiles and runs fine on Xcode Beta2. When I downloaded beta4, I got a few syntax errors for the new swift language which I corrected. I now get this error:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
The problem is that it does not tell me where this error is so that I can further troubleshoot it. Where can I type -v in order to "see the invocation" and troubleshoot further? Without this, there is absolute no way to figure out the problem. Thanks in advance.
Here's how I was able to find out what the problem was:
Click on the issue in the issue navigator (⌘ + 4, then click on the line with the red ! at the start)
At the bottom of the file that appears, there should be a line that says something like:
1. While emitting IR SIL function #_TToZFC4Down8Resource12getInstancesfMS0_U__FTSS6paramsGVSs10DictionarySSPSs9AnyObject__9onSuccessGSqFGSaQ__T__7onErrorGSqFT5errorCSo7NSError8responseGSqCSo17NSHTTPURLResponse__T___T_ for 'getInstances' at /path/to/file.swift:112:5
The location where your error occurred is at the end of that line. (In this case, on line 112 of file.swift in getInstances).
I was trying to add the PayPal framework to my iOS Project (Xcode 7.2 and Objective C language). When building it did not throw any error, but when I tried to archive the Project and make the IPA, I was getting that error
unable to execute command: Segmentation fault: 11
Screenshot:
After struggling for a long time, I disabled the Bitcode in Project's Target > Build Settings > Enable Bitcode. Now the project can be archived. Please check the following screenshot.
Can't really give a straight solution on this (although I'm sure it's an Apple bug), but I just came across the exact same error message and happen to solve it. Here's what I did:
In General
Comment out recently changed Swift code (check commits) until the app compiles again
Command-click each called method in the failing line and check if there could be an ambiguity
My Example
In my case (I was using the XMPPFramework written in Objective-C) the failing code looked like this:
for roomMessage: XMPPRoomMessage in self.messages {
let slices = split(roomMessage.nickname(), { $0 == "_" }, allowEmptySlices: false)
}
Once I replaced roomMessage.nickname() with "0_test" the code didn't fail any more. So I command-clicked the method nickname() (twice) and here's what I saw:
My guess was that the Swift 1.1 compiler has problems with figuring out which method to call if the exact type of an object is not clear. So I made the type of roomMessage explicit and got another error which I fixed by removing the braces behind the nickname() method call. This made my app build again. Here's the working code:
for roomMessage: XMPPRoomMessageCoreDataStorageObject in self.messages {
let slices = split(roomMessage.nickname, { $0 == "_" }, allowEmptySlices: false)
}
I hope this helps someone out there to investigate the issue more quickly than I did.
I also had the same problem,
when I cleaned the derived data
Remove all removed derived data from Trash as well.
Stop Xcode, restart it and clean build
It should be fixed now.
In my case this error because I use Class name for variable
var MYClass : MYClass {
get {
return.....
}
}
And this fixes my problem
var myClass : MYClass {
get {
return.....
}
}
My problem was that I tried to mimic static variables with the so-called module approach (the Module design pattern). So, I had something like that (just a simple static reference to an operation queue declared at the level of a swift file):
let globalQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.suspended = false
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
So, that worked fine in Xcode 6.x.x, but ceased to compile in Xcode 7beta. Just want you guys to be aware of it.
P.S. In general, I managed to find out what was wrong from the logs (see the screenshot attached). Hope this saves you some time.
I got Segmentation fault when I called a protocol function the same protocols extension.
I had a code something in the line with this:
protocol Rotatable {
func rotate() -> Self
}
extension Rotatable {
func rotate(steps: Int) {
for _ 0..<steps { self.rotate() }
}
}
When I later made an object and declared that it would follow the Rotatable protocol I got Segmentation fault 11 and the program crashed.
Ex: this would cause Segmentation fault and crash Xcode
struct SomeStruct : Rotatable {
}
If I however first implemented the function rotate() in SomeStruct and then afterwards declared that it conformed to Rotatable there where no problem.
I had a similar today and tried the steps described here including removing files I had recently modified. Nothing seemed to work. I tried something that had been suggested when SourceKit would crash in Xcode.
I when into the derived data directory and deleted everything. The location is listed under "Preferences -> Locations -> Derived Data" There is an arrow icon right next to the path which opens finder with that directory selected. Select all the directories inside and delete them. Close Xcode and Reopen it. That made the problem disappear for me.
I think that some intermediate file is getting corrupted and the compiler does not know how to handle it.
I get this error because a silly mistake!!
in a class I defined
var url: String!?
:)
So it seems that this description is a multiple & generic error for a lot of reasons!!
This can happen as well if you are porting Objective-C code to Swift and you move an objective C protocol to swift. If you leave off the #objc at the protocol definition and you still have Objective-C code that uses that protocol you can get this error.
The solution in that case is adding #objc to the protocol
protocol MyPortedProtocol {}
changes to
#obcj protocol MyPortedProtocol {}
Also make sure any classes that implement this protocol add #objc to the methods
I did answer in "Swift compiler segmentation fault when building"
I had this error too, and i fixed like this:
check your project and find out which files are using twice and remove one, or delete all and re-add them.
Errors in my xCode
:0: error: filename "AttributedString.swift" used twice: '/Users/.../CNJOB/CNJOB/AttributedString.swift' and '/Users/.../CNJOB/CNJOB/AttributedString.swift'
:0: note: filenames are used to distinguish private declarations with the same name
:0: error: filename "APIClient.swift" used twice: '/Users/.../CNJOB/CNJOB/APIClient.swift' and '/Users/.../CNJOB/CNJOB/APIClient.swift'
:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode 3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
For me it's caused by adding the swift files to different targets (today extension in my case).
I forgot to add one #end after #implementation in a .m file that had multiple classes in it. Something like:
#implementation Adjust
#end
#implementation Data //#end For this class was missing
#implementation Create
#end
I got this bug because of line
self.textView.inputAccessoryView = self.toolbarItems;
If you delete it the error will gone.
My steps:
1)
Deleted Derived data
Cleared build folder Didn't help
Copied class files to another folder as backup and commented everything in this class. Error gone.
Commented code blocks one by one until
build was success.
For me the problem was mixing Generics, Extensions, and #objc.
It turns out Xcode doesn't like having #objc inside extensions of generic classes:
class FaultyClass<T: TypeValidator>: UIControl where T.ItemType == String {
}
extension FaultyClass: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
The above code gives the error #objc is not supported within extensions of generic classes. So I moved the method to the class itself but didn't delete the empty extension. This got rid of the error but when I compiled the project I got the segmentation fault.
The solution was to move UITextFieldDelegate to the class declaration.
class GoodClass: <T: TypeValidator>: UIControl, UITextFieldDelegate where T.ItemType == String {
// MARK: - TextFieldDelegate
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
My problem was in methods signatures:
func setCategory(categoryId: Int?, subcategoryId: Int?) -> FilterSettings {
func changeCategory(categoryId: Int?, subcategoryId: Int?, handler: #escaping (Int) -> ()) {
I don't get why compiler cannot handle such declarations.
In my case it was because of an inappropriate inout in the function parameters. So I suggest you to look for that as well.
For me it was something similar to what #LuisCien described in this answer https://stackoverflow.com/a/42803582/4075379
I didn't have any generics or #objc tags, but it was these lines of code that were causing the segmentation fault:
public extension CGFloat {
/// Whether this number is between `other - tolerance` and `other + tolerance`
func isEqual(to other: CGFloat, tolerance: CGFloat) -> Bool {
return (other - tolerance...other + tolerance).contains(self)
}
}
i.e. an extension on a primarily Objective-C primary type?
Very luckily, I was able to delete those lines because the project wasn't using anymore. That fixed the issue.
Dumb mistake. I referred to self in a Class method:
public class func FunctionName() -> UIImage {
let bundle = Bundle.init(for: type(of: self))
...
}
I run into this problem when building some legacy code whaich was not adapted for latest Swift versions.
Segmentation fault: 11
When you open Report navigator it contains some context like:
1. Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
2. While evaluating request IRGenSourceFileRequest(IR Generation for file "/Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift")
3. While emitting IR SIL function "#$s20NSURLProtocolExample11AppDelegateC11applicationAD29didFinishLaunchingWithOptionsSbSo13UIApplicationC_So12NSDictionaryCSgtF".
for 'application(application:didFinishLaunchingWithOptions:)' (at /Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift:17:3)
0 swift 0x000000010b2d3615 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1 swift 0x000000010b2d2615 llvm::sys::RunSignalHandlers() + 85
2 swift 0x000000010b2d3bcf SignalHandler(int) + 111
3 libsystem_platform.dylib 0x00007fff2039bd7d _sigtramp + 29
...
To solve this issue:
comment the pointed line (line 17 in AppDelegate.swift)
Build and fix all others issues
uncomment line from step 1
Swift 5 Very Easy And Smooth Solution
1- Just check your last added Extension / Code / Folder File before then this issue occur
2- Just Commit the code or save that code
3- Clean and Build & DONE :-)
Happy Coding
I ran into a similar problem when switching from beta2 to beta4.
Clean
then
Build

Objective-C compiler is leaving out a protocol definition

I'm writing a couple classes that make use of the Objective-C runtime library. This includes retrieving Protocol definitions at runtime based on their name. However, it appears that Protocols that are not explicitly adopted by a class or referenced in code using #protocol(ProtocolName) are excluded from compilation and not available at runtime.
Example:
#protocol MyProtocol <NSObject>
-(void)doSomething;
#end
//Somewhere else in code
Protocol *protocol = NSProtocolFromString(#"MyProtocol");
// ^ value of "protocol" will be nil when I run the application!
//However, if I use do the following:
Protocol *whyDoIHaveToDoThis = #protocol(MyProtocol);
Protocol *protocol = NSProtocolFromString(#"MyProtocol");
// ^ value of "protocol" will now be a pointer as expected when I run the application!
Does anyone know why this is, and even better, how to force the compiler to include Protocol definitions that are not in use at compile time, but which I will later want available at runtime?
You can force the compiler to include the protocol by making a dummy method that's not called that uses it. I've done this before:
void preserveProtocolFromBeingTrimmed()
{
(void)#protocol(BrightnessProtocol);
}
I see that Apple uses this in their FxBrightness plug-in from the FxPlug SDK.

Resources