Swift Tutorial - App Development for iOS8 [Part 1, Hello World!]

Original author: Jameson Quave
  • Transfer
  • Tutorial


Recently, Apple introduced to the public a fairly important change in the development of iOS applications, announcing the new programming language Swift. I made a decision: studying this language step by step, I will in my articles talk about everything that I managed to find. This is only the first of many posts on this topic, but I hope you decide to learn the language with me!

It is very likely that many of the code examples presented in the posts will be changed later. This is partly because my programming style is to write now to test the idea and then do refactoring, and partly because because for me (as for many others) Swift is a completely new programming language. So, most likely, as soon as I learn something new, the course of these lessons will change.

So, I'm going to start with a fairly simple application. I will also explain how the code works. Ready? Let's go ...

UPD: The article was written in accordance with the changes in Xcode 6 Beta 5

The basics

Swift eliminates the use of the variable declaration standard, which uses the type name before the variable declaration; instead, the keyword is used for the declaration, as in JavaScript var.
So for example, this line is Objective-C
NSString *myString = @"This is my string.";

in Swift will be replaced by this
var myString = "This is my string."

The keyword is used to declare constants. let
let kSomeConstant = 40

In this case, it is kSomeConstantimplicitly defined as an integer. If you want to specify the type, then you can do it like this:
let kSomeConstant: Int = 40

A little bit about Clean Code
The author of the translation recommends using the second example of declaring constants. A fairly revealing example is described in the official documentation:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

In this, the author of the translation is in solidarity with Helecta (see the corresponding post )

Both arrays and dictionaries are described using []
var colorsArray = ["Blue", "Red", "Green", "Yellow"]
var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]

This is not all, but I believe that these basics are important enough for further reading of the textbook. So let's move on toHello, World!

Hello World!

First of all, we will write the simplest application that you can imagine to get started - Our application will do only one thing: print the phrase “Hello, World!” To the console. To do this, we need the installed Xcode IDE, for downloading which a developer account is required. If you have an account, then feel free to download from the official XCode 6 beta 4 website , it is advisable to do this before reading the description below. So, you have installed your copy of the IDE. Now let's output “Hello, World!” To the console. This example not only demonstrates the simplest application that can be written, but also, importantly, shows that the development environment is configured correctly.Hello, World!

In Xcode, create a project using the “Single View Application” application template.

Make sure you select Swift as your application language.

You should now find the AppDelegate.swift file in the project hierarchy. Inside, find the following line:
"// Override point for customization after application launch."

Replace this line with our amazing code:
println("Hello World")

Now click "Run". You should see an empty application loading and the words Hello, World!printed in the console located at the bottom of the Xcode window. Note that this will not be displayed in the iPhone simulator.

Congratulations! You just wrote your first Swift app! True, it will not receive any bonuses, prizes, only your own applause. Now, let's dig a little deeper ...

Adding a Table View

In this section we will try to add material to the screen. Open Main.storyboard file in Xcode, transfer the object from the Object Library (“Object Library”) Table Viewto the application screen, expand the table so that it coincides with the edges. Then change the height by dragging the top edge, leaving a small space on top (this is necessary for the status bar). If you run the application, you will see an empty table in the simulator.

Now you need to create a delegate and data source for the table. This is easiest to do in the interface constructor. Press the Command key, click and drag Table Viewto the object View Controllerin the hierarchy of the .storyboard file, and select “data source”. Repeat with the option "delegate".

Note:I got a ton of questions about the above, because many people report that they do not set the table view. Therefore, I recorded a video explaining how connecting Storyboard objects in code works. To view, go to full screen mode and select the 720p option so that you can notice everything that interests you. This will be slightly different from the Xcode interface, but functionally everything works as well.

Now let's delve into the protocol methods for the table view. Due to use UITableViewDataSourceand UITableViewDelegatewe have to change the class definition.
Open the file and replace the line
class ViewController: UIViewController {

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

If you press the Command key and click on one of these protocols, you will see the “required” functions. A table view requires at least these two:
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

Change our class View Controllerby adding these two functions:
func tableView(tableView: UITableView!, numberOfRowsInSection section:    Int) -> Int {
   return 10
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
   let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
   cell.textLabel.text = "Row #\(indexPath.row)"
   cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"
   return cell

The first method returns the number of rows in the section. In our example, the “magic” number is 10, however, instead of it, as a rule, the length of the array controller should be used. Our code is intentionally simplified.

In the second method, pure magic happens. We instantiate the class UITableViewCell( cell) using the cell style Subtitle. Then we assign a value to the text value of this cell "Row #\(indexPath.row)". In Swift, in a similar way, the values ​​of variables are embedded into the string without conversion (thus, we get strings of the form "Row #1", "Row #2")

Detailed text label ( detailTextLabel) is available only when using the cell class Subtitlethat we use in this example.

When you start the application, you will see a delightful list of cells with headers and subheadings showing their row numbers. This is one of the most common ways to display data in iOS, you will see that it will come in handy more than once. You can see the full text of the code on github .

In the next post, we will explore the use of the iTunes Search API to create an application that can search and display albums within the iTunes Store.

Question about further translation

Dear Habralyudi! If you read this translation, help the author decide on the future of the cycle.
To do this, you just need to participate in the survey.

Only registered users can participate in the survey. Please come in.

Is translation useful for you?

  • 61.6% Yes, the translation was useful 248
  • 11.6% No, translation is useless 47
  • 15.4% I can not answer unambiguously 62
  • 11.1% Not Interested in Swift 45

Should I translate the following articles in the series?

  • 74.7% Of course it is! After all, there are so few materials in Russian according to Swift- 317
  • 12.5% No, it’s not worth it, enough English-language materials 53
  • 12.7% Interesting to read, but to me it is useless 54

Also popular now: