Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@trozware
Last active January 8, 2018 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trozware/bc582b9a49feb7bbd3adce8ea049c9d3 to your computer and use it in GitHub Desktop.
Save trozware/bc582b9a49feb7bbd3adce8ea049c9d3 to your computer and use it in GitHub Desktop.
NCSS-2018-Swift
// https://eval.weheartswift.com/eval/playground/swift-sandbox
// https://swift.sandbox.bluemix.net/#/repl
// VARIABLES
////////////
var hitPoints = 29
print(hitPoints)
hitPoints = 12
print(hitPoints)
/////////////////////////////////////////////////////////////
// CONSTANTS
////////////
let playerName = "Maximus"
print(playerName)
// un-comment next line to see error
// playerName = "Minimus"
/////////////////////////////////////////////////////////////
// NAMING
/////////
// Valid Names
let myVariable = 42
let next_number = 43
let 💩 = "pile of poo"
let phase_1_active = true
// Invalid names - un-comment these lines to see errors
// let first number = 37
// let 2Much = 4_000_000
// let a+b = "AB"
/////////////////////////////////////////////////////////////
// TYPES
////////
let anotherPlayerName = "Shocker"
print(type(of: anotherPlayerName))
var weaponStrength = 104
print(type(of: weaponStrength))
let damagePerSecond = 13.54
print(type(of: damagePerSecond))
var isDead = false
print(type(of: isDead))
/////////////////////////////////////////////////////////////
// COMMENTS
///////////
// This is a single line comment
let x = 3 // Comment on the end of a line
/*
This is a multi-line comment.
You start and end these with
slashes & asterisks.
*/
// STRINGS
//////////
let string1 = "I am a mage!"
print(string1)
let robotHead = "🤖"
print("I am fighting a demonic \(robotHead).")
let robotHitPoints = 427
print("The robot has \(robotHitPoints) hit points!")
let spellName = "Fire"
for character in spellName.characters {
print(character)
}
print(spellName.characters.count)
print(spellName.isEmpty)
/////////////////////////////////////////////////////////////
// SWIFT 4 STRINGS - WILL NOT WORK IN SANDBOX
/////////////////////////////////////////////
/*
for character in spellName {
print(character)
}
print(spellName.count)
print(spellName.isEmpty)
let greeting = "I am a fire mage"
let firstWord = greeting.prefix(4)
print(firstWord)
let lastWords = greeting.suffix(9)
print(lastWords)
let words = greeting.components(separatedBy: " ")
print(words)
*/
/////////////////////////////////////////////////////////////
// ARRAYS
/////////
var classTypes = ["Mage", "Warrior", "Priest"]
print(classTypes)
classTypes.append("Rogue")
print(classTypes)
let warriorIndex = classTypes.index(of: "Warrior") // 1
let warlockIndex = classTypes.index(of: "Warlock") // nil
classTypes.remove(at: 1)
print(classTypes)
/////////////////////////////////////////////////////////////
// SETS
///////
var raceSet: Set = ["Human", "Dwarf", "Orc"]
print(raceSet)
raceSet.insert("Troll")
print(raceSet)
raceSet.insert("Dwarf")
print(raceSet)
raceSet.remove("Goblin")
print(raceSet)
/////////////////////////////////////////////////////////////
// DICTIONARIES
///////////////
var weaponSkills = [
"Sword": 7, "Staff": 36, "Bow": 17
]
print(weaponSkills)
weaponSkills["Axe"] = 13
print(weaponSkills)
let staffSkills = weaponSkills["Staff"]
print("I have \(staffSkills) staff skill points.")
let maceSkills = weaponSkills["Perth"]
print("I have \(maceSkills) mace skill points.")
weaponSkills.removeValue(forKey: "Sword")
print(weaponSkills)
weaponSkills.removeValue(forKey: "Crossbow")
print(weaponSkills)
/////////////////////////////////////////////////////////////
// IF
/////
var enemyStrength = 37
if enemyStrength > 30 {
print("Too big for me to fight.")
}
/////////////////////////////////////////////////////////////
// IF ... ELSE
//////////////
var anotherEnemy = 24
if anotherEnemy > 30 {
print("I should run away.")
} else {
print("I think I can beat this enemy.")
}
/////////////////////////////////////////////////////////////
// IF ... ELSE IF ... ELSE
//////////////////////////
var enemyIsDead = false
var enemyPetIsDead = true
if enemyIsDead == true {
print("I WIN!!!!")
} else if enemyPetIsDead == true {
print("Making progress.")
} else {
print("This could be a long fight...")
}
/////////////////////////////////////////////////////////////
// SWITCH
/////////
var newDirection = "S"
switch newDirection {
case "N":
print("🚶‍♀️ North")
case "E":
print("🚶‍♀️ East")
case "S":
print("🚶‍♀️ South")
case "W":
print("🚶‍♀️ West")
default:
print("Just wandering around...")
}
/////////////////////////////////////////////////////////////
// FOR
//////
for i in 0 ..< 3 {
print(i)
}
var classTypes = ["Mage", "Warrior", "Priest"]
for type in classTypes {
print(type)
}
/////////////////////////////////////////////////////////////
// WHILE
////////
var enemyHealth = 4
while enemyHealth > 0 {
print(enemyHealth)
enemyHealth -= 1
}
/////////////////////////////////////////////////////////////
// REPEAT ... WHILE
///////////////////
var myStamina = 0
repeat {
print(myStamina)
myStamina += 2
} while myStamina < 10
/////////////////////////////////////////////////////////////
// LOOPING THROUGH DICTIONARIES
///////////////////////////////
var weaponSkills = [
"Sword": 7, "Staff": 36, "Bow": 17
]
var totalSkills = 0
for (key, value) in weaponSkills {
print("My skill in \(key) is \(value).")
totalSkills += value
}
let averageSkill = totalSkills /
weaponSkills.count
print(averageSkill)
/////////////////////////////////////////////////////////////
// SIMPLE FUNCTION
//////////////////
func showCharacterName() {
print("My name is Maximus")
}
showCharacterName()
/////////////////////////////////////////////////////////////
// FUNCTION PARAMETERS
//////////////////////
func showCharacterName(name: String) {
print("My name is \(name)")
}
showCharacterName(name: "Griselda")
func showCharacter(name: String,
hitPoints: Int) {
print("My name is \(name)")
print(" and I have \(hitPoints) hit points.")
}
showCharacter(name: "Bob", hitPoints: 28)
/////////////////////////////////////////////////////////////
// BETTER FUNCTION CALLS
////////////////////////
func changeHitPoints(newHitPoints: Int) {
print("Changing hit points to \(newHitPoints)")
}
changeHitPoints(newHitPoints: 12)
func adjustHitPoints(to newHitPoints: Int) {
print("Adjusting hit points to \(newHitPoints)")
}
adjustHitPoints(to: 34)
/////////////////////////////////////////////////////////////
// RETURNING VALUES
///////////////////
func square(of number: Int) -> Int {
return number * number
}
let result = square(of: 4)
print(result)
/////////////////////////////////////////////////////////////
// UN-NAMED PARAMETERS
//////////////////////
func convertCtoF(_ degreesC: Double) -> Double {
let degreesF = degreesC / 5 * 9 + 32
return degreesF
}
let boiling = convertCtoF(100)
let human = convertCtoF(37)
print(boiling)
print(human)
/////////////////////////////////////////////////////////////
// DEFAULT PARAMETERS
/////////////////////
func showInfo(_ name: String,
useUpperCase: Bool = false) {
var info = "My name is \(name)."
if useUpperCase {
info = info.uppercased()
}
print(info)
}
showInfo("Griselda", useUpperCase: true)
showInfo("Bob")
/////////////////////////////////////////////////////////////
// OPTIONAL VARIABLES
/////////////////////
var characterDescription: String?
print(characterDescription)
characterDescription = "Charming but deadly."
print(characterDescription)
/////////////////////////////////////////////////////////////
// UN-WRAPPING OPTIONALS
////////////////////////
var bonusPoints: Int?
// Un-comment next line to see error
// let triple1 = bonusPoints * 3
// error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
// Un-comment next line to see error
// let triple2 = bonusPoints! * 3
// fatal error: unexpectedly found nil while unwrapping an Optional value
bonusPoints = 7
let triple3 = bonusPoints! * 3
print(triple3)
/////////////////////////////////////////////////////////////
// CHECKING FOR OPTIONALS
/////////////////////////
var otherDescription: String?
if let description = otherDescription {
print("\(description)")
} else {
print("No description available.")
}
/////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment