Swift

(10 minutes of reading time) Swift is a programming language created by Apple and is increasingly being used. Many developers are already creating or modifying their projects and learning the advantages that this language brings. In today's text we will show the improvements that Swift presents to programmers.

Swift

(10 minutes of reading time)


Swift is a programming language developed by Apple for development on iOS, macOS, watchOS, tvOS, Windows and Linux system. It was developed to maintain compatibility with the Cocoa API and with existing Objective-C code. Swift's compiler uses the LLVM infrastructure and is bundled with Xcode.

In 2014, Swift was announced at WWDC, Apple's annual conference. Starting with version 2.2 in December 2015, it was distributed under the Apache 2.0 license, when Apple made Swift's source code available as an open-source project.

With the opening of the source code, it was possible to use the language in other spheres of development, mainly for web applications, and there were frameworks that help in the development, such as: Vapor, Perfect and Kitura, owned by IBM.

Swift was quickly accepted by iOS developers, and this contributed greatly to the rapid development of the programming language, with new versions being released approximately every five or six months. That's why Swift is among the 20 most popular programming languages on the market

Swift was inspired by languages such as Objective-C, Rust, Haskell, Ruby, Python, C#, among others. It is an alternative to the Objective-C language that employs modern concepts from programming language theory and strives to provide a simpler syntax. In her presentation, she was described as: "Objective-C without the corpulence of C".

In Swift we see key Objective-C concepts such as protocols, closures, and categories, however the syntax is often replaced by cleaner versions and allowing the application of these concepts in other structures of the language.


WHAT IS SWIFT?

Swift is a strongly typed, static and inferred programming language. That is, the values assigned to variables in Swift must be of the same type as the declared variable (strong typing), that a variable's type is checked and set at compile time (static typing), and that variable types can be inferred by the compiler from the values passed at startup (inferred typing).

Variable types in Swift can be optional, this makes development safer, reducing the risk of uncertain behavior caused by missing expected values in certain parts of the program.

Still on the security side, Swift checks that your variables have been initialized before use, forces objects to be initialized so they are never null, checks for overflows in arrays and integers, and automatically manages memory allocation for you.

And to conclude how safe it is, defining constants is super simple, with the let keyword, and defining variables even more, with the var keyword.

You can still find the following items in Swift:

- Unified Closures with function pointers;
- Generic types;
- Tuples;
- Super structs, which support the definition of methods, extensions and protocol implementation;
- Flow control and even more security with guard, defer and repeat keywords.

Swift is also multi-paradigm, supporting development in object-oriented, imperative, concurrent, and functional paradigms.


SWIFT x OBJECTIVE-C

With the emergence of Swift, Objective-C did not cease to exist, today it is considered a very mature and stable language, and Swift was designed from the beginning to be compatible with it. And both are compatible with the Cocoa API and the Cocoa Touch Framework, used in the development of applications for iDevices and Macs.

This framework contains functions that allow developers to draw images and texts on the screen, responding to user interaction. That way, when you hear that you still need to learn Objective-C to make applications for iOS, most mean you need to learn how to use the Cocoa Touch framework and with Swift you have one more way to start using this framework.

In addition, both languages are compatible with the LLVM architecture of compilers, which makes it possible to reuse multiple build tools from one to another.

When comparing Objective-C, which is a language with more than 20 years, Swift brings tools such as Generics and a simpler syntax where with few lines of code the programmer can do more things than he would with Objective-C. Swift closely resembles scripting languages like Ruby and Python, however, it keeps core method calls similar to Objective-C thus making it easy for new and old developers to migrate.

Objective-C translates method calls into an objc_msgSend call. It is responsible for selecting what you want to send and its object, looking for the part of the code that should supposedly handle the events of this method through the method table of the class. This is extremely fast, but sometimes it does much more than necessary. When you declare a MyObject* object, it can be MyObject or a subclass, it can be an instance of a static type, and even an instance of a completely different class. That way, you can lie to the compiler about the type of the object you are sending, and your code will still work.

Unlike Objective-C, in Swift you can't lie to the compiler, the object needs to be more specific, if we instantiate an object of the MyClass class it can be either an instance of MyClass or MySubclass, nothing more. Instead of using objc_msgSend, the Swift compiler emits code that makes a call on a vtable, an array of functions and pointers that is accessed by an index:
callMethod = object->class.vtable[indexOfMethod1]
callMethod()
class MyClass {
        func method1() { print("calling method1") }
        @final func method2() { print("calling method2") }
}

class MySubClass: MyClass {
        override func method1() { print("calling subclass method1") }
}

func TestClass(obj: MyClass) {
        obj.method1()
        obj.method2()
}
SWIFT: ADVANTAGES AND DISADVANTAGES

Swift came to solve the biggest complain of programmers regarding Objective-C: the complicated and difficult to debug syntax, since Swift is easier, concise, and more expressive.

A good example of this can be found in the initial exercise “hello world” in both languages, in the table below:
Despite being easier, Apple makes it very clear that this simplicity does not diminish the power of this language.

It is a fast language, as the name suggests, safe, scalable, with automatic memory management and because it is very easy to read, it also makes it easier for new developers to join the team with the project in progress.

Below we will see some of the main features of Swift.


ACCESS CONTROL

Swift supports six levels of access control with symbols: open, public, internal, fileprivate, and private. Unlike other object-oriented languages, these access controls ignore inheritance hierarchies: private indicates that a symbol is accessible only within the immediate scope, fileprivate indicates that it is only accessible within the file, internal indicates that it is accessible within the scope of the module that contains o, public indicates that it is accessible from any module, and open, only for classes and their methods, indicates that the class can be "subclassed" from outside the module.


TYPE OF VALUES

In many object-oriented languages, objects are internally represented in two parts. The object is stored as a block of data positioned on the heap, while the handle object is represented by a pointer.

Objects are passed between methods by copying the pointer value, allowing anyone with a copy to access the data contained in the heap. In turn, basic types such as integer and floating-point values are represented directly. The handles contain the data, not a pointer, and this data is passed directly to methods by copying. These accessor styles are called pass-by-reference for objects, and pass-by-value for base types.

Similar to C# (if you want to know more about this language, read this text from our blog: C# – Variables and Constants), Swift natively supports objects using both semantics of pass by reference and pass by value. The first one is used for class declaration and the second one for struct.

And speaking of Structs, in Swift it has almost all the same characteristics as classes: methods, implementation protocols and use of extension mechanisms. For this reason, Apple generically named all data as instances, rather than objects or values. However, structs do not allow inheritance.
// Definiton of struct
struct Resolution {
    var width = 0
    var height = 0
}

// Instance Creation
let hd = Resolution(width: 1920, height: 1080)

//  Being "Resolution" a struct, a copy of the instance is created
var cinema = hd
ENUMERATIONS AND PATTERN MATCHING

In Swift, strongly typed enumerations and their variants carry multiple values.

Here are some examples of declaring enumerations and pattern matching:
enum Browser {
    case chrome
    case firefox
    case safari
    case edge
    case ie(UInt8)
}

let browser = Browser.ie(11)
switch browser {
case .chrome:
    fallthrough // .chrome ou .edge
case .edge:
    print("Chromium")
case let .ie(version):
    print("Internet Explorer (version)")
default:
    print("Outro navegador")
}
OPTIONS

An important feature in Swift are optional types, which allow values or references to operate similarly to the common C pattern, where a pointer can reference a value or be null.
let website: String? = "https://www.wikipedia.org"
if website != nil {
    print("Website: (website!)") // `!` desembrulha o valor forçadamente
}

// Alternative form (default)if let addr = website {
    print("Website: (addr)")
}

// Alternative for (guard)
func unwrap(_ website: String?) -> String {
    guard let addr = website else {
        return "" // return
    }
    return addr
}
ERROR HANDLING

Swift has exceptions like Objective-C. Like for example:
enum ValueError: Error {
    case tooSmall
    case tooLarge
}

// Função que pode falhar
func verify(n: Int) throws -> Int {
    guard n >= 4 else {
        throw ValueError.tooSmall
    }

    guard n <= 20 else {
        throw ValueError.tooLarge
    }

    return n
}
And the error handling:
do {
    print("Number:", try verify(n: 3))
    print("Number:", try verify(n: 4))
} catch ValueError.tooSmall { // Captura erro específico
    print("Error: number too small ")
} catch { // Demais erros
    print("Erro")
}
GENERIC

Example of a binary tree in Swift:
// Recursive types need to be declared as `indirect`
indirect enum Tree {
    case empty
    case node(T, Tree, Tree)
}

let tree = Tree.node(5.96, .empty, .node(1.0, .empty, .empty))

// The first member is extracted as a constant; ignore other membersif case let .node(value, _, _) = tree {
    print("(value)")
}

// Members are extracted if the condition is satisfied
if case let .node(value, left, right) = tree, value < 6.0 {
    print("-> (left)")
    print("-> (right)")
}
ITERATORS AND CLOSURES

An iterator, in Swift is represented by the Iterator Protocol; the Sequence protocol provides adapter methods for creating new iterators. It also has a literal to represent ranges (a type of iterator).

In the following example the program lists the prime numbers between 4 and 20:
var numbers: [Int] = [];
// `4...20` é um iterador inclusivo (inclui 20)
for i in 4...20 {
    // `2..
CONCLUSION

With Swift, Apple has enhanced its Xcode development tool by adding a Playground part in which the programmer can easily test their code without having to build or compile. In addition to showing the result immediately, it also shows graphs about the code's performance.

If you're wondering why learn to program in Swift if you don't even have a Mac, here's the best part: you don't need a Mac to learn to program or develop solutions using Swift.

The vast majority of agnostic code editors (eg Atom, VSCode, Sublime etc) already support Swift. Furthermore, you can compile code written in Swift on your Linux, thanks to the language being made available as open source! And if you use Windows, you can too, thanks to Swift's compatibility with the C language, and the extensive collection of C libraries already present on the system that Swift also supports.

In conclusion, Swift is a very safe, clean syntax, very accessible and easy to learn language, whether you are just starting to learn to program or are a veteran with years of experience in other languages.

With it you'll have access to the world of iOS development, through Xcode and the Cocoa Touch Framework, so if that's your goal, learning Swift is a great start!

We at beecrowd offer Swift on our platform, come and practice with us!


Do you like our content? So, follow us on social media to stay on top of innovation and read our blog.
Share this article on your social networks:
Rate this article:
[yasr_visitor_votes size="medium"]

CONTENT

Our Latest Articles

Read about the latest trends in technology
Blog 14-05
Participating in programming competitions is a test not only of technical skills...
NEARSHORE_ LATAM AS THE MAIN DESTINATION FOR THE BEST IT TALENT thumb blog
As we navigate an ever-changing and digitally evolving world, LATAM solidifies itself...

Extra, extra!

Assine nossa newsletter

Fique sempre atualizado com as novidades em tecnologia, transformação digital, mercado de trabalho e oportunidades de carreira

Lorem ipsum dolor sit amet consectetur. Venenatis facilisi.