let val = (Double)6
Reference: The Swift Programming Language: Language Guide: The Basics: Constants and Variables
let x = 5
guard x == 5 { return }
guard is missing the elseguard is missing a thenReference: The Swift Programming Language: Language Guide: Control Flow: Early Exit
enum Direction {
case north, south, east, west
}
StringAnyIntReference: The Swift Programming Language: Language Guide: Enumerations: Raw Values
Reference: Apple Developer: Documentation: Dispatch: Dispatch Group
let val = 5
print("value is: \(val)")
Reference: The Swift Programming Language: Language Guide: Strings and Characters: String Interpolation
vals after this code is executed?var vals = [10, 2]
vals.sort { (s1, s2) -> Bool in
s1 > s2
}
[10, 2][2, 10]nilReference: Apple Developer: Documentations: Swift: Array: sort()
typealias Thing = [String: Any]
var stuff: Thing
print(type(of: stuff))
Dictionary<String, Any>DictionaryErrorThingReference: The Swift Programming Language: Language Reference: Types: Type Identifier
let x = ["1", "2"].dropFirst()
let y = x[0]
12nilexplanation
dropFirst() from Swift.Collection.Array returns a type of ArraySlice<Element>
as in the documentation pages:
@inlinable public func dropFirst(_ k: Int = 1) -> ArraySlice<Element>
The ArraySlice type makes it fast and efficient for you to perform operations on sections of a larger array. Instead of copying over the elements of a slice to new storage, an ArraySlice instance presents a view onto the storage of a larger array. And because ArraySlice presents the same interface as Array, you can generally perform the same operations on a slice as you could on the original array.
Slices Maintain Indices
Unlike Array and ContiguousArray, the starting index for an ArraySlice instance isn’t always zero. Slices maintain the same indices of the larger array for the same elements, so the starting index of a slice depends on how it was created, letting you perform index-based operations on either a full array or a slice.
The above code returns a slice of value ["2"] but the index did not change. let y = x[1] would give the expected result.
To safely reference the starting and ending indices of a slice, always use the startIndex and endIndex properties instead of specific values.
Reference
var test = 1 == 1
trueYES1Reference: The Swift Programming Language: Language Guide: Basic Operators: Comparison Operators
var x: Int?
let y = x ?? 5
50nilReference: The Swift Programming Language: Language Guide: Basic Operators: Nil-Coalescing Operators
func add(a: Int, b: Int) -> Int { return a+b }
Int(Int, Int) -> IntInt<Optional>Reference: The Swift Programming Language: Language Guide: Functions: Function Types
func myFunc(_ a: Int, b: Int) -> Int {
return a + b
}
myFunc(5, b: 6)myFunc(5, 6)myFunc(a: 5, b: 6)myFunc(a, b)Encodable and DecodableReferences:
let value1 = "\("test".count)"
StringIntnulltest.countReference: The Swift Programming Language: Language Guide: Strings and Characters: String Interpolation
Reference: The Swift Programming Language: Language Guide: Closures: Escaping Closures
class Person {
var name: String
var address: String
}
var name is not formatted correctly.address is a keyword.Reference: The Swift Programming Language: Language Guide: Initialization: Class Inheritance and Initialization
let names = ["Bear", "Joe", "Clark"]
names.map { (s) -> String in
return s.uppercased()
}
["BEAR", "JOE", "CLARK"]["B", "J", "C"]["Bear", "Joe", "Clark"]let val = 5
IntitemNumberIntReference: The Swift Programming Language: Language Guide: The Basics: Type Safety and Type Inference
extension String {
var firstLetter: Character = "c" {
didSet {
print("new value")
}
}
}
didSet takes a parameter.c is not a character.Reference: The Swift Programming Language: Language Guide: Extensions: Computed Properties
newOld value callsReference: The Swift Programming Language: Language Guide: Properties
self.callback = {
self.attempts += 1
self.downloadFailed()
}
self inside the closure causes retain cycle.var vals = Set<String> = ["4", "5", "6"]
vals.insert("5")
Reference: The Swift Programming Language: Language Guide: Collection Types: Sets
weak or unowned.lazy.Reference: The Swift Programming Language: Language Guide: Automatic Reference Counting
if let s = String.init("some string") {
print(s)
}
String initializer does not return an optional.String.= is not a comparison.Reference: The Swift Programming Language: Language Guide: The Basics: Optionals
typealias CustomClosure = () -> ()typealias CustomClosure { () -> () }typealias CustomClosure -> () -> ()typealias CustomClosure -> () {}Reference: The Swift Programming Language: Language Reference: Declarations: Type Alias Declaration
selfinstanceclassthisReference: The Swift Programming Language: Language Guide: Methods: Instance Methods
Reference: The Swift Programming Language: Language Guide: Structures and Classes
var strings = [1, 2, 3]
strings.append(4)strings.insert(5, at: 1)strings += [5]Reference: The Swift Programming Language: Language Guide: Collection Types: Arrays
for i in 0...100 {
print(i)
}
References:
Reference: The Swift Programming Language: Language Guide: Type Casting: Type Casting for Any and AnyObject
let names = ["Larry", "Sven", "Bear"]
let t = names.enumerated().first().offset
References:
let vt = (name: "ABC", val: 5)
let test = vt.0
ABC05nameReferences:
class LSN: MMM {
}
Reference: The Swift Programming Language: Language Guide: Inheritance: Subclassing
var userLocation: String = "Home" {
willSet(newValue) {
print("About to set userLocation to \(newValue)...")
}
didSet {
if userLocation != oldValue {
print("userLocation updated with new value!")
} else {
print("userLocation already set to that value...")
}
}
}
userLocation = "Work"
About to set userLocation to Work... userLocation updated with new value!About to set userLocation to Work... userLocation already set to that value...About to set userLocation to Home... userLocation updated to new value!ErrorReference: The Swift Programming Language: Language Guide: Properties: Property Observers
Reference: The Swift Programming Language: Language Guide: Initialization: Class Inheritance and Initialization
throws.Reference: Apple Developer: Documentation: Dispatch: DispatchQueue
let x = ["a", "b", "c"]
String[]Array<String>Set<String>Array<Character>Reference: The Swift Programming Language: Language Guide: Collection Types: Arrays
oThings after this code is executed?let nThings: [Any] = [1, "2", "three"]
let oThings = nThings.reduce("") { "\($0)\($1)" }
Reference: Apple Developer: Documentation: Swift: Array: reduce(_:_:)
!trytry?try!?tryReference: The Swift Programming Language: Language Guide: Error Handling: Handling Errors
protocol TUI {
func add(x1: Int, x2: Int) -> Int {
return x1 + x2
}
}
add is a reserved keyword.Reference:
wheels and doors examples of?class Car {
var wheels: Int = 4
let doors = 4
}
Reference:
deinitinit?initReference:
let dbl = Double.init("5a")
print(dbl ?? ".asString()")
five5a.asString()5Reference:
this and toThat examples of?func add(this x: Int, toThat y: Int) { }
Reference: The Swift Programming Language: Language Guide: Functions
for (key, value) in [1: "one", 2: "two"] {
print(key, value)
}
Reference: The Swift Programming Language: Language Guide: Control Flow: For-In Loops
XCTest@testableXCTAssertReference:
class Square {
var height: Int = 0
var width: Int {
return height
}
}
Reference:
let vals = ("val", 1)
Reference:
var x = 5
x = 10.0
x is undefinedx is a constantx has no typeReference: The Swift Programming Language: Language Guide: The Basics
var items = ["a": 1, "b": 2, "c": "test"] as [String: Any]
items["c"] = nil
print(items["c"] as Any)
References:
let val = 5.0 + 10
val is a constant and cannot be changed5.0 and 10 are different typesReference: The Swift Programming Language: Language Guide: The Basics: Type Safety and Type Inference
struct Test {
var score: Int
var date: Date
}
Reference: The Swift Programming Language: Language Guide: Initialization
let x = try? String.init("test")
print(x)
References:
var vals = [1, 2, 3]
vals.sort { $0 < $1 }vals.sort { (s1, s2) in s1 < s2 }vals.sort(by: <)Reference: Apple Developer: Documentation: Swift: Array: sort()
Reference: Apple Developer: Documentation: Dispatch: DispatchQueue: async(group:qos:flags:execute:)
Reference: The Swift Programming Language: Language Guide: Deinitialization
String?Optional[String][String]??StringReference: The Swift Programming Language: Language Guide: The Basics: Optionals
for i in ["0", "1"] {
print(i)
}
Reference: The Swift Programming Language: Language Guide: Control Flow: For-In Loops
let names = ["Bear", "Tony", "Svante"]
print(names[1] + "Bear")
References:
let name: String?
name can hold only a string value.name can hold either a string or nil value.let constants.name.Reference: The Swift Programming Language: Language Guide: The Basics: Optionals
val after this code is executed?let i = 5
let val = i * 6.0
Reference: The Swift Programming Language: Language Guide: The Basics: Type Safety and Type Inference
enum Positions: Int {
case first, second, third, other
}
print (Positions.other.rawValue)
Reference: The Swift Programming Language: Language Guide: The Basics: Raw Values
"t".forEach { (char) in
print(char)
}
References:
let s1 = ["1", "2", "3"]
.filter { $0 > "0" }
.sorted { $0 > $1 }
print(s1)
References:
Reference: The Swift Programming Language: Language Guide: Enumerations: Associated Values
class AmP: MMM, AOM { }
References:
let numbers = [1, 2, 3, 4, 5, 6].filter { $0 % 2 == 0 }
vals in this code?let vals = ["a", 1, "Hi"]
Reference: The Swift Programming Language: Language Guide: Type Casting
x in tuple vtlet vt = (name: "ABC", val: 5)
_, x) = vtReference: The Swift Programming Language: Language Guide: The Basics: Tuples
let x = try? String.init(from: decoder)
Reference: The Swift Programming Language: Language Guide: Error Handling: Handling Errors
let loopx = 5
repeat {
print (loopx)
} while loopx < 6
Reference: The Swift Programming Language: Language Guide: Control Flow: While Loops
var vals: Set<String> = ["4", "5", "6"]
vals.insert("5")
Reference: The Swift Programming Language: Language Guide: Collection Types: Sets
class LSN: MMM{ }