Reprint:Multi-paradigm programming language-an example of Swift

The original from InfoQ,Author Guo Lin

Based on the Swift case study of language,Introduction what is a multi-paradigm programming language;Also introduces several of today's more popular programming paradigm,Worth a read。Collection,Original linkIn this

Swift programming paradigm

Programming paradigm is the idea behind the program language。Representing programming language designers believe that how the program should be built and implemented。Common programming paradigm:Procedural、Object-Oriented、Functional、Generic programming。

Some programming language is designed for a particular design paradigm,E.g,CyesProcedural programming languageSmalltalkandJavaIt is a more pureObject-OrientedProgramming language;Haskell、Scheme、Clojure isFunctional ProgrammingLanguage。

Other programming languages ​​and programming paradigms relationship does not correspond,As Python、Scala、Groovy supports both object-oriented and functional programming to some extent。Swift also supports multiple programming paradigms of programming languages。

Since the representative of the thinking behind the language,Programming paradigm largely determines what language will be presented to the face。Do not need in-depth study,Just browse the code,Scala can be found and is very similar to Swift,This is because they support the programming paradigm is similar;Scheme and Swift looks very different,This is because they support very different programming paradigm。For the purposes of understanding a programming language,With respect to the grammar and writing experience language,Understand language programming paradigm is more important。because,Like reading a book,On pondering how words,How to build a chapter is very important,But more important is to understand the book thought to express。

Swift is to support object-oriented programming paradigm,Also supports functional programming paradigm,Also supports generic programming。Swift supports multiple programming paradigms is determined by its goals。Swift to create the original intention is to provide a practical industrial language。Unlike Haskell by universities and research institutions such programming language has academic nature。When Apple launched the Swift took a clear business purpose:Mac OS and iOS system's main programming language Objective-C has been significantly old state,Swift will make Apple systems developers have a more modern programming languages,Thereby contributing to the sound development of the whole Apple ecosystem。

Swift's design and development of all reflect "Practical industrial language"This goal。This determines the Swift can not do extreme language experiment,It needs to talk sense to the reality on the basis of,Prudent to seek a breakthrough。This determines the need to inherit Swift heritage,In reality care needs based on the now most programmers,Be developed for the future。

Object-Oriented

Core concepts of object-oriented programming is inheritance,Polymorphism,And packaging。Construction of the base unit to the object program object-oriented programming languages,Inheritance provides a way to reuse the code;Polymorphism provides a higher abstraction,So that we can design a more generic program;A code package provides more convenient and safe mechanism uses。Swift has all of the above object-oriented features。so,Swift is a complete object-oriented programming language。

Swift inherits the Objective-C object-oriented aspects of the main features,Provide class-based encapsulation and inheritance mechanism。But given the structure (Struct) And enumerations (Enum) Richer object-oriented features,So that they can be used to encapsulate more complex objects。Other,With respect to the Objective-C,Swift is a more secure language。

Single inheritance,Multi-protocol

In succession,Swift Unlike C ++ can inherit one or several classes,And similar to Objective-C and Java,Only single inheritance。But Swift can implement multiple protocols (Java is the corresponding interfaces Interface)。This does not make up for the limitations of multiple inheritance to some extent,,While avoiding multiple inheritance is difficult to control defects。

In addition to implementing protocol,Swift also allows multiple extensions (Extension)。It is an extension to an existing class,The method of enumeration or structure to add new features。Expansion and Objective-C in the classification (Category) similar,But with Objective-C is different from the classification,Swift Extended no name。

More powerful structure,enumerate

C ++ and Java, and most other object-oriented programming language mainly class (Class) as object-oriented basic structure。Swift is given structure (Struct) and enumeration (Enum) more object-oriented features,Making structures, and enumerations are also able to take part of the data package work。In some other languages ​​we need to resolve class scene,Swift can use the structure and enumerated types,And more appropriate。E.g,Swift's Array and Dictionary is the structure realization,Rather than class implements,This differs from most programming languages。

Swift structures and enumerations, like classes,,Complete the following things:

  • Defined attributes
  • Definition method
  • It has constructors
  • Can be extended (Extension)
  • You can abide by the agreement (Protocol)

