3

In a blog post I have just read:

'Swift allows us to extend classes from NSObject to get Objective-C runtime features for an object. It also allows us to annotate Swift methods with @objc to allow the methods to be used by the Objective-C runtime.'

I don't understand the term objective-C runtime features. Is it meaning that the code could be used in a objective-C project as well?

Lewis Black
  • 917
  • 2
  • 8
  • 22
  • https://developer.apple.com/reference/objectivec/objective_c_runtime, http://nshipster.com/swift-objc-runtime/. – Martin R Mar 07 '17 at 07:55

2 Answers2

2

Quoting the apple docs

The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.A.dylib.

That API is useful primarily for developing bridge layers between Objective-C and other languages, or for low-level debugging. You most likely don't need to use it.

Even when written without a single line of Objective-C code, every Swift app executes inside the Objective-C runtime, so that's why you can access it.

You can do things like swizzling

Papershine
  • 4,593
  • 2
  • 24
  • 44
0

Objective-C Runtime

Swift can use Objective-C Runtime library.

C + extra layer + Objective-C Runtime = Objective-C

It uses similar API with different implementations for different platforms like iOS or MacOS.

[Message dispatch]

It contains:

  • basic structures like class, object, variable, property, method
  • functions for working with these structures
    • Introspection - get/read info about class/object in runtime. For example instance variables, methods names, method arguments. class_getName
    • Reflection - modify its own structure and behavior. For example allocate new class, add variable, add method. class_addMethod
    • objc_msgSend - based on message dispatch
    • Swizzling - swap method realisation in runtime. method_exchangeImplementations. [Objective C], [Swift] swizzling example

Using [@objc vs dynamic] expose Swift's API for Objective-C and adds a dynamic behaviour for Swift code. It is useful when you need something which is not possible to do with usual swift approaches. Good examples are KVO, swizzling...

[KVO]

Objective-C vs Swift

Swift has better performance(based on table dispatch) but Objective-C is more dynamic language[more]

yoAlex5
  • 21,739
  • 5
  • 148
  • 151