मैं सामान्य पुस्तक के लिए स्विफ्ट पुस्तक से मैट्रिक्स उदाहरण पोर्ट करने की कोशिश कर रहा हूं।स्विफ्ट में कोई डिफ़ॉल्ट (टी) नहीं है?
यहाँ मैं अब तक क्या मिला है:
struct Matrix<T> {
let rows: Int, columns: Int
var grid: T[]
init(rows: Int, columns: Int, repeatedValue: T) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: repeatedValue)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
ध्यान दें कि मैं था निर्माता को repeatedValue: T
पारित करने के लिए।
सी # में, मैं सिर्फ default(T)
इस्तेमाल किया है | जो संदर्भ प्रकार के लिए बूलियन्स के लिए संख्या के लिए 0
, false
और null
होगा। मैं समझता हूं कि स्विफ्ट गैर-वैकल्पिक प्रकारों पर nil
की अनुमति नहीं देता है, लेकिन अगर मैं एक स्पष्ट पैरामीटर पास कर रहा हूं, तो मैं अभी भी उत्सुक हूं, या अगर default(T)
के बराबर है।