Swift Extension: same extension function in two Modules

与世无争的帅哥 提交于 2019-11-28 09:00:48
Vasily Bodnarchuk

Details

  • Swift 3, Xcode 8.1
  • Swift 4, Xcode 9.1

Problem

frameworks SwiftFoundation and SwiftKit has the same names of the properties and functions

decision

Way1

Use different names of the properties and functions

// SwiftFoundation
public extension UIView {
    public class func swiftFoundationSomeClassMethod() {
        print("someClassMethod from Swift Foundation")
    }

    public var swiftFoundationSomeProperty: Double {
        print("someProperty from Swift Foundation")
        return 0
    }
}

Way2

Group the properties and functions

// SwiftKit
public extension UIView {
    public class SwiftKit {
        public class func someClassMethod() {
            print("someClassMethod from Swift Kit")
        }

        public var someProperty: Double {
            print("someProperty from Swift Kit")
            return 0
        }
    }

    var SwiftKit:SwiftKit {
        return SwiftKit()
    }
}

Result

import UIKit
import SwiftKit
import SwiftFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = view.SwiftKit.someProperty
        UIView.SwiftKit.someClassMethod()

        _ = view.swiftFoundationSomeProperty
        UIView.swiftFoundationSomeClassMethod()
    }
}

Project

Your method

SwiftFoundation.UIView.swiftFoundationSomeClassMethod()

Your variant of using the namespaces is not correct because all UIView extensions from both frameworks are included in you UIView class. Look at image bellow, you can see SwiftKit class and swiftFoundationSomeClassMethod() inside SwiftFoundation. This can confuse other developers.

If it is an extension of an ObjC NSObject object like UIView then yes the extension method requires a prefix.

However for those who find the underscore unsightly can use this is an alternative technique using Swift protocols to replace the UIColor.red.my_toImage() with UIColor.red.my.toImage() read more about that here Better way to manage swift extensions in your project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!