Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

swift - Why is the shorthand argument name $0 returning a tuple of all parameters?

I was trying to define a variable that can hold a closure and ran into some difficulties using Swift's shorthand argument names. Take the following code snippet:

var returnAString: (String, String) -> String
returnAString = { return $0 }

This gives me the compile error '(String, String)' is not convertible to 'String'. When I modify the closure return a string with the first argument value, I get back both argument values in a tuple.

println(returnAString("1", "2")) // Prints "(1, 2)"

However, if I modify the closure to print the second argument the correct argument is printed as expected.

returnAString = { $1 }
println(returnAString("1", "2")) // Prints "2"

I've got the feeling that I'm doing something a little silly here, but I couldn't find any explanation of why this would be happening.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Closures § Shorthand Argument Names

Shorthand Argument Names

… the number and type of the shorthand argument names will be inferred from the expected function type.

It looks like this is the expected behavior. By providing only $0 you are inferring (at least to the system) that you want a tuple.

This only seems to be a special case of using $0. For example, the following cannot be compiled.

var returnAString3: (String, String, String) -> String
returnAString3 = { return $1 }

No matter how it's modified.

returnAString3 = { return $1.0 } // still fails.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...