Swift Programming
Published in

Swift Programming

1. Learn Swift by running Scripts

Learn using command line Scripts without using Xcode UI

$ swift
Welcome to Swift! Type :help for assistance.
1> print(“Hello World”)
Hello World
2>

Hello World! in Swift

However this tutorial is about running scripts. Open your code editor and create a file called hello.swift. And type the following into it.

print("Hello World!")
$ swift hello.swift
Hello World!
#!/usr/bin/env swiftprint("hello world!!)
$ chmod +x hello.swift
$ ./hello.swift
Hello World
dump(Process.arguments)
$ swift hello.swift foo bar “hello world”
▿ 4 elements
  —  [0]: hello.swift
  —  [1]: foo
  —  [2]: bar
  —  [3]: hello world

The Swift Compiler

Note: On OSX Yosemite and Xcode 6.1 and above you can run the Swift Compiler by just typing swiftc in the command line.

$ swiftc hello.swift -o hello
$ ./hello
Hello World

Get on with it!

Now that you know how to run a Swift program as a script, let us get on with it. Type the following program and run it.

Our first function in Swift

func doNothing() {
}
doNothing()

Functions return a value

Now let us see what doNothing returns if at all anything. For that we will assign the value returned by doNothing() to a new variable called nothing. You use the var statement to define variables in Swift.

func doNothing() {
}
var nothing = doNothing()
functions.swift:3:5: warning: variable ‘nothing’ inferred to have type ‘()’, which may be unexpected
func doNothing() {
}
var something: () = doNothing()
func doNothing() {
}
var something: Void = doNothing()
func doSomething() {
return "Hello World"
}
var something: String = doSomething()
functions.swift:4:25: error: ‘()’ is not convertible to ‘String’
var something: String = doSomething()
^
functions.swift:2:12: error: cannot convert the expression’s type ‘String’ to type ‘()’
return “Hello World”
^~~~~~~~~~~~~

Function return Types

The compiler is expecting the function to return a ‘()’ aka Void! And we are returning type String. If you return anything other than a Void from a function you need to specify its return type. So let us specify a return type for the function.

func doSomething() -> String {
return "Hello World"
}
var something: String = doSomething()

Type inference in Swift

func doSomething() -> String {
return "Hello World"
}
var something = doSomething()

Function parameter Types

Now we will write a function, given a name, will return a greeting.

func greet(name) -> String {
return "Hello "+ name
}
var greeting: String = greet(“John”)
functions.swift:1:12: error: use of undeclared type ‘name’
func greet(name) -> String {
^~~~
func greet(name: String) -> String {
return "Hello "+ name
}
var greeting = greet("John")
print(greeting)

Variable Type in Swift

Swift is a Strongly Typed Language. Which means every variable you define must have a corresponding Type, either explicitly defined or inferred. You cannot assign a value of a different type to a variable already defined. The two ways you can define a variable are by using the var or let statements.

var name = "John"
let anothername = "Bob"
var name = "John"
name = "Jill" // Ok
let anothername = "Bob"
anothername = "Ben" // error
  1. In variable definitions using var and let. In this case if you initialize the variable in the same statement, the type need not be specified, the type will be inferred.
  2. In function definitions, in functions parameter list.
  3. The return Type in a function definition.

Function Type

In Swift, functions have a Type too! What is the Type of the greet function we wrote above?

(String) -> String

Factorial Function in Swift

Here is the definition of factorial from wikipedia.

5! = 5 * 4 * 3 * 2 * 1 = 120
func factorial(n: Int) -> Int {
if n == 0 {
return 1
}
var fact = 1
for i in 1…n {
fact = fact * i
}
return fact
}
print(factorial(5)) // prints 120
(Int) -> Int
 if n == 0 {
return 1
}
 var fact = 1
 for i in 1...n {
fact = fact * i
}
for i in 0..<length

The isPrime Function in Swift

The isPrime function takes a given integer and returns true or false, based on whether the given number is a prime number or not.

import Foundationfunc isPrime(n: Int) -> Bool {
if n < 2 {
return false // are not primes
}
var limit = Int(sqrt(Float(n)))
if limit < 2 {
return true // 2, 3 are primes
}
for i in 2…limit {
if n % i == 0 {
return false
}
}
return true
}
import Foundation
(Int) -> Bool
 if n < 2 {
return false // are not primes
}
var limit = Int(sqrt(Float(n)))
Float(n)
sqrt(Float(n))
Int(sqrt(Float(n)))
 if limit < 2 {
return true // 2, 3 are primes
}
 for i in 2…limit {
if n % i == 0 {
return false
}
}
return true

All Prime numbers less than 100

The next program will print out all the prime numbers from 2 to 100 and uses the isPrime function.

var primes: [Int] = []
for i in 2…100 {
if isPrime(i) {
primes.append(i)
}
}
print(primes)
// Prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
var primes: [Int] = []
isPrime(i)
 if isPrime(i) {
primes.append(i)
}

Optionals in Swift

Try this

var num: Int = 10
print(num)
var num: Int
print(num)
error: variable ‘num’ used before being initialized
print(num)
^
var num: Int                 // Value is nil
var num: Int = 0 // Value is zero
var num: Int = nil           // Error!
var num: Int?
print(num) // prints nil
var num: Int?
if num == nil {
print("num is nil") // prints "num is nil"
}
var num: Int? = 10
func square(x: Int) -> Int {
return x * x
}
square(num)
error: value of optional type ‘Int?’ not unwrapped; did you mean to use ‘!’ or ‘?’?
square(num)
^
var num: Int? = 10
func square(x: Int) -> Int {
return x * x
}
print(square(num!)) // 100
var num: Int? = nil
func square(x: Int) -> Int {
return x * x
}
print(square(num!)) // Fatal Error!
var num: Int? = nil
func square(x: Int) -> Int {
return x * x
}
if num != nil {
print(square(num!))
} else {
print("num is nil") // prints "num is nil"
}
var num: Int? = 10
func square(x: Int) -> Int {
return x * x
}
if let newnum = num {
print(square(newnum)) // prints 100
} else {
print(“num is nil”)
}
if let newnum = num

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Santosh Rajan

Founder www.geekskool.com. Programmer for over 30 years. Making better programmers is my passion. Bangalore. India. www.santoshrajan.com