Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...