guard
示例代码
func peripheralViewModel(at row: Int) -> SILDiscoveredPeripheralDisplayDataViewModel? {
guard row < discoveredPeripheralsViewModels.count else { return nil }
return discoveredPeripheralsViewModels[row]
}
说明:把 guard 当作是断言会更好理解
- 如果断言为yes,则继续往下执行,如果断言为no,则走else里面的代码
if let
示例代码1
if let firstIndex = firstIndexOfReplacement(device: peripheral) {
let replacement = replaceViewModels[firstIndex]
if (allDiscoveredPeripheralsViewModels[index].discoveredPeripheral.isFavourite) {
replacement.discoveredPeripheral.isFavourite = true
}
allDiscoveredPeripheralsViewModels[index] = replacement
}
说明
- if let 主要是判断后面的可选项类型是否有值,如果有值就将该值赋值给这个常量
示例代码2
if let discoveredPeripheral = peripheralViewModel.discoveredPeripheral,
discoveredPeripheral.isConnectable,
centralManager.canConnect(to: discoveredPeripheral) {
centralManager.connect(to: discoveredPeripheral)
isConnecting.updateValue(true, forKey: discoveredPeripheral.peripheral!)
} else {
isConnecting.updateValue(false, forKey: peripheralViewModel.discoveredPeripheral.peripheral!)
}
说明
- if let 后面可以有多个需要判断的条件