Skip to content

Instantly share code, notes, and snippets.

@Adem68
Last active May 26, 2021 07:22
Show Gist options
  • Save Adem68/708e19d1ac402394ff8586f90c813f22 to your computer and use it in GitHub Desktop.
Save Adem68/708e19d1ac402394ff8586f90c813f22 to your computer and use it in GitHub Desktop.
Swift 101 Practice
// Constant
let constVariable = 10
print("const:", constVariable)
// Variable
var myVariable = 10
myVariable = 20
print("myVariable:", myVariable)
// String Interpolation
let width = 94
let label = "The width is \(width)"
print(label)
// Arrays
var shoppingList = ["catfish", "water", "tulips"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
shoppingList.append("blue paint")
print(shoppingList)
print(occupations)
// Empty Array and Empty Dictionary
let emptyArray = [String]()
let emptyDictionary = [String : Float]()
// Control Flows
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
// Optionals
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
print(greeting)
// Handling Optional Values
let nickname: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi, \(nickname ?? fullName)!"
print(informalGreeting)
// Switches
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and moke ants on a log.")
case "cucumber", "watercress":
print("Add some raisins and moke ants on a log.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
// For-in Iteration in Dict - Finding the highest numbers in dict
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5 ,8],
"Square": [1, 4, 9, 16, 25],
]
var largestNumbers = [String: Int]()
for (key, numbers) in interestingNumbers {
largestNumbers[key] = numbers.max()
}
print("Largest numbers in dict:", largestNumbers)
@Adem68
Copy link
Author

Adem68 commented May 26, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment