Is Swift a Dynamic or Static Language

Is Swift a dynamic or static language?

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.

How do we determine a language is dynamic or static? an example is Swift

  1. I've never heard of the term "static language" or "dynamic language." The usual terms I've heard of are "statically typed language" or "dynamically typed language."

  2. "Dynamic" isn't a defined term in this context, so there's not much to say here.

  3. Polymorphism has multiple different meanings, so I'll assume you mean subtype polymorphism. In that case, yes, dynamic dispatch is necessary. The whole idea is that you want objects of different types to behave in their own way in response to the same message (method call). The only way to do this is to decouple messages and function invocations, so that an appropriate function can be called at runtime depending on the type of the receiver of the message.

  4. Swift is a statically typed language, through and through. This might be obscured a bit by type inference. If you have an expression like

     func someFunction() -> Int { return 123 }
    let x = someFunction()

    The type inference doesn't mean "x has some type that will be figured out at runtime." To the contrary, it means "The type of x can be deduced at runtime because we already know the type of someFunction."

    All types in Swift are known at compile time. In the worst case, a must at least have type Any, which is still a type. It's not a particularly useful type (because there isn't much an Any is guaranteed to be able to do), but it's still a type.

    There is some confusion in that there's talk of types at compile time and runtime types. Here's an example:

         class Car {
    func vroom() { print("vroom") }
    }

    class SportsCar: Car {
    override func vroom() { print("VROOOOOM") }
    }

    let car: Car = SportsCar()

    func driveSportsCar(_: SportsCar) { print("driving") }
    // Compile types are what determine usage compatibility
    driveSportsCar(car) // cannot convert value of type 'Car' to expected argument type 'SportsCar'

    // Runtime types are what determine method implementations
    car.vroom() // => "VROOOOOM"

    In this example, car has a compile time type of Car, and a runtime type of SportsCar. The compile time type determines how it can be used, where it can be passed, etc. For example, you couldn't pass car to a driveSportsCar() function, because even though its runtime type is SportsCar, its compile time type is Car, which isn't compatible.

    The runtime type of an object is what determines the method implementations to be called.

Swift language statically or dynamically dispatched?

Describing C++, Java, and C# as statically dispatched is not particularly accurate. All three languages can and often do use dynamic dispatch.

Swift, similarly, can do both. It does differ from ObjC in that it does not always dynamically dispatch. Methods marked @final can be statically dispatched, as can struct and enum methods. I believe non-final methods can be statically dispatched if the runtime type can be proven at compile time (similar to C++ devirtualization), but I'm not certain about the details there.

Dynamic type casting in swift 4

Swift is pretty much a static language so you can't dynamically change the type. Therefore, we are going to use polymorphism to work around this.

Assuming that State, City and Area all have a name property, you can create an protocol like this:

protocol NamedLocation {
var name: String { get; }
}

And make all three classes conform to the protocol:

extension State: NamedLocation { }
extension City: NamedLocation { }
extension Area: NamedLocation { }

Now you can make your pickerViewItems to be of type [NamedLocation] and you can still access the name property.

What is the difference between statically typed and dynamically typed languages?

Statically typed languages

A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is; other languages (e.g.: Java, C, C++) offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin).

The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.

Examples: C, C++, Java, Rust, Go, Scala

Dynamically typed languages

A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).

Examples: Perl, Ruby, Python, PHP, JavaScript, Erlang

Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.

Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.

Difference between static and dynamic programming languages

Static Typing

Static typing means that types are known and checked for correctness before running your program. This is often done by the language's compiler. For example, the following Java method would cause a compile-error, before you run your program:

public void foo() {
int x = 5;
boolean b = x;
}

Dynamic Typing

Dynamic typing means that types are only known as your program is running. For example, the following Python (3, if it matters) script can be run without problems:

def erroneous():
s = 'cat' - 1

print('hi!')

It will indeed output hi!. But if we call erroneous:

def erroneous():
s = 'cat' - 1

erroneous()
print('hi!')

A TypeError will be raised at run-time when erroneous is called.

Static/Dynamic vs Strong/Weak

  • Static/Dynamic Typing is about when type information is acquired (Either at compile time or at runtime)

  • Strong/Weak Typing is about how strictly types are distinguished (e.g. whether the language tries to do an implicit conversion from strings to numbers).

See the wiki-page for more detailed information.

statically/dynamically typed vs static/dynamic binding

Static and dynamic are jargon words that refer to the point in time at which some programming element is resolved. Static indicates that resolution takes place at the time a program is constructed. Dynamic indicates that resolution takes place at the time a program is run.

Static and Dynamic Typing

Typing refers to changes in program structure that are due to the differences between data values: integers, characters, floating point numbers, strings, objects and so on. These differences can have many effects, for example:

  • memory layout (e.g. 4 bytes for an int, 8 bytes for a double, more for an object)
  • instructions executed (e.g. primitive operations to add small integers, library calls to add large ones)
  • program flow (simple subroutine calling conventions versus hash-dispatch for multi-methods)

