← Back to Swift Course | Chapter 12: Generics & Advanced Types | Lesson 3 of 7

Type Constraints क्या हैं

एक type constraint एक rule है जो कहता है एक generic placeholder को सिर्फ वे types भर सकते हैं जो एक certain requirement पूरी करते हैं, जैसे "comparable होना चाहिए।"
Syntax
swift
func functionName<T: ProtocolName>(_ items: [T]) -> T? {
    // can use what ProtocolName provides, e.g. < for Comparable
}

Constraining to Comparable

एक generic placeholder में : Comparable जोड़ना function को < और > जैसे comparison operators उपयोग करने देता है, जो एक unconstrained type पर guaranteed नहीं हैं।

उदाहरण: Constraining to Comparable

markup
func findLargest<T: Comparable>(_ items: [T]) -> T? {
    guard var largest = items.first else { return nil }
    // Loop over `items where item > largest`, binding each item to `item`
    for item in items where item > largest {
        largest = item
    }
    // Return `largest` from this function
    return largest
}
// Print `findLargest([3, 7, 2, 9, 4]) as Any` to the console
print(findLargest([3, 7, 2, 9, 4]) as Any)
// Print `findLargest(["banana", "apple", "cherry"]) as Any` to the console
print(findLargest(["banana", "apple", "cherry"]) as Any)

Constraining to a Custom Protocol

एक generic placeholder को किसी custom protocol से भी constrain किया जा सकता है, conforming types को इसकी specific requirements implement करने की मांग करते हुए।

उदाहरण: Constraining to a Custom Protocol

markup
// Define a protocol `Summable` describing required behavior
protocol Summable {
    static func + (lhs: Self, rhs: Self) -> Self
    static var zero: Self { get }
}
// Extend `Int` with additional functionality
extension Int: Summable {
    static var zero: Int { 0 }
}
func total<T: Summable>(_ items: [T]) -> T {
    // Declare a mutable variable `result`, initialized to `T.zero`
    var result = T.zero
    // Loop over `items`, binding each item to `item`
    for item in items {
        result = result + item
    }
    // Return `result` from this function
    return result
}
// Print `total([1, 2, 3, 4])` to the console
print(total([1, 2, 3, 4]))
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. #}
आम गलतियां
  1. एक generic function लिखना जो अपने placeholder type पर < या == उपयोग करता है बिना पहले इसे Comparable या Equatable से constrain किए -- compiler unconstrained comparisons reject कर देगा।
  2. एक class-inheritance constraint (T: SomeClass) को एक protocol constraint (T: SomeProtocol) के साथ confuse करना; दोनों एक जैसा colon syntax उपयोग करते हैं लेकिन अलग मतलब रखते हैं।
  3. किसी generic function को उन requirements से over-constrain करना जिनकी इसे असल में ज़रूरत नहीं, अनावश्यक रूप से यह सीमित करते हुए कि कौन से types उपयोग किए जा सकते हैं।
चैप्टर सारांश
  • एक constraint किसी generic placeholder को एक protocol conform करने वाले या एक class inherit करने वाले types तक restrict करता है।
  • Constraints placeholder नाम के बाद एक colon से लिखे जाते हैं, जैसे <T: Comparable>।
  • Constraints आपको ऐसे operations (जैसे < या ==) उपयोग करने देते हैं जो हर possible type पर available नहीं हैं।
  • कई constraints को & या एक where clause उपयोग करके combine किया जा सकता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.