How to set up smartphones and PCs. Informational portal
  • home
  • Reviews
  • Development How to program with Swift. Making the first application

Development How to program with Swift. Making the first application

Swift is Apple's robust and intuitive programming language that you can use to create apps for iOS, Mac, Apple TV, and Apple Watch. It gives developers unprecedented creative freedom. With this simple, easy-to-use open source language, all you need is an interesting idea to create something incredible.

Developers are already using
amazing features of Swift.

Swift is a fast, efficient, real-time programming language that can be easily inserted into pre-built Objective-C code. Now developers can not only write more reliable and secure code, but also save time and create applications with advanced capabilities.

Great app in Swift. Ease of use and real-time responsiveness is why VSCO chose Swift to create a new version of their iOS photo app.

Excellent applications,
developed in Swift language.

More and more developers are embedding Swift code into their applications. And some even create completely new applications in Swift.

Duolingo Khan
Academy Clear Sky Guide

Procreate Kickstarter Eventbrite Hipmunk

Productivity is higher. The apps are better.

Swift apps exceed expectations. For example, the regular search algorithm runs much faster in Swift.

Up to 2.6 times faster than Objective-C

Up to 8.4 times faster than Python 2.7

10,000 integers were found in the graph using the depth-first search algorithm*

Swift language added
into the curriculum.

It's not just developers who appreciate the potential of the Swift language. Universities and other educational institutions teach Swift in programming classes and publish free courses on iTunes U, meaning even beginners can easily move from basic coding to pro-level programming.

Universities that have included Swift in their curriculum

  • University of California at Santa Cruz
  • Foothill College
  • Royal Melbourne University of Technology
  • Technical University of Munich
  • Lawson Community College
  • Manhattan Community College
  • Mesa Community College
  • Houston Community College
  • Central Piedmont Community College
  • University of Plymouth
  • California State Polytechnic University
  • Stanford University
  • Northwest Kansas Technical College
  • Technological Institute of Monterrey
  • Aberystwyth University
  • Full Sail University
  • Ingesup School
  • Southern Methodist University

Swift is everywhere.
And now it is open to everyone.

Swift is freely available for use by developers, teachers, and students under the Apache 2.0 open source software license. We provide OS X and Linux binaries that allow you to compile code for iOS, OS X, watchOS, tvOS, and Linux. And to accelerate the development of Swift into an even more powerful language, we've created a new community where users can directly contribute to the Swift source code.

Meet Swift.

main book

Download the tutorial Swift programming language from the Apple Books Store for free. Learn how Swift makes programming more convenient, flexible, and fun.

Xcode

Xcode is a Mac application designed for developing other applications for Mac and iOS. Xcode has all the tools you need to create amazing apps. It can be downloaded for free from the Mac App Store.

Developer Website

Get in-depth technical information and a complete overview of the Swift language. Check out the developer blog for the latest news. You also have free access to great resources like tutorials, videos, and code samples.

If you're thinking about which programming language to learn, we recommend paying attention to Swift, and here's why.

1. What is Swift and why was it named so?

Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS, but differs from Objective-C in a wider range of capabilities that were limited to connections with C. In addition, Swift can be called safe because the language is strongly typed: in any moment in time you know exactly what type of object you are working with. Its main advantage is speed: both when working on a project and when launching a finished application. It is for this advantage over other languages ​​(according to the creators, it has absorbed all the best from other programming languages) that it was called Swift (translated as fast).

2. What should you learn, Objective-C or Swift?

This issue has been widely discussed since the introduction of Swift, but as then, there are more arguments in favor of studying it. And Apple itself has made it clear more than once that the future belongs to Swift. At the same time, it can be used in parallel with Objective-C so that there are no problems with different versions. For the same reason, many employers take seriously the fact that someone refuses to learn Objective-C, believing that Swift is still quite raw.

3. Why is Swift faster than other languages? Maybe this isn't true?

Apple boasts that Swift is up to 2.6 times faster than Objective-C and 8.4 times faster than Python 2.7. We think that the question of why you need to care about fast code execution does not arise - and it should be clear that faster code works more efficiently and smoothly, which allows the user to enjoy interacting with the device.

4. I've heard that learning Swift is very easy. Is it so?

We can say that this is true. Swift was designed to make it easy for those new to programming to start creating their own apps, making it incredibly easy to learn to code. Apple compares its brainchild to a scripting language, and programmers compare it to BASIC.

5. So I can just write an application and almost immediately upload it to the App Store?

