Created
September 6, 2016 19:57
-
-
Save SpacyRicochet/eff379aba07f995e0b8ec34c3b8a01fa to your computer and use it in GitHub Desktop.
WIP Swift bug report.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
If you construct a Swift NSObject subclass with a designated initialiser that only has default parameters, for example; | |
{code:swift} | |
class SomeClass: NSObject { | |
private let foo: Int! | |
init(foo bar: Int = 1) { | |
foo = bar | |
} | |
} | |
{code} | |
… you can use the initialiser without any parameters, e.g.; | |
{code} | |
SomeClass() // Works fine | |
{code} | |
However, if you then try create this class in an Objective-C file with the `+new` method, you get a fatal error at runtime instead of a compile time error. This; | |
{code} | |
#import <Foundation/Foundation.h> | |
#import "InitTestProject-Swift.h" | |
int main(int argc, const char * argv[]) { | |
@autoreleasepool { | |
// insert code here... | |
NSLog(@"Hello, World!"); | |
[SomeClass new]; // No compiler warning. | |
} | |
return 0; | |
} | |
{code} | |
… results in; | |
{code} | |
fatal error: use of unimplemented initializer 'init()' for class 'InitTestProject.SomeClass' | |
Program ended with exit code: 9 | |
{code} | |
--- | |
`[[SomeClass alloc] init]` gives a compiler warning, which now makes sense. `+new` uses `alloc init` to create new instances and the exact `init()` without _any_ parameters hasn't actually been implemented. | |
However, the intent for creating a designated initialiser with only default parameters if for it to be initialised easily. In Swift this works great (e.g. `SomeClass()`). But in Objective-C, one might want `[[SomeClass alloc] init]` and especially `[SomeClass new]` to also work out of the box. | |
For the implementation, you could check whether the parameters of an NSObject subclass designated initialiser all have defaults, and if so create a convenience initialiser `init()`. That would call the original with all the parameters filled in. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample project: https://github.com/SpacyRicochet/InitTestProject