Result Builders क्या हैं
एक result builder special magic है जो आपको एक natural-looking block में steps की एक list लिखने देता है, और Swift गुप्त रूप से इन सभी को आपके लिए एक final value में combine करता है।
Syntax
@resultBuilder
struct BuilderName {
static func buildBlock(_ parts: Type...) -> ResultType {
// combine parts
}
}
@BuilderName func build() -> ResultType {
part1
part2
}
Defining a Minimal Result Builder
एक @resultBuilder type buildBlock implement करता है, जिसे Swift किसी annotated closure के अंदर लिखे हर statement को एक final value में combine करने के लिए अपने आप call करता है।
उदाहरण: Defining a Minimal Result Builder
@resultBuilder
struct StringBuilder {
static func buildBlock(_ parts: String...) -> String {
return parts.joined(separator: ", ")
}
}
func makeList(@StringBuilder content: () -> String) -> String {
return content()
}
let result = makeList {
"apple"
"banana"
"cherry"
}
print(result)
Login to try C/C++/Java/PHP code in the editor
Result Builders with Conditional Logic
एक ज़्यादा complete result builder builder block के अंदर if statements support करने के लिए buildEither या buildOptional भी implement करता है।
उदाहरण: Result Builders with Conditional Logic
@resultBuilder
struct StringBuilder {
static func buildBlock(_ parts: String...) -> String {
return parts.joined(separator: ", ")
}
static func buildOptional(_ part: String?) -> String {
return part ?? ""
}
}
func makeList(includeExtra: Bool, @StringBuilder content: () -> String) -> String {
return content()
}
let result = makeList(includeExtra: true) {
"apple"
"banana"
}
print(result)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- यह मान लेना कि result builders सिर्फ SwiftUI के लिए हैं; ये एक general Swift language feature हैं जो किसी भी plain command-line code में उपयोग किए जा सकते हैं।
- यह भूल जाना कि एक result builder type को कई components को एक में combine करने के लिए कम से कम एक static
buildBlockmethod चाहिए। @resultBuilderको किसी function के parameter पर गलत तरीके से apply करना; इसे closure PARAMETER के type को annotate करना चाहिए, जैसे@MyBuilder () -> String।
चैप्टर सारांश
@resultBuilderएक type को चिह्नित करता है जो define करता है कि एक special block में कई expressions को एक value में कैसे combine करें।- एक minimal result builder एक static
buildBlockmethod implement करता है। - Builder को इसके type से पहले
@BuilderNameके साथ एक closure parameter पर apply किया जाता है। - Result builders SwiftUI की view syntax को power देते हैं, लेकिन एक general-purpose Swift feature हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: