當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift Result map(_:)用法及代碼示例

實例方法

map(_:)

返回一個新結果,使用給定的轉換映射任何成功值。

聲明

func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> Result<NewSuccess, Failure>

返回值

Result 實例,如果此實例表示成功,則將 transform 的評估結果作為新的成功值。

參數

transform

采用此實例的成功值的閉包。

詳述

當您需要轉換 Result 實例的值時,使用此方法表示成功。以下示例將結果的整數成功值轉換為字符串:


func getNextInteger() -> Result<Int, Error> { /* ... */ }


let integerResult = getNextInteger()
// integerResult == .success(5)
let stringResult = integerResult.map({ String($0) })
// stringResult == .success("5")

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result map(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。