Static typing means that the executable form of a program generated at build time will vary depending upon the types of data values found in the program. Dynamic typing means that the generated code will always be the same, irrespective of type -- any differences in execution will be determined at run-time.

Note that few real systems are either purely one or the other, it is just a question of which is the preferred strategy.

Static and Dynamic Binding

Binding refers to the association of names in program text to the storage locations to which they refer. In static binding, this association is predetermined at build time. With dynamic binding, this association is not determined until run-time.

Truly static binding is almost extinct. Earlier assemblers and FORTRAN, for example, would completely precompute the exact memory location of all variables and subroutine locations. This situation did not last long, with the introduction of stack and heap allocation for variables and dynamically-loaded libraries for subroutines.

So one must take some liberty with the definitions. It is the spirit of the concept that counts here: statically bound programs precompute as much as possible about storage layout as is practical in a modern virtual memory, garbage collected, separately compiled application. Dynamically bound programs wait as late as possible.

An example might help. If I attempt to invoke a method MyClass.foo(), a static-binding system will verify at build time that there is a class called MyClass and that class has a method called foo. A dynamic-binding system will wait until run-time to see whether either exists.

Contrasts

The main strength of static strategies is that the program translator is much more aware of the programmer's intent. This makes it easier to:

  • catch many common errors early, during the build phase

  • build refactoring tools

  • incur a significant amount of the computational cost required to determine the executable form of the program only once, at build time

The main strength of dynamic strategies is that they are much easier to implement, meaning that:

  • a working dynamic environment can be created at a fraction of the cost of a static one

  • it is easier to add language features that might be very challenging to check statically

  • it is easier to handle situations that require self-modifying code

Dynamic type languages versus static type languages

The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).

A good take on the issue is from Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages by Erik Meijer and Peter Drayton at Microsoft:

Advocates of static typing argue that
the advantages of static typing
include earlier detection of
programming mistakes (e.g. preventing
adding an integer to a boolean),
better documentation in the form of
type signatures (e.g. incorporating
number and types of arguments when
resolving names), more opportunities
for compiler optimizations (e.g.
replacing virtual calls by direct
calls when the exact type of the
receiver is known statically),
increased runtime efficiency (e.g. not
all values need to carry a dynamic
type), and a better design time
developer experience (e.g. knowing the
type of the receiver, the IDE can
present a drop-down menu of all
applicable members). Static typing
fanatics try to make us believe that
“well-typed programs cannot go wrong”.
While this certainly sounds
impressive, it is a rather vacuous
statement. Static type checking is a
compile-time abstraction of the
runtime behavior of your program, and
hence it is necessarily only partially
sound and incomplete. This means that
programs can still go wrong because of
properties that are not tracked by the
type-checker, and that there are
programs that while they cannot go
wrong cannot be type-checked. The
impulse for making static typing less
partial and more complete causes type
systems to become overly complicated
and exotic as witnessed by concepts
such as “phantom types” [11] and
“wobbly types” [10]. This is like
trying to run a marathon with a ball
and chain tied to your leg and
triumphantly shouting that you nearly
made it even though you bailed out
after the first mile.

Advocates of dynamically typed
languages argue that static typing is
too rigid, and that the softness of
dynamically languages makes them
ideally suited for prototyping systems
with changing or unknown requirements,
or that interact with other systems
that change unpredictably (data and
application integration). Of course,
dynamically typed languages are
indispensable for dealing with truly
dynamic program behavior such as
method interception, dynamic loading,
mobile code, runtime reflection, etc.
In the mother of all papers on
scripting [16], John Ousterhout argues
that statically typed systems
programming languages make code less
reusable, more verbose, not more safe,
and less expressive than dynamically
typed scripting languages. This
argument is parroted literally by many
proponents of dynamically typed
scripting languages. We argue that
this is a fallacy and falls into the
same category as arguing that the
essence of declarative programming is
eliminating assignment. Or as John
Hughes says [8], it is a logical
impossibility to make a language more
powerful by omitting features.
Defending the fact that delaying all
type-checking to runtime is a good
thing, is playing ostrich tactics with
the fact that errors should be caught
as early in the development process as
possible.

Different in dynamic and static version of realm

It is described here: https://realm.io/docs/java/latest/#dynamic-realms

But the main difference is that a DynamicRealm is not type-safe and does not enforce your schema. Everything you are specified using Strings, whic means they are slower and more unsafe than the static Realm that uses the type system. So unless you are dealing with really dynamic data or migrations I would encourage you to stay with the static Realm. That way you get the full benefit of a statically typed language like Java, less bugs and faster code.



Related Topics



Leave a reply



Submit