Features of the Swift language

Features of the Swift language

The CROC mobile development team shared useful features of the Swift language, which are designed to facilitate and speed up the development process.

Options

In fact, these are containers that either have a value or not – enum with one of two values: nil or any other. These states are designated as Nope and Some, respectively. Accordingly, nil is a valid value, not a crutch, as in Objective-C, and when creating an optional variable, it is assigned by default if no value is specified. They are declared as follows:

var number: Int?

And inside they look like this (link to the source code of the option in the open swift repository: https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift ):

public enum Optional : ExpressibleByNilLiteral {
    case none
    case some(Wrapped)
    public init(_ some: Wrapped)
        ...
    /// Creates an instance initialized with `nil`.
    /// Do not call this initializer directly. It is used by the compiler when you initialize an `Optional` instance with a `nil` literal.
    public init(nilLiteral: ())
        ...
}

Thanks to the options, the Swift language has some cool features that are not in the same Objective-C:

  • All variables at any time in runtime are always defined and initialized. It’s just that if you don’t write a direct initializer, the variable (if it’s an Optional type) is defined as nil, and if it’s not Optional, the compiler won’t let you build the application, because you forgot to initialize this and that. This is because nil is a special kind of value, and you can tell the compiler, “this is an empty variable, so initialize it yourself.”
  • Swift almost never throws a nullpointerexception. The only case when you can run into such a mistake is to try to force unwrap the option in which nil lies.

The guard operator

The guard statement works in much the same way as if, but with one difference: it is triggered when the condition is NOT met.

Guard-constructions are salvation. They allow you to succinctly describe what to do if an error is found — and just forget that this very error may be here. How it looks like:

APIService.getMyData { (data, error) in
guard error == nil else {
Logger.error(error!.description)
return
}
completion(data)
}

Here we are trying to request our data from the API. In the callback of this request, we check whether an error occurred in the process: if yes, then we do return, if not, then we pass the received data to the compliance further.

Wildcard

When a function consists of a single input parameter, it is very long and lazy to write its name in order to pass a variable there. Therefore, you can put an underscore before the parameters that you want to omit when calling the function. This is called a “Wildcard”.

In the wildcard syntax, it will look like this: when you plan to call a function, you can not write the parameter name, but simply put a value. Let’s say we have the following function:

func displayError(error: Error) {
errorLabel.text = error.description
}

If there was no wildcard in the function parameters, the function with the MyError variable, inside of which there is some specific error, would have to be called this way:

displayError(error: myError)

But thanks to wildcard we can write like this:

func displayError(_ error: Error) {
errorLabel.text = error.description
}

And later call the function:

displayError(myerror)

You can also refer to the underlining, re-assign it or transfer it somewhere.

Constants

Another feature of the Swift language is that it does not provide a constant attribute, and the const keyword simply does not exist. Instead, let is used:

let name: String = "Swift"
print(name)

let means that we can assign a value to a variable only once. And then either change something inside it, if it is a reference type, or transfer something from it to another place. And when you try to re-assign something, the compiler will say: “this is not possible, I will not collect it.”

let is often used for class fields and parameters. If a variable is needed in a mutable form— for example, it is a function counter— then it is declared via var. This sometimes confuses beginners — especially those who come from JavaScript, because there is a slightly different relationship between var and let.

Higher order functions

Higher-order functions are similar to lambda expressions in Kotlin (but, strictly speaking, they are not) and do something for each element of the collection to which they are applied.

For example, the map(_:) method is used to transform sequences (Sequence type). It is very concise, you can quickly sort the collection or calculate the sum of the Fibonacci numbers:

let fibonacci = sequence(first: (0, 1), next: { ($1, $0 + $1) })
.prefix(20).map{$0.0}
.filter {$0 % 2 == 0 && $0 < 4000}
print (fibonacci)
// [0, 2, 8, 34, 144, 610, 2584]

Is it readable? Not very. For an unprepared person or someone who writes according to an imperative approach, this can cause difficulties.

Another method – reduce(_:_:) – reduces all elements to a single value:

let NumberSum = numbers.reduce(0) { $0 + $1}
print(NumberSum)

Sometimes reduce(_:_:) is used for very complex things — for example, to count intersections of sets. This is a convenient thing for small tasks — to calculate the sum of an array, find a subarray, sort something.

Access Attributes

In the Swift programming language, “everyone knows everything”: you can access any class and any dependency from any file, if they are open. The only way to do something about it – for example, you don’t want your classes and modules to be accessed by applications from the outside — is to configure access attributes. Swift has six of them:

  • public
  • private
  • protected
  • open
  • closed
  • fileprivate

open and closed are about inheritance. Is it possible to inherit from this class and is it possible to override some fields or methods inside it. If the file is “open”, anyone can inherit from it and overwrite anything inside it. If “closed”, everyone knows about its existence and can do what you allow them. But to inherit from it and override something in it is not.

fileprivate is a very interesting thing. Imagine that you have a class declared in File 1. In File 2, you write extensions for it: add fields, methods, and so on. And mark one of the methods with the fileprivate attribute. Now it will only be available in File 2. And in other files, including File 1, it will not be possible to access it.

In fact, there are many other features in the Swift language — in this article we have tried to list the most basic ones. Share Swift chips in the comments that help you in your work.

Outsourcing Software Development Services | Dedicated Solutions Outsourcing

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png