At this point the package,Structures, and enumerations are almost exactly the same class。Different places,Structures, and enumerations are inherited or not inherited。so,Both types of data there is no polymorphism。

in conclusion,Like Swift classes and other object-oriented programming language class is the core concepts of object-oriented languages,It has object-oriented basic features。Swift structures and enumerations have more than any other object-oriented features of object-oriented programming language,You can encapsulate more complex objects。But can not be inherited,There will be no polymorphism。

More value type,Rather than a reference type

Structure,Another difference is the enumeration class:Structures, and enumerations are value types,The class is a reference type。

Type and value of the assignment is passed as an argument when,Actually is copied,Operation is a copy of an object。Swift has a lot of value types,Including Number,String,Array,Dictionary,Tuple,Struct and Enum, etc.。

Reference types and the assignment is passed as an argument when,The object is passed by reference,The object is not a copy。These references point to the same instance。References to these operations,It will affect the same instance。

Swift scores in the region and reference types for variable objects and immutable data to distinguish。Mutable,Using a reference type;Immutable data,Use value type。Value type of data,Can guarantee you will not be accidentally modified。Value type of data passed to the function,Internal functions can be freely copied,Change the value,Without fear of side effects。In a multithreaded environment,Multiple threads running simultaneously,An unexpected error may modify data,This can often be a difficult to debug bug。The use of value types,You can safely pass data between threads,Because the value type is passed is a copy,There is no need to synchronize data between threads Change。This can guarantee the security of the code thread environment。

Struct is a value type,It implies that the structure should primarily be used to encapsulate data。E.g,Three-dimensional coordinate system point Point,Representative geometry size Size, etc.。The class is a reference type,Means for enclosing class should have the status of,Objects can inherit。E.g,people,Animals, etc.。

Swift中,Array、Dictionary、String value type,They behave like the C language, like Int。You can be as simple as using Int safely use Array,Regardless deep copy like annoying problem。Swift enhanced support for value types,We encourage the use of value types。Because the value of the type more secure。Greater use of value types,It will help us write more predictable behavior,More secure code。

Safer language

Type-safe language

Swift is a strongly typed language,This means that the wrong type of parameters Swift prohibiting further operation。E.g,You can not let String and Float sum。This is consistent with C # and Java;The C and Javascript such a weakly typed language is not the same。

Swift is a statically typed language,This means that the variable is Swift at compile time type checking。Compile time,The compiler will try to find related errors include wrong type, including。E.g,String and Int adding this type of operation errors,The compiler at compile time can tell you,Without error when run。This is consistent with C # and Java;And with Python and Ruby is not the same kind of dynamically typed language。

Swift does not allow the incorrect type of operation or the type of conversion takes place,So Swift is type-safe。

Swift supports type inference,And there is a very good type inference device。In most cases,You do not have to declare the type of,The compiler can you derive variables as context type。

Initialization process safety

Swift class (including structures, and enumerations) initialization process is similar to the design of Java。Swift has a particular class method,As initialization method,They do not func prefix,But in the init method name。This differs from the Objective-C initialization method is a common way。For the initialization method can guarantee special treatment in the language mechanism initialization method is called only once。This mechanism is in Objective-C does not exist,In Objective-C,,Initialization method just like any other regular method,It can be called multiple times。

Swift initialize method must ensure that all the instance variables are initialized。Swift initialization method requires special initialization sequence。First ensure that the current class instance variables are initialized,Initialization method before calling the parent class to complete the parent class instance variable initialization。

Swift ensure the initialization method is called only once,And all instance variables are initialized。This makes the Swift initialization process is secure。

Security rewrite

Swift provides a rewritten (Overriding) protection mechanisms。If you want to override the base class methods,We must add a keyword before the override method overriding subclass。To do so is to declare to the compiler that you want to provide a rewritten version。The compiler will confirm,Whether the method has the same method as defined in the presence of base class。in case,The base class is not defined in the same manner,The compiler will error。on the other hand,If you do not add keywords to define a method of overriding the base class methods and the same,The compiler also being given,To prevent accidental rewrite behavior。This will rewrite behavior in two ways to ensure the correctness of。

Optionals

