Fullstar

Archives

  • December 2025
  • August 2024
  • July 2024
  • February 2024
  • November 2023
  • August 2023
  • July 2023
  • January 2023
  • November 2022
  • October 2022
  • September 2022
  • February 2022
  • January 2022
  • September 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020

Categories

  • Code
  • Lens
  • Life
0
Fullstar
  • Code

Swift Learning Log

  • August 31, 2023
  • Brandon

Looking for a Shorter Overview?

AI Summary

Swift fundamentals are collected in runnable examples, from initialized variables, optionals, and collections to closures. It also covers value versus reference semantics through structs and classes, plus enums, inheritance, and protocols.

Key Moments

AI-generated
1

Parameter initialization and optionals

Initialize Swift constants and variables before use, then represent absent values with Optional and safely access related properties through optional chaining or guard.
2

String and collection operations

Use String indices instead of integer subscripts, and declare arrays, dictionaries, and sets with explicit element types when needed.
3

Functions and closures

Pass functions as values, return closures, use variadic and inout parameters, and progressively shorten closure syntax for collection operations.
4

Value and reference object types

Structures copy values when passed, whereas classes use reference semantics; enums model associated or raw values, and protocols define required interfaces.
Total
0
Shares
0
0
0

参数声明

/* Swift中所有参数在使用前必须已经初始化 */
let a = 10
var b = "abc"
var c = 1, d = 2, e = 3
var name: String = "abc"

/* alias */
typealias AudioSample = UInt16

/* tuple */
var nameRankandSerial = ("Crunch", "Captain", 34592)
let (name, rank, serialnum) = nameRankandSerial
print(rank + " " + name + ", \(serialnum)")
var pair : (Int, String) = (1, "two")

/* 0b: 2, 0o: 8, 0x: 16 */
let a = 0xF

/* computed variables */
var now : String {
    get {
        return NSDate().description
    }
}

struct abStruct {
    var a : Float
    
    init(a: Float) {
        self.a = a
    }
    var b : Float {
        get {
            return a * 10
        }
        set {
            self.a = newValue / 10
        }
    }
}

/* setter observer */
var saveNew = ""
var saveOld = ""
var s: String = "whatever" {
    /* call before set */
    willSet {
        saveNew = newValue
    }
    /* call after set */
    didSet {
        saveOld = oldValue
        s = "override"
    }
}

/* optional */
var a: String? = "abc"
var b: Optional<String> = "abc"
var c: Int("abc")

/* the Optional type is implemented as an enumeration with two cases - Optional.none and Optional.some(wrapped) */
let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none

/* optional chaining */
class Person {
    var residence: Residence?
}
class Residence {
    var numberOfRooms: Int = 1
}
let john = Person()
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}

/* guard statement */
func testDog(dogName: String?) -> String {
    guard let brier = dogName else {
        return "no value"
    }
    return brier
}

String and Collection types

/* String Indices */
var classInfo = "ECE 564"
classInfo[classInfo.startIndex]
classInfo[classInfo.index(before: classInfo.endIndex)]
classInfo[classInfo.index(classInfo.startIndex, offsetBy: 4)]

for index in classInfo.indices {
    print("\(classInfo[index]) ", terminator: "")
}

/* array */
var MyArray: [String] = ["one", "two", "three"]
var someInts = [Int]()
var someMoreInts = [Int](repeating: 5, count: 5)

/* dictionaries */
var MyDict: [String: String] = ["Name":"Ric", "Title":"Prof"]
var namesOfIntegers = [String: String]()
namesOfIntegers = [:]

/* sets */
var letters2 = Set<Character>()
var allMyPets: Set<String> = ["Brier", "Bentley", "Kenny", "Minnie", "Niki"]

Closures

/* Closures are reference types, and it capture and store references to any constants and variables */
/* that were in scope when the closure was defined.*/
/* 3 types of closures: Global and Nested functions, Closure Expressions (Anonymous functions) */

/* Global function */
func someFunction(argumentLabel parameterName: Int) -> String {
    print("inside the function we use parameterName: \(parameterName)")
    return "Hi"
}
someFunction(argumentLabel: 5)

/* function can be used as parameter or return value */
func sayGreeting(greetPerson: (String, String) -> String) -> String {
    //...
}

func boolToString (isOdd: Bool) -> () -> String {
    return {
        if isOdd == true {
            return "It is Odd"
        } else {
            return "It is Even"
        }
    }
}
let result = boolToString(isOdd: false)
result()

func minMax(array: [Int]) -> (min: Int, max: Int) {
    return (min, max)
}
let minMaxAns = minMax(array: [3, 7] )

print("\(minMaxAns.min) is the min and \(minMaxAns.max) is the max")

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5, 6, 7, 8, 9)

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let tempA = a
    a = b
    b = tempA
}
var a = 5
var b = 6
swapTwoInts(&a, &b)

/* Nested function: function exists inside the body of another function */
var baseCount = 1  // Global variable