6. Since everything is so simple, how quickly will I become a professional?

Generally speaking, this is a controversial issue. Swift is constantly improving, so only its creators are the true experts. Even if you've created several great apps yourself and mastered a number of advanced courses and tutorials, you still won't be one of the best, which is why in interviews they say that they are constantly improving, and have not achieved perfection by this point).

Anyway, once you've played around with Swift and gotten a feel for it, figured out whether you like it or not, and started working on real projects, then you can say that you're at least aiming to become a pro. In general, it all depends on you.

7. Still, why was it necessary to create a new language if the old one was working?

Objective-C was once Apple's primary programming language for writing apps, dating back to the days of OS X. But over that time, languages ​​and programming practices have changed a lot, especially in the field of mobile development. Instead of refining the old, Apple decided to go a different route and change the way developers work, making the process more interactive.

8. What about the fact that Swift is not yet fully developed?

Well, it’s not a fact that Apple will finish developing Swift in the coming years, because this would mean killing it. Here, as with any new language, there is a possibility of errors. But everything is constantly updated, because it is in the interests of Apple itself. By the way, Google is already thinking about the possibility of launching Swift applications on Apple, so it still has a long way to go.

9. I once studied programming languages. What is this language like?

Most likely in Ruby or Python. Although you can also learn the syntax from C here.

10. I heard something about cocoa. More?

Cocoa and Cocoa Touch are frameworks that run on OS X and iOS, respectively. Both of them are primarily implemented with Objective-C and integrated with Xcode (if you don't already know, it's a development environment). They consist of libraries, APIs and runtimes. Since Swift is an iOS development language, it also works with Cocoa and Cocoa Touch. If interesting,

Swift is an incredibly powerful and simple programming language introduced by Apple in 2014 that opens the door for many programmers to create apps for iOS, macOS, Apple TV and Apple Watch. This language inherited ideas from Objective-C, Rust, Haskell, Ruby, Python, C# and CLU. It uses secure programming patterns and contains new features to make programming fun and interesting. Created by Chris Lattner, it's a robust, fast, and open language that makes it even easier to create apps for the world's most popular phone.

Swift is a modern programming language with a stable release version that is quite easy to learn, even if you consider that it is your first language. It prevents a lot of errors at the compilation stage, speeds up the development process and improves code quality.

Swift philosophy

The main philosophy of the language is its simplicity, speed and security. The entry threshold has changed significantly compared to Objective C - even without knowing any other programming languages ​​or basics, you can safely start learning the language.

Apple has simplified the language for developers as much as possible: the syntax has become cleaner, which increases the readability of the code for both experienced and novice programmers. The total amount of code has decreased, resulting in increased productivity. All methods that were used in Objective C were completely redesigned, rethought and rewritten. Swift is constantly being developed and updated, which indicates its reliability and focus on the future.

Where is Swift used?

Developers use this programming language to write mobile applications for Apple phones, smartwatches and computers. There was even a rumor that Google wants to transfer Android completely to Swift, anything can happen. This is a universal language that can be used in any platform from the Cupertino company.

Importantly, in the fall of 2016, Apple facilitated the opening of a student learning center where anyone can learn how to program iOS apps. But that's not all; in the states, Swift is already included in the curriculum of many leading educational institutions. This programming language has huge potential.

Swift Learning Difficulty

Swift is a safe language that will protect you from most mistakes in the programming process. It will tell you where the error is and why the program does not compile. But on the other hand, there is strict typing here. Apple's language is unforgiving.

There is currently little documentation available compared to other languages. But this can be explained by the fact that the language was recently released and became an Open Source project, because at the time of release it could only be used by those developers who had an active Apple Developer Program subscription.

Even earlier it could be said that Swift is not very popular and there are a small number of third-party libraries and extensions for it, but now this is completely not the case. There are dozens of excellent solutions from third-party developers on GitHub and the Internet that will help improve your project.

Pros/Cons of Swift

This modern and powerful programming language has a number of advantages that set it apart from others or the same Objective-C. And these are new powerful language features, extremely strict data typing, more concise syntax, significantly higher performance in access operations to collections (sorting and searching), support for a certain majority of modern syntactic constructs existing in other high-level programming languages. And one of the main features of Swift is that it is fully backwards compatible with Objective-C. Thus, this allows you to gradually rewrite projects from one language to another, and also makes it possible to use Objective-C functionality within Swift itself.

