Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix extension functions

Tags:

In Swift it's not necessary to prefix classes anymore as their module acts as the namespace.

What about prefixing extension functions? For example:

extension UIImage {      public func hnk_hasAlpha() -> Bool { ... }  } 

On one hand Swift is not dynamic so collisions would generate compiler errors.

But what happens if compiled code runs in a future iOS/OS X version in which one of my extension methods is added? Would methods in different modules be considered different symbols even if they have the same signature?

Does it make a difference if the extended class is a NSObject subclass or a pure Swift class?

like image 998
hpique Avatar asked Aug 29 '14 11:08

hpique


People also ask

What are extension functions?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.

How do you call a function with an extension?

Example of extension function declaration and its useisExcellent() and call it from the main() function. The declare Student. isExcellent() function is known as extension function, where Student class is known as receiver type. The above example only demonstrates about how to declare an extension function.

How do you access the extension function in Kotlin?

In Kotlin, you can easily call another function by just importing the same in the current Kotlin file where your main function is running. Whatever the function we are declaring in a Kotlin file will be compiled into a static method by default, and it will be placed under the same package.

Can we write extension function inside a class body?

This is done via special declarations called extensions. For example, you can write new functions for a class or an interface from a third-party library that you can't modify. Such functions can be called in the usual way, as if they were methods of the original class. This mechanism is called an extension function.


1 Answers

There's some subtlety here:

Extensions of Objective-C types are implemented as Objective-C categories, with all that implies.

Extensions of Swift types, however, are only in effect where visible due to imports. This means that you can't accidentally stomp on a private system method (whether now or one introduced in the future), and if the system introduces a public method with the same name as yours, you'll get a compile-time failure when you rebuild, but your existing app won't break.

like image 167
Catfish_Man Avatar answered Oct 02 '22 22:10

Catfish_Man