Is Swift a dynamic or static language?

前端 未结 4 504
生来不讨喜
生来不讨喜 2020-12-15 03:23

I\'m just curious if Swift is dynamic like php or static, I mean can I generate classes while an application is running?

相关标签:
4条回答
  • 2020-12-15 03:58

    Generally you never say static language. You could say static type language or dynamic type language, and you could also say strong type language or not.

    So java is a static type language as well as strong type language, because compiler has no ability to detect type automatically, so it's static, and type is strongly restricted so it's a strong type language as well.

    And javascript is both a dynamic type language and non-strong type language. Because the compiler has ability to detect type during runtime, and type isn't strictly restricted as well.

    So based on above examples, you could say as swift allows us to not declare type and leave to the compiler to detect type by it self, so swift is announced as a dynamic type language by Apple official. And it's also a strong type language for you should use type strictly, when even you haven't declare type, if the compiler detect it to be a String, then it isn't any other type.

    Hope it's helpful.

    0 讨论(0)
  • 2020-12-15 04:08

    It is static - very static. The compiler must have all information about all classes and functions at compile time. You can "extend" an existing class (with an extension), but even then you must define completely at compile time what that extension consists of.

    Objective-C is dynamic, and since, in real life, you will probably be using Swift in the presence of Cocoa, you can use the Objective-C runtime to inject / swizzle methods in a Swift class that is exposed to Objective-C. You can do this even though you are speaking in the Swift language. But Swift itself is static, and in fact is explicitly designed in order to minimize or eliminate the use of Objective-C-type dynamism.

    0 讨论(0)
  • 2020-12-15 04:11

    Swift itself, is statically typed. When used with Cocoa, you get access to the objective-c runtime library which gives you the ability to use dynamic classes, messages and all. This doesn't mean the language itself is dynamically typed. You could do the same with C or any other language that supports a bridge to C by using libobjc.A.dylib.

    0 讨论(0)
  • 2020-12-15 04:11

    Only when you'd like to use objective c library. Swift is inherently static typed. They just give you interface so as you can gradually move to swift.

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