func outerFunction(_ startCount: Int) {
    let anotherCounter = baseCount + 1
    func innerFunction(){
        let finalCounter = anotherCounter + startCount + 1
    }
    innerFunction() 
}

outerFunction(5)

/* Closure Expression */
func forwards(s1: String, s2: String) -> Bool {
    return s2 > s1
}
var ans = names.sorted(by: forwards)

var ans = names.sorted(by: { (s1: String, s2: String) -> Bool in return s2> s1 })

var ans = names.sorted(by: { s1, s2 in return s1 > s2 })

var ans = names.sorted(by: { s1, s2 in s2 > s1 })

var ans = names.sorted(by: { $0 > $1 })

var ans = names.sorted(by: > )

/* Trailing Closures: useful when closure is too long to inline in single line */
let digitNames = [
    0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
let numbers = [16, 58, 510]

let strings = numbers.map {   //no parentheses
    (value) -> String in
    var output = ""
    var number = value
    while number > 0 {
        output = digitNames[number % 10]! + output
        number /= 10
    }
    return output
}
print(strings)

Object Types

Structures are value types – always copied when they are passed, classes are passed by reference!

/* struct */
struct Dog {
    var breed: String
    var name: String = "Fido"
    
    func bark() { return }
    init() {
        breed = "Unknown"
    }
}

/* enum */
/* enum with associated value */
enum Reference {
    case Book(Int)
    case Magazine(String)
}

let footnote1 = Reference.Book(9780201633610)
var footnote2 = Reference.Magazine("Time, August 26, 2019")

switch footnote2 {
case .Book(let val):
    print(val)
case .Magazine(let val):
    print(val)
}

/* enum with raw value, type should be the same, if not specify there would be default value */
enum Letters: String {
    case a = "Alpha"
    case b = "Bravo"
    case c = "Charlie"
}

let newEnum = Letters.c
print(newEnum)
print(newEnum.rawValue)

/* class */
class Pet {
    var legs : Int = 4
    var name : String = "none"
    
    init() {}
    
    init(legs: Int, name: String)
    {
        self.legs = legs
        self.name = name
    }
}

class Horse : Pet {
    var breed : String = ""
    init(name: String, breed: String) {
        self.breed = breed
        super.init(legs: 4, name: name)
    }
}

/* protocol */
public protocol CustomStringConvertible {
    var description: String { get }
}
struct Point: CustomStringConvertible {
            let x: Int, y: Int
            var description: String {
                return "The point is (\(x), \(y))"
            }
}

Related Posts

AI-generated

AOP reading notes

From fork and execve to virtual dispatch and exception unwinding, these notes capture the C++ rules that shape program startup, file handling, templates, inheritance, and…
49.1% match October 10, 2022

Golang入门

从函数闭包、切片映射到接口、错误处理与并发通信,这份速查式笔记用代码串起语言的核心概念,并说明信道和互斥锁如何协调多个执行任务。
45.9% match February 4, 2024

Questions Answered

AI-generated

How do Swift optionals safely handle missing values?

Use optional types, optional chaining, and guard binding to unwrap values safely.

How are strings and collections declared in Swift?

Use String indices plus typed arrays, dictionaries, and sets for stored values.

How do closures capture and process values in Swift?

Closures retain scoped references and can be passed, returned, or written inline.

When should Swift use structs instead of classes?

Use structs for copied value semantics and classes for shared reference semantics.

Next Up

C++ Core Mechanics
并发核心语法
核心算法伪代码
掌握小组件刷新
Total
0
Shares
Share 0
Tweet 0
Pin it 0
Brandon

Previous Article
  • Code

English Learning – Food Related

  • August 31, 2023
  • Brandon
View Post
Next Article
  • Code

Setting Up and Maintaining a Ubuntu Environment for My Home Server

  • November 24, 2023
  • Brandon
View Post
You May Also Like
View Post
  • Code

Letta部署记录

  • Brandon
  • December 26, 2025
View Post
  • Code

WordPress 后台任务利器:使用 BGRunner 构建可靠的异步处理

  • Brandon
  • December 14, 2025
View Post
  • Code

WordPress image offload

  • Brandon
  • December 14, 2025
View Post
  • Code

ComfyUI应用手册

  • Brandon
  • December 6, 2025
View Post
  • Code

Leetcode Java常用代码

  • Brandon
  • February 17, 2024
View Post
  • Code

Golang入门

  • Brandon
  • February 4, 2024
View Post
  • Code

Setting Up and Maintaining a Ubuntu Environment for My Home Server

  • Brandon
  • November 24, 2023
View Post
  • Code

English Learning – Food Related

  • Brandon
  • August 31, 2023

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Fullstar

Input your search keywords and press Enter.

AOP reading notes

Golang入门

算法伪代码

Private: Swift Widget Tutorial

嵌入式程序设计基础(ARM9)

ARM9指令系统常用指令

UP NEXT

AOP reading notes

49.1% match October 10, 2022 0