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

后端 未结 1 519
醉梦人生
醉梦人生 2020-12-16 05:14

Apple\'s documentation is quite clear about how Objective-C initialization methods get converted into Swift intializers:

The “init” prefix gets sliced

相关标签:
1条回答
  • 2020-12-16 05:41

    From what I've been able to figure out just by playing around, the following rules are used to convert factory methods to convenience initializers.

    1. List item
    2. Method is a class method
    3. Return type is instancetype or MyClassName *
    4. Method takes at least one argument
    5. Method name starts with a "class name suffix"; that is, a suffix of the class name, with the restriction that you can't have partial words. The first letter may optionally be lower case.

    The class name suffix (optionally followed by "With" like in the initWith conversion) is stripped off and the rest of the method name is used for the first parameter, with the first letter lower-cased.

    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 those all map to the same swift initializer, only one will be available (generally the first one declared)

    0 讨论(0)
提交回复
热议问题