其他分享
首页 > 其他分享> > 【swift】guard、if let

【swift】guard、if let

作者:互联网

guard

示例代码

func peripheralViewModel(at row: Int) -> SILDiscoveredPeripheralDisplayDataViewModel? {
        guard row < discoveredPeripheralsViewModels.count else { return nil }
        return discoveredPeripheralsViewModels[row]
    }

说明:把 guard 当作是断言会更好理解

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
}

说明

示例代码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!)
}

说明

标签:示例,peripheral,guard,let,swift,discoveredPeripheral,row
来源: https://www.cnblogs.com/cchHers/p/15811719.html