swift - 函数组合运算符不尊重默认参数?

标签 swift ubuntu

我正在 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.

来自Language Guide - Closures .

此外,关于运行和不运行的比较:请注意以下是两行完全不同的代码:

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/

相关文章:

ios - 如何在 iOS Swift 中创建延迟,以便任务 A 在任务 B 开始之前结束?

ios - 半透明模态视图 Controller 不覆盖状态栏

node.js - 尝试在 Ubuntu 12.04 上安装 Ionic 时 node.js 出错

linux - Virtualenv:找不到工作命令

python - 错误 : ‘memcpy’ was not declared in this scope (Ubuntu 16. 04,opencv2.4.13)

android - 将手机连接到 Ubuntu 中的 Android-Studio 进行调试

swift - 在 Sandbox 中获取/User/Library/Container/<identifier> 的访问权限

ios - 核心数据中的多次插入

swift - "Cannot assign value of type ' 字符串 ' to type ' AnyObject? '", swift 3,Xcode 8 测试版 6

bash - Docker Ubuntu 环境变量