One of the nice things is the Playground - this is a kind of interactive sandbox where a developer can write code and immediately see the result of his work. This allows you to increase the speed of writing the main project several times, because writing individual pieces of code or algorithms can now be carried out in the playground with visual feedback, without the risk of making mistakes in the main project.

Apple has reworked a lot of things, giving us a virtually new advanced enumeration system, efficient accessor management, and optimized automatic garbage collection.

The dark side of the language is its low popularity and low prevalence. Most current projects are written in Objective-C and will have to be maintained, and many companies do not rewrite their large projects simply because it is a huge and incredibly time-consuming process.

Related Technologies

Apple has made the transition from using static libraries to dynamic ones and has added this functionality to its programming language, which means it is evolving faster than iOS itself. Now developers can easily present their application along with the libraries they have written. Previously, you had to wait for a new iOS release, but now the situation has changed. Dynamic libraries provide the ability to make improvements and changes to your code more flexible than ever before.

Swift is a more functional and accessible language that, like Objective-C, supports the official Cocoa and Cocoa Touch frameworks. There are many open source projects available on the Internet, including from large companies such as Airbnb, which allow you to use all modern methods and solutions when writing code.

miden16 June 10, 2014 at 01:06 pm

Swift programming language. Russian version

  • Development for iOS,
  • Swift

Hello, Habr! On June 2, we all could see with our own eyes how Apple began to create a revolution in the camp of Objective-C developers by presenting to the world its new programming language - Swift. At the same time, she made available to the public a small documentation on the language, which we decided to translate if there was demand. We present to your attention a translation of the first chapter. If the topic is interesting, we will continue to publish the translation every week.

Language guide
The Basics
Basic Operators
Strings and Characters
Collection Types
Control Flow
Functions
Closures
Enumerations
Classes and Structures
Properties
Methods
Subscripts
Inheritance
Initialization
Deinitialization
Automatic Reference Counting
Optional Chaining
Type Casting
Nested Types
Extensions
Protocols
Generics
Advanced Operators

Language Reference
About the Language Reference
Lexical Structure
Types
Expressions
Statements
Declarations
Attributes
Patterns
Generic Parameters and Arguments
Summary of the Grammar
Trademarks

Welcome to Swift

About the Swift language
Swift is a new programming language for developing iOS and OS X applications that combines the best of C and Objective-C, but without the restrictions imposed for the sake of compatibility with C. Swift uses safe programming patterns and adds modern features that make creating an application in a simpler, more flexible and fun process. Built from scratch by us, Swift is an opportunity to reimagine how apps are developed.

Swift has been in development for several years. The basis of the new programming language was the existing compiler, debugger and frameworks. We've simplified memory management with Automatic Reference Counting (ARC). Our frameworks have also undergone major modernization. Objective-C began to support blocks, literals and modules - all this created favorable conditions for the introduction of modern technologies. It was this preparatory work that served as the foundation for a new programming language that will be used to develop future software products for Apple.

Objective-C developers will find Swift familiar. It combines the readability of named parameters with the power of Objective-C's dynamic object model. It opens up existing Cocoa frameworks and is compatible with code written in Objective-C. Built on this common foundation, the language offers many new features and unifies the procedural and object-oriented aspects of the programming language.

Swift won't scare off novice programmers either. It's the first powerful programming language that's as intuitive and fun as a scripting language. It supports so-called playgrounds, which allow programmers to experiment with code, seeing the result in real time without having to compile and run the application.

Swift incorporates the best of modern languages ​​and is developed taking into account Apple's extensive experience. Our compiler is synonymous with performance, and our language is optimized for development without regard for compromise. It is designed in such a way that you can easily develop your first “hello, world!” application, and even an entire operating system. All this makes Swift an important tool for developers and for Apple itself.

Swift is a fantastic new way to build apps for iOS and OS X, and we'll continue to build on it by adding new functionality and introducing new features. Our goal is ambitious. And we can't wait to see what you can create with it.

Introduction to Swift
According to a long-standing tradition, the first program in a new language should display the words “Hello, world” on the screen. With Swift it's done like this:

Println("Hello, world")
If you've ever developed in C or Objective-C, this syntax should seem eerily familiar to you - in Swift, this line of code is a complete program. You no longer need to import separate libraries to provide basic functionality like console I/O or string manipulation. Code written in the global scope is the entry point to the program, so the main function is no longer needed. Also note that there is no semicolon at the end of each line.

