在 swift 中将元组解构为函数参数

问题描述 投票:0回答:2

考虑一个基本的

swift
函数来分隔完全限定路径的组件:

public static func splitPath(_ path: String)  -> 
      (directory: String,
       filenameOnly: String, 
       ext: String) {
  let url = URL(fileURLWithPath: path)
  return (url.deletingLastPathComponent().path, 
          url.deletingPathExtension().lastPathComponent, url.pathExtension)
}

现在考虑一个方法

readFile
,它采用相同数量和类型的参数:

  public static func readFile(_ subDir: String, 
      _ fname: String = "", 
      _ ext: String = "") throws -> String { ... }

如何在给定返回的元组

readFile
的情况下直接调用
splitPath()
方法?

    let fcontents = try readFile(splitPath(path))

在其他语言中,这是通过可变参数的

splat
执行的。

swift
2个回答
0
投票

此功能称为

implicit
tuple
splat
已在
swift 3
中删除。如果您想了解更多详细信息,可以在这里

但是你可以像这样使用元组作为函数参数

public  func readFile( _ tuple: (directory:String, filenameOnly:String , ext:String )) throws -> String { //... }

0
投票

还有另一种方法来填充元组

func call<Input, Output>(_ block: (Input) -> Output, with input: Input) -> Output {
    block(input)
}

所以你可以像这样使用它

let tuple = (2, 4)
let result = call(+, with: tuple)
print(result) // print 6

此外,您可以使用运算符功能使其更具可读性

precedencegroup TupleSplattingPrecedence {
    higherThan: CastingPrecedence
    lowerThan: RangeFormationPrecedence
    associativity: left
}

infix operator <- : TupleSplattingPrecedence
func <- <Input, Output>(block: (Input) -> Output, tuple: Input) -> Output {
    block(tuple)
}

let add: (Int, Int) -> Int = { $0 + $1 }
let tuple = (2, 3)
print(add <- tuple) // print 5

当我们使用 curry 函数时,这个语法会很有用

let curryAdd: (Int) -> (Int) -> Int = { a in
        { b in
            a + b
        }
    }
print(curryAdd <- 3 <- 4) // print 7
© www.soinside.com 2019 - 2024. All rights reserved.