Swift Learning Log

参数声明

/* 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 post

  1. 链接原理浅析(基于Unix ELF文件格式)

    2022-01-23

  2. Linux运行程序与shell编程

    2020-12-08

  3. AOP reading notes

    2022-10-10

  4. Golang入门

    2024-02-04

There are no comment yet.

COMMENT

Take a Coffee Break

Recommend post

  1. 常用工具指令

    2022-09-18

Category list

ABOUT

Welcome to FullStar, a captivating online destination where the realms of software development and personal reflections intertwine.

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Life Logs

  1. 回首

    2023-07-14

Return Top