Swift in Optionals allows us to respond more safely may exist,There may not exist a value of。In Objective-C where we mainly rely on documentation to find out whether an API will return nil。Optionals Let this responsibility is given to the type of system。If the API return value declared as Optional,It means that it may be nil。If it is not Optional,It means that it is impossible to nil。

In Swift,Type a question mark followed by a statement Optional Type,And exclamation mark!Optional type of unpacking just syntactic sugar。Optionals actually realized by the enumeration:

 

That is,Optional In fact, an enumeration type。Through the language type system to clear the case may be nil。This document than using Objective-C will be described in much safer。

Object-oriented programming summary

Now the vast majority of programmers working language is object-oriented programming language is still。Most popular modern programming languages ​​will allow you to create objects。Object-oriented programming language is easy modeling。because,Objects and classes seem easy and real-world things and concepts correspond。But practice shows that programming,Anything not become the object of a good thing。For a bad example in Java:Only Java objects passed as a parameter to a function (of course, primitive Primitive Type),Therefore, in order to function is passed as a parameter to another function,You need to be wrapped in a function object,Typically use an anonymous class (which is also in Java,Listener Listener usual implementation),And this class will not have other effects,Everything is just to satisfy Java object design,So that by the compiler。

Java has a pure object-oriented concepts。It is designed from the ground,We hope everything is subject to a pure object model to model for the world。But the development up to now,Java added more and more non-object thing。Introducing closures,Thereby obtaining a function of a programming function;The introduction of generics,Thereby obtaining a parameterized type。This may imply,The world is so colorful,Use a single model for the modeling world and will not succeed。

Swift unity in the pursuit of pure programming paradigm on this point is not stubborn。Swift fully supports object-oriented programming,It has a complete object-oriented basic concepts。This enables programmers to learn and be familiar with the cost of using the Swift object-oriented programming is reduced。Java or Objective-C programmers for many of the concepts Swift will feel very familiar。For them,Swift is not difficult to learn,Swift will soon be able to put into actual production。

The same time,Swift also supports certain extent, functional programming style。In functional programming scenario for,At the same time the programmer also has functional programming and thinking ability,You can use Swift to functional programming methods to improve productivity。This will be described in detail in the next chapter。

Functional Programming

Functional programming is a mathematical function modeling of the core programming language programming paradigm。It will be seen as calculated in computing mathematical functions,And avoids state and mutable object using a program。Functional programming There are two main ideas:

  • The core to function as a programming language modeling
  • State and avoid variability

Function is the cornerstone of functional programming。Functional programming language code that is a combination of functions from。The process of writing a functional language is a function of the design process。Large-scale program consists of thousands of function composition,To effectively combining these functions。Functional programming languages,Try to avoid state,Avoid variable objects。No mutable state,So that it functions in a functional language becomes a pure function。Modular pure function more easily,Easier to understand,For multiplexing friendly。

function

The core functional programming is a function,Function is a "first class citizen"。It's like the main abstract method is a class object-oriented language,The main functional programming languages ​​abstract method is a function of。All features of Swift functions has a function of functional languages。You can easily use Swift to write functional style code。

Higher-order functions,A function

Higher-order functions,Refers to a function may be a function of other parameters or return results。

A function,Further extends the use of the function,So that the function as the language of the "first class citizen"。This means that the function can appear anywhere in the emergence of other language constructs (such as variables)。It can be said,A higher-order function is a function of more stringent。

Swift function is a function of,Of course, all higher-order functions。

A Java cited hereinbefore in order to function as a parameter passed to another function,Examples of poor function needs to be wrapped in an extra class anonymous。Swift function is a function,Function may be passed directly to another function as a parameter。This avoids this extra anonymous class in Java appears。

Closure

Will be a function closure within it all the variables cited implicit binding。Also known as,Closures are referenced entity by a combination of function and environment associated therewith formed。 function is actually a special kind of closure。

Objective-C in the latter part of the added support for closures。It is a function of a closure。By supporting closure,Objective-C to expand their language skills。But if the closure syntax compared to Swift,Objective-C's closure will be a bit heavy complex。 The following example shows the simplicity and elegance of language Swift closures:

 

This embodiment,The map function iterates through the array,Processing all elements of the array used as a parameter to be passed closure,And returns a new array treated。Examples can be seen in,Swift used {}To create an anonymous closure。use inTo partition parameter and return type。In many cases,Because of type inference,Type declaration can be omitted。

Invariance

Swift before the introduction of invariance,The door to discuss Haskell pure functional languages。This will help us to gain a deeper understanding of invariance。

Briefly,Haskell no variables。This is because,Haskell pursuit of a higher level of abstraction,The variable is actually a class of low-level computer hardware:Memory space (registers,Memory) abstract。Reason for the existence of variables,It can be regarded as the remains of a computer language evolution,For example, at the beginning of the hardware directly in assembly language,Variables need to operate a stored procedure。Before the emergence of the computer,Solve mathematical problems are constructed around mathematical functions。Mathematics,Variables computer language that there is no need to repeat the assignment。

Haskell based on a more abstract mathematical model。Use the Haskell just focus on mapping the relationship between design data。And on the math,Represent an entity relationship between the two data mapping function is。This makes the process of writing Haskell code and design are consistent mathematical functions,Haskell programmer's ideas are closer to the essence of mathematics。Haskell abandoned the variables at the same time,Also abandoned the cycle control。This is because there is no variable,There will be no loop position control loop variable。It is also well understood。Recall that in our mathematics curriculum before learning computer,There is no need to use for this type of concept。We still use the function to process a sequence to another sequence of conversion。

Another result invariance,Is pure function。No mutable state,No variable objects,So that it functions in a functional language becomes a pure function。Pure function that is a function without side effects,No matter how many times to perform,The same input means that the same output。The behavior of a pure function does not depend on global variables、Database content or network connection status。Natural pure code is modular:Each function is self-contained,And comes with well-defined interfaces。Pure function has very good characteristics。It means easier to understand,Easier combination,Testing more convenient,Thread safety。

Swift provides a degree of invariance support。In Swift,can use whereCommon variable declaration,You can also use letQuickly and easily declare invariant。

 

Swift distinction <strong>where</strong> and <strong>let</strong> In order to force the compiler to use this distinction。Swift is declared invariant,It must be initialized when they are declared,Or initialize in the constructor。In addition to these two places,Will no longer be invariant change。Swift in encouraging the use of invariants。because,Use invariant easier to write easy to understand,Easy to test,Loosely coupled code。

There are many benefits invariance:

  • Higher level of abstraction。Programmers can think closer to mathematically。
  • Easier to understand the code。Due to the absence of side effects,No matter how many times to perform,The same input means that the same output。Pure function than to understand the functions and objects have mutable state is much easier to simply。You no longer need to worry about changing the status of an object,It will have a certain behavior (function) have an impact。
  • Thread-safe code。This means that a multithreaded environment,Run the code no synchronization problems。They could not because of the exception and in unpredictable state。

Unlike Haskell this purely functional programming language can not Shen Ming variables,Swift offers variable and non-variable two kinds of ways Shen Ming。Programmers are free to choose:When using object-oriented programming paradigm,You can use variables。In case of need,Swift also provide support invariance。

Lazy evaluation

Calculating a characteristic is an inert functional programming languages。After calculation of the expression is not an inert it is bound to variables evaluated immediately,But when the evaluation value is drawn down。

Lazy evaluation has the following advantages:

  • First of all,You can use them to create such a data type infinite sequence。Because the value will be calculated until needed,This set can be used an inert analog infinite sequence。
  • second,Reduces storage space。Because the calculation will occur when really needed。so,Saving unnecessary storage space。
  • third,Reduce the amount of calculation,Generating more efficient code。Because the calculation will occur when really needed。so,Saving the portion not used to calculate the time value。E.g,Looking for the first value in the array meet a certain criteria。After finding a,Array value after the value may be necessary to calculate the。

Pure functional programming language,Haskell is performed as the default lazy evaluation。so,Haskell is known as a lazy language。Most programming languages ​​such as Java、C ++ is a rigorous evaluation,Or is eager evaluation。Swift default is strict evaluation,That is, every expression need to be evaluated,Regardless of whether this expression in practice does need to be evaluated。but,Swift also provides syntax support lazy evaluation。Inert when needed,We need to explicitly declare。This provides the conditions for developers to use in inert Swift。

The following example shows the default values ​​of the array is strictly required sequence becomes inactive:

 

The following results were obtained:

 

The results showed an inert sequence seq。Its value is only calculated when needed will really happen。

Functional Programming summary

Functional programming languages ​​are not the young,It is as old as history and object-oriented programming。1958Was created in Lisp is the oldest functional programming language。It's older than the C language。But until recently,Functional programming ideas gradually being taken seriously。Almost all programming languages ​​are more or less new-fangled affected functional programming ideas。Python、Scala、Groovy、Swift has a function,Closure。So that you can function directly to another function,Function can also be returned in a return value in the form of another function。Elimination of state,Invariance provide benefits more and more accepted,Scala、Groovy、Swift provides declare immutable object methods,To support the preparation of more close to functional style code。

Functional programming languages ​​have their good place,Maybe in the future it will become an important programming paradigm。but,The importance of functional programming may be more indirectly reflected in the influence of other programming language development。future,It may be difficult to emerge a mainstream programming language mainly in the functional programming paradigm design。As such a single Java programming paradigm (object-oriented) Construction,The mainstream programming language of opportunity should not be too much。Haskell such as the pursuit of a purely functional programming language,More likely just a partial academic language test。

Let me repeat once again on the grounds mentioned in a:The world is so colorful,The use of a single model for the modeling world and may not be successful。of course,Such predictions often be broken。in case,Future computer field appeared to solve all the problems of the unity paradigm,I will be happy to learn and discuss it again。But if only discuss the state of the case,We still have to face a world of division and compromise。

Swift is not a language mainly in the functional programming paradigm built,It is more of a blend of functional programming learn some good ideas (even more flexible and powerful function,Invariance advantage)。In most scenarios under Swift,The main features still appear to object-oriented programming language。because,As another door successor object oriented programming language of Objective-C,Swift needs to inherit the Objective-C:Cocoa。We now write the code Swift,Most of the time or on the Cocoa framework,Cocoa can be said that Swift's standard library。In a major framework to object-oriented language in writing code,The most appropriate way of thinking will continue to be object-oriented。Cocoa can be said to be the starting point basis Swift departure,It can be said impede its occurrence tires for bone changes。

Swift support for functional programming,It allows the programmer to select a plurality。Swift does not force the programmer must be an object-oriented way of thinking。Under appropriate circumstances Scene,Programmers can choose to use functional style writing code。If that is the appropriate scene,It is possible to improve productivity。

Object-oriented and functional programming

in case,We now by language paradigm to popular language classification,It supports object-oriented programming language should be the longest team。Now most popular modern programming languages ​​are object-oriented,They will allow you to create objects。But at the same time,You will find several popular programming languages,Python、Scala even Java are more or less influenced by functional programming languages。They all introduce some functional programming concepts,You can write the code having a functional style to a certain extent。

After getting familiar with the object-oriented programming language class,Then contacting functional programming language,Often feel refreshing,Even feel like a functional language would be good way to salvation。That Should we turn this completely functional programming language? Use Haskell to save the world?

After a large-scale object-oriented programming languages ​​in practice,We do a deeper understanding of their shortcomings (eg,Difficult to write software applications in a multithreaded environment;Code reuse is not a good way to inheritance)。Functional languages ​​does have many advantages,Some advantages just can solve the problem of object-oriented languages ​​(pure function is to adapt to a multi-threaded environment,Pure function is inherently modular,With very friendly to code reuse)。but,Functional programming may also exist some problems。These issues,You may want to come to light after the larger scale industry practice。Now that we have recognized,Pure object-world modeling is difficult。Then the mathematical model for the modeling world may not be good to go。And it is believed that,They have their own respective areas of expertise and the environment。We still can not use some single programming paradigm to solve all the problems。

Larger reality is that many companies have made huge investments in object-oriented programming language,Even now object-oriented programming has exposed some problems,The functional programming and presents a number of advantages to solve these problems,Any prudent person would not,It is impossible to immediately abandon the object-oriented programming,Thorough and comprehensive turned to functional programming languages。

At the same time realistic option is to support object-oriented programming,Provide functional support。Such,In most parts of the object-oriented capability,You can still use the object-oriented approach。And in place for functional programming,When and you have functional programming and thinking ability,It may also be employed to improve the functional programming methods Productivity。

Swift is such a realistic option。Complete object-oriented support,Swift has inherited the legacy of the Objective-C rich heritage。Swift in the Objective-C objects not complicated。in case,You come across a scene requirements for multi-threaded safety,You need to use the functional style writing this part of the code,It is also very easy in the Swift。

Generic Programming

Generic programming is another interesting topic。Generics provide a higher level of abstraction for programming languages,That parameterized type。in other words,The original is a specific to a type or class of algorithms which types of information abstracted。This abstract concept out in the C ++ STL (Standard Template Library) is the template (Template)。STL shows the power of generic programming,He appeared to become a powerful weapon in C ++。In addition to C ++,C#、Java、Haskell and other programming languages ​​are also introduces a generic concept。

Generic programming is a little partial some concepts,It relates only to how to deal with more abstract type。It is not enough to prop up the core concept of a language。We will not hear a programming language is purely generic programming,And no other programming paradigms。But precisely because generic and does not change the core programming language,So most of the time,It may be well into other programming paradigm。C++、Scala、Haskell these different styles of programming languages ​​support generics。Generic programming provides a higher level of abstraction,This means that more skills。This most programming languages ​​for both adorned with a delicious wine。

In Swift,Generics are widely used,Many Swift standard library is built out by generic code。Such as Swift arrays and dictionaries are generic collection types。Such examples can be seen everywhere in Swift。

Generic function

Swift function supports generics。Generic functions by a function parameter and return value is defined as a generic type,So that the function can be applied to any suitable type。The following shows a simple generic function:

 

Generic type

In addition to the generic function,Swift can also customize the generic class,Generic structure and the generic enumeration。Such generic type can be applied to any type of,Its usage and Array and Dictionary Swift offers the same。

Examples with a stack (Stack) show the definition and use of generic structure。Enumeration and generic definition and use of the same generic class。

 

Generic type parameter T is used in three places:

  • When you create an array of items,Specifies the type of data items can be stored;
  • Specifies the argument types of function push;
  • It specifies a function to pop the return value of type。

Generics agreement

As for the agreement,Swift does not provide a similar structure such as a class or a method to define a generic protocol。But we can use typealias keyword to define the type of association agreement,Such generic protocol can be simulated to some extent the effect of,Examples are as follows:

 

Class implementation of the protocol must be defined as an alias Element The association type。This is similar to the concept of generics,Generics achieve a certain degree of agreement on。

Generic constraints

In generic programming practice,We will encounter some scenes need for further constraints on the generic type。Type constraint specifies a generic type parameter,Or required to implement a specific protocol。such as,`Means that generic parameters refer to the object needs to comply with the agreement Equatable。

Type constraints on generic type parameters to do a certain constraint,May enforce compliance with the generic parameter represents the type of a protocol。And where further statement can be made more detailed requirements of the protocol generic parameter type constraint declared the need to comply with the。where statements can be further constraints on the type of association agreement。such as,Associated with the type of agreement you can comply with the requirements of the two generic parameters they are the same。

Generic Programming summary

Overall,Swift provides a comprehensive generic programming syntax,So that programmers can write higher level of abstraction,More flexible code,In the same time avoiding repeated code,But also has a good type of security。

Summarize

To sum up,Swift is a typicalMulti-paradigm programming language,Supports object-oriented object-oriented programming is to inherit substantial results;Support for functional programming,In order to explore new possibilities;Supports generic programming,It is adorned with a delicious wine。

Swift allows programmers to use object-oriented capability in most of the time,Easily continue to use the object-oriented programming;In a scenario for functional programming,At the same time the programmer also has functional programming and thinking ability,You can also use Swift to functional programming methods to improve productivity;As well as any time a programmer can use generics in Swift,Raise the level of abstraction。

Reference Documents


Original article written by LogStudio:R0uter's Blog » Reprint:Multi-paradigm programming language-an example of Swift

Reproduced Please keep the source and description link:https://www.logcg.com/archives/1045.html

About the Author

R0uter

The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *