How are Objective-C factory methods converted to Swift convenience initializers?

Apple's documentation is pretty clear how Objective-C initialization methods are converted to Swift-intializers:

The prefix "init" is truncated and becomes a keyword indicating that this method is an initializer. For init methods that begin with "initWith", "C" is also deleted. The first letter of the selector part, in which "init" or "initWith" is separated from it, becomes lowercase, and this part of the selector is considered as the name of the first argument. The rest of the selector also matches the argument names.

You can also use factory class methods as initializers; however, there is much less information about how these selector names are mapped to Swift functions:

For consistency and simplicity, Objective-C factory methods are displayed as convenience initializers in Swift. This mapping allows them to be used with the same concise, understandable syntax as initializers. For example, if in Objective-C you call this factory method as follows:

OBJECTIVE-C

UIColor *color = [UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:1.0]; 

In Swift, you call it like this:

SWIFT

 let color = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0) 

What are the rules for mapping Objective-C factory methods to Swift initializers?

+7
objective-c swift
source share
1 answer

From what I could figure out just by playing around, the following rules are used to convert factory methods into convenient initializers.

  • List item
  • Method - a class method
  • Return type instancetype or MyClassName *
  • The method takes at least one argument.
  • The method name begins with a "class name suffix"; that is, a class name suffix, with the restriction that you cannot have partial words. The first letter may optionally be lowercase.

The class name suffix (optionally followed by ā€œCā€, as in the initWith transformation) is deleted, and the rest of the method name is used for the first parameter, with the first letter lowercase.

For example, the following conversions apply:

 [MyClassName myClassNameWithObject:obj] → MyClassName(object: obj) [MyClassname classNameWithObject:obj] → MyClassName(object: obj) [MyClassName nameObject:obj] → MyClassName(object: obj) 

Note: since they all map to the same fast initializer, only one will be available (usually the first one declared)

+6
source share

All Articles