Skip to content

Instantly share code, notes, and snippets.

@pbardea
Last active April 16, 2016 04:48
Show Gist options
  • Save pbardea/e86289692efbbb444df8d31db75383bd to your computer and use it in GitHub Desktop.
Save pbardea/e86289692efbbb444df8d31db75383bd to your computer and use it in GitHub Desktop.
An introduction to programming. In Swift.
// This is a comment. The computer will ignore everything after a double slash.
// ---- Hello World ----
print("Hello world!")
var numPlanetsInSolarSystem = 8
var floatVariableName = 4.3
// Integers
var five = 2 + 3
var three = 7 / 2
var threeAndAHalf = 7.0 / 2.0
// Strings
var myName = "Your Name"
print("Hello! My name is " + myName) // This is how we "add" strings
// Booleans
var wittyBoolName = true
var moonDistance = 370300
var astronautDistance = 295322
var astronautArrivedToMoon = moonDistance <= astronautDistance
// astronautArrivedToMoon is false, becuase the moonDistance is greater than astronautDistance
// Printing
print(4+3)
// Variables
var numberOfPlanets = 9
numberOfPlanets = numberOfPlanets - 1 // numberOfPlanets is now 8
print("We now have \(numberOfPlanets) planets. We'll miss you Pluto.")
numberOfPlanets -= 1 // This is the short form of the line above
// numberOfPlanets is now 7. :o
// We can also double the number of apples:
var numberOfSpaceRockets = 3
print("We start off with \(numberOfSpaceRockets) rockets.")
numberOfSpaceRockets *= 2
print("Woah! We suddenly have \(numberOfSpaceRockets) rockets! Thanks Elon!")
// Constants
let zero = 0 // Will always be 0. Forever.
// If statements
var condition = true
if (condition) {
print("The condition was true")
}
var firstNum = 3
var secondNum = 2
if (firstNum > secondNum) {
print("firstNum is greater than secondNum")
} else {
print("firstNum is less than or equal to secondNum")
}
var cond1 = false
var cond2 = true
if (cond1) {
print("Cond1 is true")
} else if (cond2) {
print("Cond1 is false, but cond2 is true")
} else {
print("Cond1 and cond2 are both false")
}
// While loop
var countdown = 10
while (countdown > 0) {
print(countdown)
countdown -= 1
}
print("Blastoff!")
// Types
var name: String = "My Name"
// Lists
var list = [1,2,3,4]
var anotherlist = 1...4 // A shortcut in Swift that does the same as above
var crew = ["Joe", "Sarah", "Dave"] // Lists can hold anything, as long as they are the same type
crew = ["Joe", "Sarah", "Dave"]
var firstCosmonaut = crew[0] // joe
var secondCosmonaut = crew[1] // sarah
crew = ["Joe", "Sarah", "Dave"]
crew[0] = "Alice"
print(crew)
crew = ["Jason", "Sarah", "Dave"]
crew.append("Cora")
print(crew)
// Dictionaries
var dictionary = ["spaceship":"vehicle to get around space time", "astronaut":"space explorer"]
var spaceShipDefinition = dictionary["spaceship"]
print(spaceShipDefinition) // prints "vehicle to get around space time"
// As long as they are variables, they can be change just like lists
dictionary["astronaut"] = "space wanderer"
// More types
var engineeringTeam: [String] = ["First Member", "Second Member"] // this is an array of strings
var yearsAtNasa: [String:Int] = ["First Member":2, "Second Member":1] // this is a dictionary from strings to ints
var engineersInSpace = [String]()
// For loops
crew = ["Joe", "Sarah", "Dave"]
for crewMember in crew {
print("\(crewMember) is in the crew")
}
// Optionals
var optional: [String]? = nil
// optional!.count // CRASH
optional = ["hi", "hello"]
optional?.count
// Functions
func methodWithFirstArgument(a: Int, andSecondArgument b: Int) {
print("This is a common way to pass \(a) and \(b) into a function in Swift")
}
func introduce(name: String) {
print("Hello my name is " + name)
}
func add(a: Int,_ b: Int) -> Int {
return a + b
}
methodWithFirstArgument(42, andSecondArgument: 13)
introduce("Jonathan")
var seven = add(4, 3)
// Objects
class Person {
var name: String
var age: Int
// The initializer is the function that creates the object
// You need at least one initializer for every class
init(givenName: String, givenAge: Int) {
// We can access the properties of an object using dot notation as below
// "self" is how we refer to the current instance of the class
self.name = givenName
self.age = givenAge
}
func introduce() {
print("Hello! My name is \(self.name) and I am \(self.age) years old. Nice to meet you.")
}
}
var person = Person(givenName: "Alex", givenAge: 16)
person.introduce() // Call a method like this
var personAge = person.age // Access properties like this
person.age += 1 // Change properties like this. Happy birthday!
// Inheritance
class Astronaut: Person {
var yearsInSpace: Int = 0
var authorizedVehicles = ["Space Shuttle", "Soyuz"]
func canFly(vehicle: String) -> Bool {
return authorizedVehicles.contains(vehicle)
}
}
// Protocols
class Vehicle { // A generic Vehicle class
let numberOfWheels: Int
var speed = 0
init(numberOfWheels: Int) {
self.numberOfWheels = numberOfWheels
}
}
protocol Flyable { // A Flyable protocol.
var distanceOffGround: Int { get set }
func land()
}
class SpaceShip: Vehicle, Flyable { // A SpaceShip is a Flyable vehicle
var distanceOffGround: Int = 0
func land() {
self.speed = 0
self.distanceOffGround = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment