Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swift functional programming is non-variable


May 21, 2021 Swift


Table of contents


Swift functional programming - indesignity

Swift supports functional programming, and this article describes immutable.

Indegeneration

Indesignity is the foundation of functional programming.

Let's start with purely functional languages like Haskell. S imply put, Haskell has no variables. T his is because Haskell pursues a higher level of abstraction, while variables are actually abstractions of a class of low-level computer hardware: memory space (registers, memory). T he reason for the existence of variables can be regarded as a relic of computer language evolution, for example, in assembly languages that initially operated hardware directly, variables were needed to use operational stored procedures. B efore the ad emerging of computers, solving mathematical computational problems revolved around building mathematical functions. In mathematics, there is no such variable in a computer language that requires repeated assignments.

Haskell, on the other hand, is based on a more abstract mathematical model. P rogramming with Haskell simply focuses on mapping between design data. M athematically, an entity that represents a mapping relationship between two data is a function. This makes the process of writing Haskell code consistent with designing mathematical functions, and Haskell programmers' thinking is closer to the nature of mathematics.

Haskell abandoned variables while also abandoning loop control. T his is because there are no variables, and there are no loop variables that control the position of the loop. T hat's understandable, too. R ecall that we didn't need to use concepts like for in our math classes before we learned computers. We also use functions to handle the conversion of one sequence to another.

Swift offers a degree of indignity. I n Swift, objects declared unchanged cannot be changed after their initial construction has been completed. I n other words, the constructor is the only place where you can change the state of an object. If you want to change the value of an object, you can only use the modified value to create a new object.

Indetermination is to reduce or eliminate the state. I n object-oriented programming languages, state is the underlying information for computing. H ow to modify the state in a controlled, Java, Ruby and other programming languages give a number of language mechanisms, such as visibility rating. H owever, because of the large number of variable states, using an object-oriented programming language can be difficult to write highly co-ed, multithreaded code. B ecause, you can't tell if there are sequential errors in many state reads and writes that go in parallel. A nd the mistake is hard to detect. I nsexuality solves this problem. I nverse means that the function has no side effects, and no matter how many times it is executed, the same input means the same output. T hen, there is no annoying synchronization mechanism in a multithreaded environment. All threads can execute code for the same function without scruples.

In object-oriented programming languages such as Java, variables are used to represent the state of the object itself. Swift, as a programming language that supports multiple paradigms, supports variables and also supports the easy affirmability of invariables.

Variables and invaris

In Java, the declaration is invarivaris:

#变量
private string mutable;
#不变量
private final String immutable;

In Scala, the declaration is invarivaris:

#变量
var mutable
#不变量
val immutable = 1

Declare variables and invaris in Swift:

#变量
var mutable
#不变量
let immutable = 1

If an invariate is declared in Swift, it must be initialized at the same time at the time of declaration, or in the constructor. O utside of these two places, you can no longer change invariables. S wift distinguishes var let not only to distinguish between variables and invariables, but also to use compilers to enforce this distinction. D eclaring invariables is encouraged. Because using invariables is easier to write, easier to understand, easier to test, and loosely coupled code.

Immedible class

Because immutability has inherent advantages such as thread security, we also have scenarios when writing object-oriented languages that use invarutable objects. However, because of the different programming paradigms, it is very troublesome to construct immedic classes in object-oriented languages.

In Java's case, if you construct a class into an imm changeable class, you need to do the following:

  • Declare the class as final. T his way the class cannot be inherited. T he behavior of a method that cannot inherit the class and cannot override it. This strategy is used by the String class in Java.

  • All instance variables are declared final. T his way, you must initialize it at the time of affirmation, or in the constructor. Elsewhere, you won't be able to change the instance variable declared final.

  • Provides the appropriate construction process. F or immedic classes, the constructor is the only place where it can be initialized. Therefore, providing a suitable constructor is a necessary condition for practical imm convertible classes.

  • There is no way to change the state other than the constructor. I nstance variables are declared final, but they can't be changed anymore. H owever, you can still change what they point to. Therefore, consider the defense method in the getter method: instead of returning a reference to the content directly, you return a reference to the copied content.

An example of an imm changeable class implemented by Java is as follows:

public final class Person {
    private final String name;
    private final List<String> interests;

    public Person(String name, List<String> interests) {
        this.name = name;
        this.streets = streets;
        this.city = city;
    }

    public String getName() {
        return name;
    }       

    public List<String> getInterests() {
        return Collections.unmodifiableList(interests);
    }
}

Most of the multi-paradigm programming languages with functional properties make it easier to construct invarient classes. Groovy, for @Immutable to indicate immvable classes.

