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

xcode - Guard with trailing closure - Swift Syntax

Let's say, I have a function which takes a closure as its last parameter, so it can be shortened to something like this:

let reminder = reminders.first { (reminder) -> Bool in
    return reminder.mealIdentifier == mealIdentifier
}

Awesome! Now let's say I want to put this in a guard statement, like this:

guard let reminder = reminders.first { (reminder) -> Bool in
    return reminder.mealIdentifier == mealIdentifier
} else {
    continue
}

The moment I do this, the compiler starts screaming. The fix is to use no trailing closure short syntax when calling the function, but it's cumbersome as the default auto-completion by Xcode doesn't have an option to NOT do trailing closures short syntaxes when your last parameter is a closure:

guard let reminder = reminders.first(where: { (reminder) -> Bool in
   return reminder.mealIdentifier == mealIdentifier
}) else {
    continue
}

Is there anything I'm missing here? Or is there a way to somehow have Xcode do autocompletion without the shortened syntax?

question from:https://stackoverflow.com/questions/65933463/guard-with-trailing-closure-swift-syntax

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

1 Answer

0 votes
by (71.8m points)

Or is there a way to somehow have Xcode do autocompletion without the shortened syntax?

Xcode is quite smart. It chooses the non-trailing closure version if you do the auto completion in a control flow statement that needs a {. For example, if I type:

guard let a = reminders.first

The auto complete shows:

enter image description here

If I choose the highlighted option, I get:

guard let a = reminders.first(where: <#T##(String) throws -> Bool#>)

enter image description here

If I then press enter, I get:

guard let a = reminders.first(where: { (<#String#>) -> Bool in
    <#code#>
})

enter image description here

It doesn't turn it into a trailing closure, as long as you autocomplete within a guard/if statement.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...