Swift中prepare函数参数前"for"的作用是什么?
Understanding the
for Parameter Label in prepare(for:sender:) Great question—this is one of those Swift syntax details that ties back to both language design principles and UIKit's Objective-C roots, so let's unpack it.
First, remember that Swift has two types of parameter names for functions:
- Internal parameter names: These are what you use inside the function body to reference the value (in this case,
segue). - External parameter labels: These are what you use when calling the function to make the code read like natural language (here, that's
for).
Even though you never call prepare(for:sender:) manually (UIKit calls it for you when a segue triggers), the for label serves a few key purposes:
- Readability: It turns the function signature into something that makes plain sense. If you did call it, you'd write
prepare(for: mySegue, sender: someSender)—which reads like "prepare for this segue, using this sender"—way clearer than a label-less version likeprepare(mySegue, sender: someSender). - Consistency with Objective-C: UIKit originated in Objective-C, where the equivalent method is
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender. Swift bridges this to keep the familiar, semantic naming: theForSeguepart gets split into theforlabel andsegueinternal name, so the intent stays the same for developers coming from either language. - API clarity: It explicitly signals the relationship between the function and its first parameter—this function exists to prepare for a specific segue, not just work with a segue in some arbitrary way.
Think of it like other Swift APIs you use regularly: when you write UIView.animate(withDuration: 0.3, animations: { ... }), the withDuration: label does the same thing—it makes the call read like a sentence, not just a list of arguments.
内容的提问来源于stack exchange,提问作者cluster1
相关产品推荐
相关产品推荐

