Swift की Best Practices
Prefer let and Value Types
Default रूप से let और structs उपयोग करना ऐसा code produce करता है जिसके बारे में reason करना आसान है, क्योंकि values program में कहीं और से अनपेक्षित रूप से बदल नहीं सकतीं।
उदाहरण: Prefer let and Value Types
// Define a struct `Point`
struct Point {
let x: Int
let y: Int
}
// Declare a constant `origin`, set to `Point(x: 0, y: 0)`
let origin = Point(x: 0, y: 0)
// Print "Origin: (\(origin.x), \(origin.y))" to the console
print("Origin: (\(origin.x), \(origin.y))")
Login to try C/C++/Java/PHP code in the editor
Avoid Force Unwrapping
! के बजाय if let, guard let, या ?? उपयोग करना crashes से बचाता है जब कोई value गायब निकलती है, code को ज़्यादा resilient बनाते हुए।
उदाहरण: Avoid Force Unwrapping
// Define the function `safeDivide` taking `a`, `b` and returning a `Int?`
func safeDivide(_ a: Int, by b: Int) -> Int? {
guard b != 0 else { return nil }
// Return `a / b` from this function
return a / b
}
// Declare a constant `result`, set to `safeDivide(10, by: 0) ?? 0`
let result = safeDivide(10, by: 0) ?? 0
// Print "Safe result: \(result)" to the console
print("Safe result: \(result)")
Login to try C/C++/Java/PHP code in the editor
Write Self-Documenting Code
Functions, parameters, और variables के लिए descriptive names code को बिना यह explain करने के लिए extra comments की ज़रूरत के पढ़ने योग्य बनाते हैं कि यह क्या करता है।
उदाहरण: Write Self-Documenting Code
// Define the function `calculateTotalPrice` taking `itemPrice`, `quantity`, `taxRate` and returning a Double
func calculateTotalPrice(itemPrice: Double, quantity: Int, taxRate: Double) -> Double {
// Declare a constant `subtotal`, set to `itemPrice * Double(quantity)`
let subtotal = itemPrice * Double(quantity)
// Return `subtotal + (subtotal * taxRate)` from this function
return subtotal + (subtotal * taxRate)
}
// Print `calculateTotalPrice(itemPrice: 20.0, quantity: 3, taxRate: 0.08)` to the console
print(calculateTotalPrice(itemPrice: 20.0, quantity: 3, taxRate: 0.08))
Login to try C/C++/Java/PHP code in the editor
- आदतन default रूप से
struct,let, और safe optional handling पसंद करने के बजाय हर जगहclassऔर force-unwrapping default करना। - अत्यधिक clever one-liners लिखना जो readability की कुर्बानी देते हैं, जब Swift का clarity-focused design explicit, self-documenting code पसंद करता है।
- Compiler warnings (जैसे
varपरletका सुझाव) को free code-quality guidance मानने के बजाय नज़रअंदाज़ करना।
varसे ज़्यादाletपसंद करें, और classes से ज़्यादा structs, जब तक mutability या reference semantics specifically ज़रूरी न हो।- Force-unwrapping (
!) से बचें सिवाय वहां जहां एकnilvalue एक genuine programming error represent करे। - Clear, descriptive names उपयोग करें और clarity की कुर्बानी दिए बिना Swift के type inference को noise घटाने दें।
- Compiler पर भरोसा करें: warnings address करें, early exits के लिए
guardउपयोग करें, और strong typing को bugs जल्दी पकड़ने दें।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: