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
623 views
in Technique[技术] by (71.8m points)

swift - One-line closure without return type

In Swift, if a closure holds only a single statement, it automatically returns the value returned from that single statement.

This does not feel very natural in all cases. Let's look at an example:

func StringReturningFunc() -> String {
    return "Test String"
}

// Error: Cannot convert the expressions type '() -> $T0' to type 'String'
let closure: () -> () = {
    StringReturningFunc()
}

As you can see, even though the closure should only call a simple function, it tries to automatically return it's return value, which is of type String, and does not match the return type void.

I can prevent this by implementing the closures body like so:

let _ = StringReturningFunc()

Which feels incredibly odd.

Is there a better way to do this or is this just something I have to live with?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The reason this happens is the shorthand for single line expression closures. There is an implicit 'return' in your closure as it is written.

let closure: () -> () = {
    StringReturningFunc()
    return
}

Writing it like that should work


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

...