實例方法
flat
flatMap(_:)
返回一個新結果,使用給定的轉換映射任何成功值並解包生成的結果。
聲明
func flatMap<NewSuccess>(_ transform: (Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure>
返回值
Result
實例,來自閉包或之前的 .failure
。
參數
transform
一個獲取實例成功值的閉包。
詳述
當您的轉換產生另一個 Result
類型時,使用此方法可避免嵌套結果。
在此示例中,請注意將map
和flatMap
與返回結果類型的轉換一起使用的結果不同。
func getNextInteger() -> Result<Int, Error> {
.success(4)
}
func getNextAfterInteger(_ n: Int) -> Result<Int, Error> {
.success(n + 1)
}
let result = getNextInteger().map({ getNextAfterInteger($0) })
// result == .success(.success(5))
let result = getNextInteger().flatMap({ getNextAfterInteger($0) })
// result == .success(5)
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift Result publisher用法及代碼示例
- Swift Result map(_:)用法及代碼示例
- Swift Result get()用法及代碼示例
- Swift Result mapError(_:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result flatMap(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。