swift programming language
Learn from examples
This is designed for use of swift language on MAC OSX and Linux
Some MAC OSX must use playground
1. Program to output an integer, a string,
and a floating point number, initially just one method.
exsw1.swift source code
exsw1_swift.out Output of execution
// exsw1.swift first example simple output integer, string, double
// note // makes rest of line a comment
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
var i = 7 // declare variable i with initial value 7
let ac = "a" // single character, let makes ac unchangeable
var msg = "sample string" // declare msg with string in quotes
var x = 37.95 // declare floating point x with initial value
var y = 127.34e10 // declare double precision with initial value
print("exsw1.swift running"); // simple print title
print("i= \(i)"); // \( ) for any type
print("ac= \(ac)"); // \( ) for any type
print("msg= \(msg)"); // \( ) for any type
print("x= \(x)"); // \( ) for any type
print("y= \(y)"); // \( ) for any type
print("sin(1.0)= \(sin(1.0))") // \( ) for functions
Execution output:
exsw1.swift running
i= 7
ac= a
msg= sample string
x= 37.95
y= 1273400000000.0
sin(1.0)= 0.841470984807897
2. commands to compile and execute the source code
at a minimum, Windows, Linux, MacOSX.
Linux:
swift exsw1.swift
MacOSX:
swift exsw1.swift
Windows: not available
save output to a file:
swift exsw1.swift > exsw1_swift.out
3. You must be able to declare variables and list and arrays
and matrix of various types.
exsw3.swift source code
exsw3_swift.out Output of execution
// exsw3.swift declare constants, variables, arrays
// see exsw3a for sets, dictionaries and classes
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw3.swift running")
let c1 = 1 // integer constant
// let c2= 1 // error must have space each side of operator
var c3 = 2 // integer variable initial value 2
let f1 = 7.5 // floating point constant
var f2 = 37.5e-6 // floating point variable
let s1 = "unchangeable string"
var s2 = "changeable string"
print("c1= \(c1)")
print("c3= \(c3)")
print("f1= \(f1)")
print("f2= \(f2)")
print("s1= \(s1)")
print("s2= \(s2)")
// var c4 : Int = 8.2 // error
let f3 : Double = 8 // this will be constant 8.0
var f4 : Double = 9 // this will be variable initial value 9.0
print("f3 as integer= \(f3)")
print("f4 as integer= \(f4)")
// define an empty array
var someInts = [Int]()
someInts.append(1)
someInts.append(2)
print("someInts= \(someInts)")
someInts = [] // back to empty array
// define an initialized array with values of same type
var V = [1.2, 1.3, 1.4]
print("V= \(V)")
// define and initialized array with some value
var big = Array(repeating: 0.0, count: 1000)
print("big[999]= \(big[999])")
Execution output:
exsw3.swift running
c1= 1
c3= 2
f1= 7.5
f2= 3.75e-05
s1= unchangeable string
s2= changeable string
f3 as integer= 8.0
f4 as integer= 9.0
someInts= [1, 2]
V= [1.2, 1.3, 1.3999999999999999]
big[999]= 0.0
exsw3a.swift source code
exsw3a_swift.out Output of execution
// exsw3a.swift declare dictionary, class
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw3a.swift running")
// define a dictionary and use some operations
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13, 17],
"Fibonacci": [1, 1, 2, 3, 5, 8, 13, 21],
"Square": [1, 4, 9, 16, 25],
"Cube":[1, 8, 27, 64]
]
var largest = 0
var mykind = " "
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
mykind = kind
}
}
}
print("kind=\(mykind) large=\(largest)")
var mynumber = 9
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number == mynumber {
mykind = kind
}
}
}
print("kind=\(mykind) has \(mynumber)")
// define a class and use some operations
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
} // end class NamedShape
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")
let aans = test.area()
print(aans)
let dans = test.simpleDescription()
print(dans)
print("exsw3a.swift finished")
Execution output:
exsw3a.swift running
kind=Cube large=64
kind=Square has 9
27.04
A square with sides of length 5.2.
exsw3a.swift finished
4. You need to be able to have loops, iteration statements
exsw4.swift source code
exsw4_swift.out Output of execution
// exsw4.swift loops and iteration statements
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw4.swift running");
var v1 = [2, 4, 6, 8] // 4 items subscripts 0,1,2,3
var f2 = [3.3, 5.5, 7.7] // 3 items subscripts 0,1,2
for i in 0...3 {
print("v1[\(i)]=\(v1[i])")
}
for i in 0..<4 {
print("v1[\(i)]=\(v1[i])")
}
Execution output:
exsw4.swift running
v1[0]=2
v1[1]=4
v1[2]=6
v1[3]=8
v1[0]=2
v1[1]=4
v1[2]=6
v1[3]=8
5. You need if then else conditional statements
exsw5.swift source code
exsw5_swift.out Output of execution
// exsw5.swift if, then, else conditional statements, switch case
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw5.swift running")
var x : Double = 2.0 // declare test variable
var i = 3
if x < 3.0 { // < > <= >= == != compare operations
print("compare < > <= >= == != x= \(x)")
}
if x > 3.0 || i == 3 && i > 2 { // || is or, && is and
print("logic || is or, && is and i= \(i)")
}
if x > 3.0 {
print("x > 3.0")
}
else if i < 3 { // optional
print("i < 3")
}
else { // optional, get here if none of the above true
print("none of the above")
} // end if optional comment
// switch case default statements
var aval = 2
switch aval {
case 1:
print("case 1")
case 2:
print("case 2")
default:
print("none of above")
} // end switch
var vegetable = "watercress"
switch vegetable {
case "celery":
print("Add some raisins.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
default:
print("Everything tastes good in soup.")
}
print("exsw5.swift finished")
Execution output:
exsw5.swift running
compare < > <= >= == != x= 2.0
logic || is or, && is and i= 3
none of the above
case 2
That would make a good tea sandwich.
exsw5.swift finished
6. You need to be able to create functions, procedures,
subroutines.
exsw6.swift source code
exsw6_swift.out Output of execution
// exsw6.swift create functions, procedures, subroutines
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw6.swift running");
let vals = [2, 4, 6]
for aval in vals {
print(aval)
}
func matcpy(_ a: [[Double]]) -> [[Double]] {
let n = a.count
let m = a[0].count
var inv = [[Double]](repeating:[Double](repeating:0.0,count:m),count:n)
for i in 0..<n {
for j in 0..<m {
inv[i][j] = a[i][j]
} // end i
} // end j
return inv
} // end matcpy
var A = [[1.2, 1.3, 1.5],[2.5, 3.5, 4.5]]
var B = matcpy(A)
print("B= \(B)")
Execution output:
exsw6.swift running
2
4
6
B= [[1.2, 1.3, 1.5], [2.5, 3.5, 4.5]]
7. You need to be able to read and write files in various formats.
exsw7.swift source code
exsw7_swift.out Output of execution
// exsw7.swift read and write files
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw7.swift running");
(coming soon)
exsw7.swift running
8. You need to be able to use a number of files combined to
build a program. This may include packages, libraries,
operating system commands, header files, etc.
exsw8.swift source code
exsw8_swift.out Output of execution
// exsw8.swift bring in separetly compiles files
#if os(OSX) || os(iOS) // for libraries, portable for OSX and Linux
import Foundation
#elseif os(Linux)
import Glibc
#endif//
print("exsw8.swift running");
print("this requires a lot of setup in Linux")
print("on MACOSX this seems only possible in playground ?")
Execution output:
exsw8.swift running
this requires a lot of setup in Linux
on MACOSX this seems only possible in playground ?
Now, you are ready for a more complete language summary
swift_example.shtml Here are many .swift examples
Last updated 7/27/2019