Last active
May 26, 2021 07:22
-
-
Save Adem68/708e19d1ac402394ff8586f90c813f22 to your computer and use it in GitHub Desktop.
Swift 101 Practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm using The Swift Programming Language (Swift 5.4) book