This introduction provides enough information to get started coding in Swift. Don't worry if you don't understand something - we will explain everything in detail in subsequent chapters.

Comment
For a better understanding of the material, we recommend using the playground mode in Xcode. Playground allows you to see the results immediately as you edit your code, without having to compile and run the application.
Simple data types
Use let to create a constant and var to create a variable. The type of the constant does not need to be specified; you can assign a value to it only once.

Var myVariable = 42 myVariable = 50 let myConstant = 42
The types of a constant and a variable must match the types of the corresponding values ​​assigned to them. However, this does not mean that you must specify their type directly. The compiler will automatically determine the type of constant and variable when assigning a value to them. So, in the example above, the compiler will determine that myVariable is an integer type.

If the initializer is missing or does not provide enough information, you can specify the type yourself after the variable, separating the name and type with a colon:

Let implicitInteger = 70 let inplicitDouble = 70.0 let inplicitDouble: Double = 70

Let's experiment
Create a constant with type Float and initialize it with the number 4.

Values ​​are never implicitly converted to another type. If you need to convert a value to another type, do it explicitly:
let label = "The width is " let width = 94 let widthLabel = label + String(width)
Let's experiment
Try removing the explicit conversion to String in the last line. What error will you receive?

An easier way to include values ​​in strings is to enclose the expression in parentheses and precede them with a backslash (\). Example:

Let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit."

Let's experiment
Try using the \() construct and print a string including the result of the sum of two integer variables and someone's name.

When working with arrays and associative arrays (dictionaries), square brackets () are used:

Var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList = "bottle of water" var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations ["Jayne"] = "Public Relations"
To create an empty array or dictionary, use the following syntax:

Let emptyArray = String() let emptyDictionary = Dictionary ()
To create empty arrays and dictionaries, use and [:] respectively—for example, when you assign a new value to a variable or pass an argument to a function.

ShoppingList = // Went shopping and bought everything.

Conditions and cycles
If and switch statements are used to create conditions, and for-in, for, while and do-while statements are used to create loops. In this case, it is not necessary to highlight conditions and initializing expressions with parentheses, while curly braces are required.

Let individualScores = var teamScore = 0 for score in individualScores ( if score > 50 ( teamScore += 3 ) else ( teamScore += 1 ) ) teamScore
The condition inside the if statement must be a boolean, which specifically means that the if score (...) statement is an error because there is no explicit comparison (for example, with zero).

The if statement can be used in conjunction with let and var to work with constants and variables that can have a nil value. Such constants and variables are called optional (that is, they can either take any value or be equal to nil). To create an optional variable or constant, add a question mark (?) after the type.

Var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName ( greeting = "Hello, \(name)" )

Let's experiment
Change optionalName to nil . What do you see on the screen? Add an else block to handle the case where optionalName is nil .

If the optional value is nil , the condition will be false and the code in the curly braces after the if will not be executed. Otherwise, the greeting variable will be assigned a new value.

The multiple choice operator switch supports many other comparison operators within itself and is not limited to simple comparisons:

Let vegetable = "red pepper" switch vegetable ( case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich ." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." )

Let's experiment
Try removing the default condition. What error will you receive?

After executing the appropriate block of code, the program leaves the switch statement without checking subsequent conditions. This way you don't have to manually add break statements at the end of each case block.

To iterate over the elements of an associative array, use the for-in statement along with specifying a pair of names for each key-value pair.

Let interestingNumbers = [ "Prime": , "Fibonacci": , "Square": , ] var largest = 0 for (kind, numbers) in interestingNumbers ( for number in numbers ( if number > largest ( largest = number ) ) ) largest

Let's experiment
Add another variable that will allow you to find out which of the three types the maximum number found is.

The while loop statement allows you to execute a block of code within it until the condition evaluates to false. The condition can also be specified after the block, which in this case will be executed at least once.

Var n = 2 while n< 100 { n = n * 2 } n var m = 2 do { m = m * 2 } while m < 100 m
The for statement can be used to iterate over a sequence of numbers using two dots (..) or using an initializer, condition, and increment. Look, these two loops do the same thing:

Var firstForLoop = 0 for i in 0..3 ( firstForLoop += i ) firstForLoop var secondForLoop = 0 for var i = 0; i< 3; ++i { secondForLoop += 1 } secondForLoop
When creating a loop, use two dots (..) if you do not want to include the larger value in the range, and three dots (...) to include both the smaller and larger values.

Functions and closures.
To declare functions, use the func keyword. A function is called by specifying its name and a list of arguments in parentheses. The return type should be separated from the formal argument list using -> .

Func greet(name: String, day: String) -> String ( return "Hello \(name), today is \(day)." ) greet("Bob", "Tuesday")

Let's experiment
Remove the day parameter. Instead, add a variable indicating the name of the dish being served for lunch.

If a function returns multiple values, you should use a tuple:

Func getGasPrices() -> (Double, Double, Double) ( return (3.59, 3.69, 3.79) ) getGasPrices()
Functions can also have an indefinite number of arguments:

Func sumOf(numbers: Int...) -> Int ( var sum = 0 for number in numbers ( sum += number ) return sum ) sumOf() sumOf(42, 597, 12)

Let's experiment
Write a function that allows you to find the arithmetic mean of an arbitrary number of its arguments.

Functions can be nested within each other. A nested function can access variables declared in the outer function. Use nested functions to tidy up the code of a complex or large function.

Func returnFifteen() -> Int ( var y = 10 func add() ( y += 5 ) add() return y ) returnFifteen()
Functions are objects of the first class (first-class type), in other words, a function can return another function as its result.

Func makeIncrementer() -> (Int -> Int) ( func addOne(number: Int) -> Int ( return 1 + number ) return addOne ) var increment = makeIncrementer() increment(7)
A function can also take another function as one of its arguments.

Func hasAnyMatches(list: Int, condition: Int -> Bool) -> Bool ( for item in list ( if condition(item) ( return true ) ) return false ) func lessThanTen(number: Int) -> Bool ( return number< 10 } var numbers = hasAnyMatches(numbers, lessThanTen)
Functions are a special case of closures. You can create a closure without specifying a name and by surrounding the body of the closure with curly braces (()). To separate the arguments and return type from the body of the closure, use the in operator.

Numbers.map(( (number: Int) -> Int in let result = 3 * number return result ))

Let's experiment
Rewrite the closure so that it returns zero for all extra numbers.

There are several techniques to make closures more concise. If the type of the closure is known a priori (for example, it is a callback of a delegate), you can omit specifying the type of its parameters and/or the type of the return value. Closures consisting of a single expression implicitly return the result of that expression.

Numbers.map(( number in 3 * number ))
In a closure, instead of specifying a variable name, you can use its ordinal number - this is especially useful when writing short circuits. The closure, which is the last argument of the function, can be passed to it immediately after the parentheses with the list of remaining parameters.

Sort() ( $0 > $1 )

Objects and classes
To create a class, use the reserved word class. Class members are declared in the same way as regular constants and variables. Moreover, class methods are declared as ordinary functions.

Class Shape ( var numberOfSides = 0 func simpleDescription() ->

Let's experiment
Add a class member constant and a class method that takes it as its argument.

To create an instance (object) of a class, just add parentheses after the class name. Methods and class members are accessed through a dot.

Var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()
In this example, we missed one important detail - the class constructor, the init method.

Class NamedShape ( var numberOfSides: Int = 0 var name: String init(name: String) ( self.name = name ) func simpleDescription() -> String ( return "A shape with \(numberOfSides) sides." ) )
Notice how the name class member is separated from the name constructor argument by self. Arguments are passed to the constructor in the normal way, as to any other class method. Note that each class member must be initialized, either when declared (like numberOfSides) or in the constructor (like name).

The class destructor is the deinit method, which can be overwritten if necessary.

To inherit a class from an existing class, after specifying the name of the child class, add a colon and indicate the name of the parent class. In Swift, there are no restrictions on the mandatory inheritance of any standard class.

Methods overridden by a child class must be marked with the override keyword - overriding methods without override will result in an error. The compiler also detects methods that are marked override but do not override any methods of their parent class.
class Square: NamedShape ( var sideLength: Double init(sideLength: Double, name: String) ( self.sideLength = sideLength super.init(name: name) numberOfSides = 4 ) func area() -> Double ( return sideLength * sideLength ) override func simpleDescription() -> String ( return "A square with sides of length \(sideLength)." ) ) let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription ()

Let's experiment
Create a Circle class and inherit from the NamedShape class. The constructor for the Circle class takes two arguments: radius and name. Override the area and describe methods of this class.

Class members can also have their own getter and setter .

Class EquilateralTriangle: NamedShape ( var sideLength: Double = 0.0 init(sideLength: Double, name: String) ( self.sideLength = sideLength super.init(name: name) numberOfSides = 3 ) var perimeter: Double ( get ( return 3.0 * sideLength ) set ( sideLength = newValue / 3.0 ) ) override func simpleDescription() -> String ( return "An equilateral triagle with sides of length \(sideLength)." ) ) var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle ") triangle.perimeter triangle.perimeter = 9.9 triangle.sideLength
In the setter of the perimeter variable, the new value assigned is implicitly called newValue . You can change the name of this variable by putting it in parentheses immediately after set .

Notice the constructor structure of the EquilateralTriangle class. This method includes three sequential steps:

  1. initializing members of a child class;
  2. calling the constructor of the parent class;
  3. changing the values ​​of members of the parent class.
If you need to execute specific code before or after assigning a new value to a variable, you can override the willSet and didSet methods to suit your needs. For example, the class below guarantees that the side length of a triangle will always be equal to the side length of a square.

Class TriangleAndSquare ( var triangle: EquilateralTriangle ( willSet ( square.sideLength = newValue.sideLength ) ) var square: Square ( willSet ( triangle.sideLength = newValue.sideLength ) ) init(size: Double, name: String) ( square = Square( sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) ) var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") triangleAndSquare.square.sideLength triangleAndSquare.triangle.sideLength triangleAndSquare .square = Square(sideLength: 50, name: "larger square") triangleAndSquare.triangle.sideLength
Class methods have one important difference from functions. The names of a function's arguments are used only within that function, whereas in a class method, the parameters are also used when calling that method (except for the first parameter). By default, a class method has the same parameter names both when called and within itself. However, you can specify a different name (in the example below - times), which will be used only inside this method. In this case, to call this method, you must use the first name (numberOfTimes).

Class Counter ( var count: Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) ( count += amount * times ) ) var counter = Counter() counter.incrementBy(2, numberOfTimes: 7)
When working with optional values, add a question mark (?) before methods, class members, etc. If the value before the question mark is nil, anything after the (?) is ignored and the entire expression is nil. Otherwise, the expression is evaluated as usual. In both cases, the entire expression will result in an optional value.

Let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength

Enumerations and Structures
The enum keyword is used to create enumerations. Note that enumerations can also contain methods.

Enum Rank: Int ( case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String ( switch self ( case .Ace: return " ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) ) ) ) let ace = Rank.Ace let aceRawValue = ace .toRaw()

Let's experiment
Write a function that compares 2 Rank enumerations based on their values.

In the above example, the enum elements are initially of integer type, and you only need to specify the value of the first element - the values ​​of the remaining elements will be determined according to the order in which they appear. You can also choose string or real types as the raw value of element values.

To convert the original value type to an enumeration type, use the toRaw and fromRaw functions.

If let convertedRank = Rank.fromRaw(3) ( let threeDescription = convertedRank.simpleDescription() )
Note that the values ​​of the enumeration elements are actual, and not simply another representation of their original values. Generally speaking, you don't have to specify their original values.

Enum Suit ( case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String ( switch self ( case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" ) ) ) let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription()

Let's experiment
Add a Color method that returns the string “black” for Spades and Clubs and “red” for Hearts and Diamonds.

Notice how the Hearts member of the Suit enumeration is accessed. When assigning a value to the hearts constant, the full name Suit.Hearts is used because we are not explicitly specifying the type of the constant. And in switch we use the short form .Hearts because the type of the self value is known a priori. You can use the short form throughout as long as the type of the variable is explicitly specified.

The struct keyword is used to create structures. Structs have many similarities to classes, including methods and constructors. One of the most significant differences between structures and classes is that instances of structures, unlike instances of classes, are passed to functions by value (that is, their local copy is first created), while instances of classes are passed by reference.

Struct Card ( var rank: Rank var suit: Suit func simpleDescription() -> String ( return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" ) ) let threeOfSpades = Card(rank: . Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()

Let's experiment
Add a method to the Card structure that creates a full deck of cards.

An enumeration member instance can have its own values, and they can be different. You assign these values ​​when you instantiate the enum (the success constant in the example). Bound and initial values ​​are different things: the initial value of an enumeration member is always constant across all instances of the enumeration and is specified when it is declared.

Let's consider an example of receiving sunrise and sunset times from a server. The server responds with either relevant information or an error message.

Enum ServerResponse ( case Result(String, String) case Error(String) ) let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese." ) switch success ( case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure.. .\(error)" )

Let's experiment
Add a third option to a multiple choice switch statement

Notice how the sunrise and sunset times are pulled from the ServerResponse object.
Protocols and Extensions.
To declare a protocol, use the protocol keyword.

Protocol ExampleProtocol ( var simpleDescription: String ( get ) mutating func adjust() )
Protocols can be supported by classes, enumerations, and structures.

Class SimpleClass: ExampleProtocol ( var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() ( simpleDescription += " Now 100% adjusted." ) ) var a = SimpleClass() a.adjust( ) let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol ( var simpleDescription: String = "A simple structure" mutating func adjust() ( simpleDescription += " (adjusted)" ) ) var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription

Let's experiment
Create an enum that will implement this protocol.

Note the mutating keyword in the SimpleStructure definition, which tells the compiler that the corresponding method is modifying the structure. In contrast, the methods of the SimpleClass class do not need to be marked as mutating, since the methods of the class can always change it without interference.

To add new methods or class members to an existing type, you must use extensions. You can also use extensions to implement a protocol with an existing type, even if it is imported from a library or framework.

Extension Int: ExampleProtocol ( var simpleDescription: String ( return "The number \(self)" ) mutating func adjust() ( self += 42 ) ) 7.simpleDescription

Let's experiment
Create an extension of type Double with a member variable absoluteValue .

You can use the protocol name like any other type - for example, to create an array of objects of different types but implementing a common protocol. Note that when working with objects of this type, methods declared outside the protocol will not be available.

Let protocolValue: ExampleProtocol = a protocolValue.simpleDescription // protocolValue.anotherProperty // Uncomment to see the error
Even though the protocolValue variable is of type SimpleClass at run time, the compiler assumes that its type is ExampleProtocol . This means that you won't be able to accidentally access methods or class members that are implemented outside of the ExampleProtocol.

Generic types
To create a generic type, enclose the name in angle brackets (<>).

Func repeat (item: ItemType, times: Int) -> ItemType ( var result = ItemType() for i in 0..times ( result += item ) return result ) repeat("knock", 4)
Create generic functions, classes, enumerations, and structures.

// Reimplement the Swift standard library's optional type enum OptionalValue ( case None case Some(T) ) var possibleInteger: OptionalValue = .None possibleInteger = .Some(100)
If you want to specify specific requirements for a generic type, such as implementing a protocol or requiring it to inherit from a particular class, use where .

Func anyCommonElements (lhs: T, rhs: U) -> Bool ( for lhsItem in lhs ( for rhsItem in rhs ( if lhsItem == rhsItem ( return true ) ) ) return false ) anyCommonElements(, )

Let's experiment
Modify the anyCommonElements function to return an array of common elements.

In simple cases, you can omit the where and write the protocol or class name after the colon. Expression is equivalent to the expression .

As has already been noted several times, including by , the conference was excellent, even if no hardware was presented at it. The software products alone were enough. How much the public liked the conference is evidenced by the fact that after it, nothing noticeable, traditional for such cases, happened.

And while much of what was presented was quite expected by the public, the programming language turned out to be a real surprise. After all, no one even suspected that Apple was working in this direction. However, the programming language is not the iPad; developments of this type are of little interest to the general public. This means that maintaining secrecy was much easier.

The most secret project

In fact, work on Swift began back in 2010, after the presentation of the iPad. The company wanted to create a simple, convenient and functional tool that could make life as easy as possible for developers.

The work was carried out in the strictest confidence. Moreover, for quite a long time only one person worked on the project - Chris Lattner, director of the Developer Tools department. Of course, the staff subsequently had to be expanded. But still, the number of these people has never been large enough. Few people knew about the development of a new language, even within the walls of Apple itself, although by 2013 it was considered the most important Developer Tools project. It is important to note that the company wanted to present the finished product right away, avoiding all kinds of beta versions. Therefore, the work stretched until 2014.

Here it would be appropriate to talk a little about Lattner himself. He came to Apple in 2005, before that he worked for the benefit of the LLVM project at the University of Illinois, being one of the leading developers.

LLVM (Low Level Virtual Machine) is a low-level virtual machine, a universal system for transformation, optimization and analysis of programs. The project began as an independent project, but subsequently received significant outside support. Including from Apple itself, which then actively used LLVM in its own projects, including OS X and iOS. The same Metal was developed using this system.

LLVM could not be avoided in the case of Swift either. Using this system, the language is compiled into machine code that is optimized to get maximum benefit when using the application on Apple technology.

At one time, Chris Lattner's move to Apple was a more than logical step. No less logical was the decision to entrust the development of a new language to him. It's too early to make a final verdict, but it looks like he did a great job.

Features of Swift

The brainchild of the latest developments, the compiled object-oriented programming language Swift builds on languages ​​such as Objective-C and C, bringing together the best of them. There are no restrictions in terms of compatibility; languages ​​can coexist perfectly in one application. The latter, by the way, is very important, since there are already a huge number of programs written in Objective-C.

Interestingly, the vague idea of ​​Swift appeared back in the days of NeXT, when Objective-C had just begun to be developed. Then the idea was born of creating a language that could make the programming process simpler and more fun. But, as we see, it took a lot of time to implement this idea.

In fact, it is not so easy to find that line when the code is simple enough to type, but at the same time readable enough for a third-party developer to understand pieces of someone else’s program without commentary. For example, a program written in Pascal is easy to understand, but the code is too long. PERL allows you to write everything in a few lines, but is characterized by extremely unreadable code.

Meanwhile, some developers who have already tried Swift in practice claim that Apple managed to come as close as possible to the ideal, to find that golden mean between readability and ease of typing.

As is immediately clear from the name of the new language ( "swift" - English. "fast, swift"), the main emphasis during its creation was on speed. In particular, it is stated that a program in Swift will run 1.3 times faster compared to a similar one written in Objective-C.

Also, when developing Swift, such important parameters as simplicity, security and flexibility were taken into account. This language eliminates entire classes of unsafe code and is capable of automatically managing memory. Swift eliminates the very possibility of making a number of mistakes that are so common among novice programmers. As for simplicity, it is well confirmed by the fact that within 24 hours from the moment, it is already on it.

The creators have put a lot of effort into making Swift code more expressive and easier to understand. The developer can immediately track the results of his creativity by viewing individual parts of the code in the so-called. “interactive playgrounds” (Interactive Playgrounds). If it takes quite a lot of time to execute the code, then you can monitor the process on a special feedback line that appears for this purpose. After the code has been improved and the algorithm has been perfected, the developer simply moves it to his project. Playgrounds can be useful not only in terms of simplifying the development process, but also in sharpening your Swift skills.

A traditional "Hello, World" application looks like this in Swift:

println("Hello, world")

And here is another example of simple code:

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

Criticism of Swift

Meanwhile, openly negative opinions regarding Swift are also appearing on the Internet. There are concerns that this is a dead-end development path and Swift will never be able to become popular. After all, even before this, there were many programming languages ​​that were created precisely with the goal of making the lives of programmers easier and simplifying the learning process. And not one of them fully coped with the tasks assigned to him. All that their creators managed to achieve was simply to increase the already considerable number of programming languages.

There is criticism of Apple's actions, which "would be better off developing languages ​​like Python or Ruby, instead of creating another one." Such words are supported by the opinion that these tools are already actively used by developers from all over the world. I also happened to find an opinion according to which Apple is in vain making its main bet on speed. They say that at modern levels of iron development this is not so important.

But what causes the most irritation is the fact (as always in such cases) that Apple created something only for itself, according to its own standards and on its own principles. Moreover, it is stated that although Swift is not very different from many other languages, the company again declares the creation of a fundamentally new product.

Instead of an afterword

One can criticize Apple for being overly closed and arrogant. You can admire the simplicity of Swift and the cleanliness of its code. But the fact remains that the future of the new programming language is still unclear. And two development scenarios are possible.

Scenario one. Swift remains just an interesting development. It is used, but not too actively, preferring to continue working with the proven and familiar Objective-C. Developers for other platforms do not notice the emergence of a new language at all.

Scenario two. The approaches used in Swift are becoming the norm in the programming world. Apple is once again managing to influence the entire world by changing the norms generally accepted among developers. The idea of ​​"playgrounds", coupled with the transparency of the code of the new language, may well revolutionize the learning of programming. And this will allow us to completely reconsider the entire educational process and provoke the emergence of a new generation of programmers.

By the way, I wouldn’t be surprised if in a few years, having thoroughly “polished” Swift, bringing it to perfection, Apple declares that it intends to abandon Objective-C altogether and rely on a new language.

I have been using Apple technology since the “classic era”, since 1995. During this period, I saw more than one sudden and significant (and sometimes downright shocking) “revolution” in the development of the company. Which, despite everything, did not lose its charm. I believe that it will continue to be so.

Best articles on the topic