Skip to content

Swift study notes

jiaxw32 edited this page Apr 22, 2023 · 2 revisions

字符串(String)

  • 字符串中截取子串
var str = "TutorialKart"
 
let start = str.index(str.startIndex, offsetBy: 2)
let end = str.index(str.endIndex, offsetBy: -4)
let range = start..<end
 
let subStr = str[range]
 
print( subStr ) // torial
  • 字符串中插入字符
var str1 = "Hello World!"
var ch :Character = "x"
var i = str1.index(str1.startIndex, offsetBy: 5)
str1.insert(ch, at: i)
print( str1 ) // Hellox World!

注:如果要插入字符的位置超出了字符串的范围,会触发异常

集合(Set)

  • 创建一个空集合

To create an empty set in Swift, use Set<T>() where T is the type of elements we would like to store in this Set.

var names = Set<String>()
print(names)

var names = Set<Int>()
print(names)
  • 获取集合随机元素1
let fruits: Set = ["apple", "banana", "cherry", "mango"]
if let element = fruits.randomElement() {
    print("Random Element : \(element)")
}
  • 获取集合随机元素2

对于空集合,随机元素返回 nil

let fruits = Set<Int>()
let element = fruits.randomElement()
print("Random Element : \(element)") // Random Element : nil
  • 集合超集检测
let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [4, 10]
 
if set1.isSuperset(of: set2) {
    print("set1 is a superset of set2.")
} else {
    print("set1 is not a superset of set2.")
}

函数(func)

  • 可变参数函数

To define a function that can accept one or more values for a parameter, also called a variadic parameter, declare the parameter followed by three period characters ... after the type.

func sum(_ numbers: Int...) {
    var result = 0
    for n in numbers {
        result += n
    }
    print("The sum of numbers is \(result)")
}
 
sum(2, 3)
sum(1, 2, 8, 4, 6)
  • 参数标签

By default the parameter name is used as label. But we can specify a custom label for parameter.

func add(a: Int, b: Int) {
    let result = a + b
    print("The result is \(result)")
}
 
add(a: 4, b: 3)

To define a custom label for function’s parameter(s) in Swift, specify the custom label before the parameter name in the function definition.

func add(firstNumber a: Int, secondNumber b: Int) {
    print(a+b)
}
 
add(firstNumber: 10, secondNumber: 20)
  • 省略参数标签

To call a function with no parameter labels in Swift, place an underscore before that parameter in the function definition.

func greet(_ name: String, country: String) {
    print("Hello \(name)")
    print("Are you from \(country)?")
}
 
greet("Abc", country: "Canada")
  • 参数默认值
func greet(name: String = "User") {
    print("Hello \(name)!")
}
 
greet()
greet(name: "Abc")
  • 引用传参
func incrementByN(x: inout Int, n: Int = 0) {
    x = x + n
}
 
var someNumber = 10
print("someNumber before function call : \(someNumber)")

incrementByN(x: &someNumber, n: 7)
print("someNumber after  function call : \(someNumber)")
  • 将函数赋值给变量
func add(a: Int, b: Int) -> Int {
    return a + b
}

//declare variable
var addFunction: (Int, Int) -> Int
//assign function to variable
addFunction = add

//call function using variable
let result = addFunction(5, 4)
print("Result is \(result)")
  • 将函数作为返回值
func calculate() -> (Int, Int) -> Int {
 
    func addition(a: Int, b: Int) -> Int {
        return a + b
    }
   
    return addition
}
 
//variable to store function
var myFunc: (Int, Int) -> Int
 
myFunc = calculate()
print(myFunc(2, 5))

协议

协议声明

protocol Mailable {
	var width: Double { get, set }
	var height: Double { get, set }
}

{ get set } should not have a comma inside.


protocol Strokeable {
	fluffiness: Int { get }
}

fluffiness should be declared using var.


protocol Buildable {
	var numberOfBricks: Int { set }
	var materials: [String] { set }
}

It's not possible to create set-only properties in Swift. Protocols can mark properties as read-only or read-write.


protocol HasPages {
	var pageCount: Int
}
protocol HasTableOfContents {
	var titles: [String]
}
protocol Book: HasPages, HasTableOfContents {
	var author: String
}

Correct! All three properties here must have { get } or { get set } after them.

协议继承

protocol Buyable {
	var cost: Int
}
protocol Sellable {
	func findBuyers() -> [String]
}
protocol FineArt: Buyable, Sellable { }

that's not correct. The cost property must have { get } or { get set } after it.

扩展属性

Swift doesn’t let you add stored properties in extensions, so you must use computed properties instead. For example, we could add a new isEven computed property to integers that returns true if it holds an even number:

extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

协议总结

  1. Protocols describe what methods and properties a conforming type must have, but don’t provide the implementations of those methods.
  2. You can build protocols on top of other protocols, similar to classes.
  3. Extensions let you add methods and computed properties to specific types such as Int.
  4. Protocol extensions let you add methods and computed properties to protocols.
  5. Protocol-oriented programming is the practice of designing your app architecture as a series of protocols, then using protocol extensions to provide default method implementations.
Clone this wiki locally