Swift: Difference between revisions
(19 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=Introduction= | =Introduction= | ||
Here is my first dip into Apple and swift | Here is my first dip into Apple and swift | ||
[https://koenig-media.raywenderlich.com/uploads/2019/11/RW-Swift-5.1-Cheatsheet-1.0.1.pdf Swift Cheat Sheet] | [https://koenig-media.raywenderlich.com/uploads/2019/11/RW-Swift-5.1-Cheatsheet-1.0.1.pdf Swift Cheat Sheet]<br> | ||
And the documentation | |||
[https://developer.apple.com/documentation/swift Docs] | |||
=Data Types= | =Data Types= | ||
Here we have the following Primatives | Here we have the following Primatives | ||
Line 7: | Line 10: | ||
*Float | *Float | ||
*Double | *Double | ||
* | *String | ||
*Bool | *Bool | ||
=Control= | =Control= | ||
Line 80: | Line 83: | ||
print(sum) | print(sum) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Collections= | |||
==Arrays== | |||
Using Arrays | |||
<syntaxhighlight lang="swift"> | |||
var d = ["dog", "cat", "bird"] | |||
// Using standard for loop | |||
for index in 0...(d.count -1) { | |||
print(d[index]) | |||
} | |||
// Alternatively | |||
for item in d { | |||
print(item) | |||
} | |||
// Declare empty | |||
var e = [String]() | |||
// Add or Remove | |||
e.append(d) | |||
e.remove(1) | |||
e[0] = "turtle" | |||
</syntaxhighlight> | |||
==Dictionaries== | |||
Using a dictionary | |||
<syntaxhighlight lang="swift"> | |||
// Initialize may values | |||
var responseMessages = [200: "OK", | |||
403: "Access forbidden", | |||
404: "File not found", | |||
500: "Internal server error"] | |||
// Initialize empty | |||
var emptyDict: [String: String] = [:] | |||
// Another approach | |||
var carDB = Dictionary[String:String]() | |||
carDB["DTQ 9999"] = "iCar" | |||
carDB["RPA 248"] = "Jag" | |||
// Update | |||
carDB["RPA 248"] = "Red Jag" | |||
// Remove | |||
carDB["RPA 248"] = nil | |||
// Iterate | |||
for (license, car ) in carDB { | |||
print("\(car) has license \(license)") | |||
} | |||
</syntaxhighlight> | |||
=Classes= | |||
==Class vs Structs== | |||
Classes are always passed by reference and Structs are passed by value i.e. | |||
<syntaxhighlight lang="swift"> | |||
let fred1 = MySalary(100) | |||
let fred2 = fred1 | |||
fred1.setSalary(50) | |||
print("Salary \(fred2)") | |||
// Prints 50 | |||
</syntaxhighlight> | |||
==Base Claas== | |||
<syntaxhighlight lang="swift"> | |||
class BlogPost { | |||
var title = "" | |||
var body = "" | |||
var counter = 0 | |||
func addCounter() { | |||
counter += 1 | |||
} | |||
} | |||
let myPost = BlogPost() | |||
myPost.title = "Hello" | |||
myPost.body = "My Body" | |||
myPost.addCounter() | |||
print(myPost.counter) | |||
</syntaxhighlight> | |||
==Optional Properties== | |||
We can make properties optional. Like most languages we need to test | |||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
class BlogPost { | |||
var title:String? | |||
var body = "hey" | |||
var counter = 0 | |||
} | |||
let post = BlogPost() | |||
// We test like this. | |||
if let actualTitle = post.title { | |||
print(actualTitle) | |||
} | |||
// If you know you have a value you can override | |||
post.title = "we have a value" | |||
actualTitle = post.title | |||
print(actualTitle!) | |||
// Or | |||
if actualTitle == nil { | |||
print(actualTitle!) | |||
} | |||
</syntaxhighlight> | |||
==Computed Properties== | |||
<syntaxhighlight lang="swift"> | |||
class BlogPost { | |||
var title:String? | |||
var author:String = "hey" | |||
// Computed Property | |||
if title != nil && author != nil { | |||
return title! + " by " + author | |||
} | |||
else { | |||
return "Something was nil" | |||
} | |||
} | |||
</syntaxhighlight> | |||
==Initialise (Constructor)== | |||
We use self in place of this for other languages. Don't forget about argument labels. Note more than one init() permitted | |||
<syntaxhighlight lang="swift"> | |||
class Person { | |||
var name = "" | |||
var age = 0 | |||
func init(_ name: String) { | |||
self.name = name | |||
self.age = 22 | |||
} | |||
func init(_ name: String, _ age: Init) { | |||
self.name = name | |||
self.age = age | |||
} | |||
} | |||
var a Person("Bill", 21) | |||
</syntaxhighlight> | |||
==Convenience Initializewr== | |||
This allows you to create an initializer where maybe only one parameter is different. It must call a standard (designated) initializer | |||
<syntaxhighlight lang="swift"> | |||
struct Scene { | |||
var minutes = 0 | |||
} | |||
class Movie { | |||
var title: String | |||
var author: String | |||
var date: Int | |||
var scenes: [Scene] | |||
init(title: String, author: String, date: Int) { | |||
self.title = title | |||
self.author = author | |||
self.date = date | |||
scenes = [Scene]() | |||
} | |||
convenience init(title:String) { | |||
self.init(title:title, author: "Unknown", date:2016) | |||
} | |||
func addPage(page: Scene) { | |||
scenes.append(page) | |||
} | |||
} | |||
var myMovie = Movie(title: "my title") // Using convenicence initializer | |||
var otherMovie = Movie(title: "My Title", author: "My Author", date: 12) // Using a long normal initializer | |||
</syntaxhighlight> | |||
==Inheritance== | |||
We do this using a colon | |||
<syntaxhighlight lang="swift"> | |||
class ImprovedBlog : BlogPost { | |||
var title = "" | |||
var body = "" | |||
var numberOfLikes = 0 | |||
func addNumberOfLikes() { | |||
numberOfLikes += 1 | |||
} | |||
} | |||
</syntaxhighlight> | |||
Override can be used and you can call the base implementation | |||
<syntaxhighlight lang="swift"> | |||
class NewCar : Car { | |||
override func drive() { | |||
print("Printing my stuff") | |||
// Print base stuff | |||
super.drive() | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 05:28, 10 July 2022
Introduction
Here is my first dip into Apple and swift
Swift Cheat Sheet
And the documentation
Docs
Data Types
Here we have the following Primatives
- Int
- Float
- Double
- String
- Bool
Control
If Statements
No surprises
if a < 4 {
print("we are here 1")
}
else if a == 4 && a < 3 {
print("we are here 2")
}
else {
print("we are here 3")
}
Switch Statements
var aCharacter = "a"
switch aCharacter {
case "a":
print("we are here a")
case "b":
print("we are here b")
default:
print("we are here not a or b")
}
Loops
Example for loop
var sum = 0
for index in 1..5 {
sum += index
print(sum)
}
Example for while loop
var counter = 5
while counter > 0 {
print("hello")
counter -= 1
}
Example for repeat while loop
var counter = 5
repeat {
print("hello")
counter -= 1
} while counter > 0
Functions
Simple example
func foo() {
print("Fred")
}
foo()
The argument label, the first argument, is just a name to use in place or variable name
func addTwoNumbers(
arg1 para1:Int,
arg2 para2:Int) -> Int {
return para1 + para2
}
let sum = addTwoNumbers(arg: 2)
print(sum)
Collections
Arrays
Using Arrays
var d = ["dog", "cat", "bird"]
// Using standard for loop
for index in 0...(d.count -1) {
print(d[index])
}
// Alternatively
for item in d {
print(item)
}
// Declare empty
var e = [String]()
// Add or Remove
e.append(d)
e.remove(1)
e[0] = "turtle"
Dictionaries
Using a dictionary
// Initialize may values
var responseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
// Initialize empty
var emptyDict: [String: String] = [:]
// Another approach
var carDB = Dictionary[String:String]()
carDB["DTQ 9999"] = "iCar"
carDB["RPA 248"] = "Jag"
// Update
carDB["RPA 248"] = "Red Jag"
// Remove
carDB["RPA 248"] = nil
// Iterate
for (license, car ) in carDB {
print("\(car) has license \(license)")
}
Classes
Class vs Structs
Classes are always passed by reference and Structs are passed by value i.e.
let fred1 = MySalary(100)
let fred2 = fred1
fred1.setSalary(50)
print("Salary \(fred2)")
// Prints 50
Base Claas
class BlogPost {
var title = ""
var body = ""
var counter = 0
func addCounter() {
counter += 1
}
}
let myPost = BlogPost()
myPost.title = "Hello"
myPost.body = "My Body"
myPost.addCounter()
print(myPost.counter)
Optional Properties
We can make properties optional. Like most languages we need to test
class BlogPost {
var title:String?
var body = "hey"
var counter = 0
}
let post = BlogPost()
// We test like this.
if let actualTitle = post.title {
print(actualTitle)
}
// If you know you have a value you can override
post.title = "we have a value"
actualTitle = post.title
print(actualTitle!)
// Or
if actualTitle == nil {
print(actualTitle!)
}
Computed Properties
class BlogPost {
var title:String?
var author:String = "hey"
// Computed Property
if title != nil && author != nil {
return title! + " by " + author
}
else {
return "Something was nil"
}
}
Initialise (Constructor)
We use self in place of this for other languages. Don't forget about argument labels. Note more than one init() permitted
class Person {
var name = ""
var age = 0
func init(_ name: String) {
self.name = name
self.age = 22
}
func init(_ name: String, _ age: Init) {
self.name = name
self.age = age
}
}
var a Person("Bill", 21)
Convenience Initializewr
This allows you to create an initializer where maybe only one parameter is different. It must call a standard (designated) initializer
struct Scene {
var minutes = 0
}
class Movie {
var title: String
var author: String
var date: Int
var scenes: [Scene]
init(title: String, author: String, date: Int) {
self.title = title
self.author = author
self.date = date
scenes = [Scene]()
}
convenience init(title:String) {
self.init(title:title, author: "Unknown", date:2016)
}
func addPage(page: Scene) {
scenes.append(page)
}
}
var myMovie = Movie(title: "my title") // Using convenicence initializer
var otherMovie = Movie(title: "My Title", author: "My Author", date: 12) // Using a long normal initializer
Inheritance
We do this using a colon
class ImprovedBlog : BlogPost {
var title = ""
var body = ""
var numberOfLikes = 0
func addNumberOfLikes() {
numberOfLikes += 1
}
}
Override can be used and you can call the base implementation
class NewCar : Car {
override func drive() {
print("Printing my stuff")
// Print base stuff
super.drive()
}
}