@Immutable
class Preson {
    String name
    String[] interests
}

@Immutable the following features:

  • It is final, i.e. not inheritable;
  • The property automatically owns the private and automatically produces the getter method;
  • Any attempt to change the property will result in a ReadOnlyProperty Exception exception being thrown;
  • Groovy creates the appropriate constructor: an ordered constructor is created, and a mapping-based constructor is created;
  • Collection classes are encapsulated in the appropriate wrapper, and arrays (and other clonable objects) are cloned.
  • The default equals, hashcode, and toString methods are automatically generated.

An example of Swift's approach to implementing an imm changeable class:

struct Person {
    let name:String
    let interests:[String]
}
  • The structure (struct) is final, i.e. it cannot be inherited;
  • let declares the instance variable, which ensures that after class initialization, the instance variable can no longer be changed;
  • struct is a value type that assigns one struct to another variable, but actually copies the pair and assigns the copied object to another variable.

Swift implements an immvable class by struct and declaring all instance variables of that let at the beginning of let. I n the area of immutability, enum has the same characteristics as structures. Therefore, the structure in the example above can also be replaced by enumerate types in the appropriate scenario.

The value type and the reference type

When a value type is passed to a function when it is assigned and as a function argument, it is actually a copy of it. Swift has a number of value types, including numbers, strings, arrays, dictionaries, yuans, enumerations, structures, and so on.

struct PersonStruct {
    var name:String
}

var structPerson = PersonStruct(name:"Totty")
var sameStructPerson = structPerson
sameStructPerson.name = "John"
print(structPerson.name)
print(sameStructPerson.name)

// result:
// "Totty"
// "John"

As you can see, the values of structPerson and SameStructPerson are different. At the time of assignment, sameStructPerson's to is a copy of StructPerson.

An instance (primarily a class) that references a class can have multiple owners. W hen an assignment and as a function argument are passed to a function, it is its reference, not its copy, that operates. T hese references all point to the same instance. Actions on these references affect the same instance.

class PersonClass {
    var name:String
}

var classPerson = PersonClass(name:"Totty")
var sameClassPerson = structPerson
sameClassPerson.name = "John"
print(classPerson.name)
print(sameClassPerson.name)

// result:
// "John"
// "John"

As you can see, the sameClassPerson changes, too, have affected ClassPerson. I n fact, they point to the same instance. This distinction also exists when it is used as a function argument.

The distinction between value types and reference types in Swift is to allow you to distinguish between variable objects and immmmedible data. S wift has increased support for value types, encouraging us to use them. With value types, functions can be freely copied and change values without fear of side effects.

Pure function

Another result of insoxuality is pure function. P ure functions are functions that have no side effects, and no matter how many times they are executed, the same input means the same output. T he behavior of a pure function does not depend on global variables, the contents of the database, or the state of the network connection. P ure code is naturally modular: each function is self-contained and has a well-defined interface. P ure functions have very good properties. It means easier to understand, easier to combine, easier to test, and more thread-safe.

Indegeneration in Objective-C

In Objective-C, Apple's Foundation library offers a number of invarutive classes: NString vs. NSMutableString, NSArray vs. NSMutableArray, and MOREL, among others. I n Objective-C, in most cases, using an invarion class is the default choice. However, there is no simple method of enforcing insofiction in let as let in Swift.

Summarize

Benefits of insexuality:

  • A higher level of abstraction. Programmers can think in a way that is closer to mathematics.

  • Code that is easier to understand. S ince there are no side effects, the same input means the same output no matter how many times it is executed. P ure functions are much easier to understand than functions and objects with variable states. You no longer have to worry about a change in an object's state, which can affect one of its behaviors (functions).

  • Code that is easier to test. E asier-to-understand code, which means testing is easier. T esting exists to check for successful transitions in your code. I n other words, the real purpose of testing is to validate changes, and the more changes you make, the more tests you need to make sure you're doing the right thing. I f you can effectively limit change, mistakes are less likely to occur and fewer places need to be tested. Changes only occur in constructors, so writing unit tests for immedible classes is a simple and enjoyable thing to do.

  • Thread-safe code. T his means that in a multithreaded environment, there is no synchronization problem with running code. Nor can they be in an unpredictable state because of the occurrence of exceptions.

Unlike haskell, a purely functional programming language can only state nonvariables, Swift provides both variable and non-variable claims. T his gives programmers a choice: variables can be used when using the object-oriented programming paradigm. Swift also provides indegenerative support when needed.

Origin: Http://lincode.github.io/Swift-Immutable
Author: Lin Guo