我正在 Linux 上试验一个简单的命令行应用程序,我有以下代码。
代码
import Glibc
import Foundation
infix operator |>> { associativity left }
func |>> <A, B, C>(f: A -> B, g: B -> C) -> A -> C {
return { x in g(f(x)) }
}
func readln(max:Int = 8192) -> String? {
assert(max > 0, "max must be between 1 and Int.max")
var buf:Array<CChar> = []
var c = getchar()
while c != EOF && c != 10 && buf.count < max {
buf.append(CChar(c))
c = getchar()
}
buf.append(CChar(0))
return buf.withUnsafeBufferPointer { String.fromCString($0.baseAddress) }
}
func myPrint(str: String?) {
guard let unwrapped = str else {
return;
}
print("\(unwrapped)")
}
//This compiles & runs
var input = readln()
myPrint(input)
//this does not!
let main = readln |>> myPrint
main()
编译器输出
/home/**********/SwiftProjects/HelloPackage/Sources/main.swift:37:5: error: missing argument for parameter #1 in call
main()
^
<unknown>:0: error: build had 1 command failures
error: exit(1): ["/home/**********/Swift/usr/bin/swift-build-tool", "-f", "/home/**********/SwiftProjects/HelloPackage/.build/debug/HelloPackage.o/llbuild.yaml"]
当我使用自定义函数组合运算符时,它不允许我使用与单独调用函数时相同的默认参数值。
谁能解释一下这是怎么回事?
最佳答案
与函数不同,闭包不允许有默认参数值。因此,上面的内容与您的自定义运算符没有任何具体关系(除了它返回一个闭包这一事实)。
Closure expression syntax can use constant parameters, variable parameters, and inout parameters. Default values cannot be provided.
此外,关于运行和不运行的比较:请注意以下是两行完全不同的代码:
var input = readln() // 'input' is a value: String?
// ...
let main = readln |>> myPrint // 'main' is a closure: (Int) -> ()
main() // expected error
/* since main is a closure, you've "lost" the default
value that is present in the _function_ readln */
关于swift - 函数组合运算符不尊重默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096997/