[英]Compare String with String value of MVC
要在collectionView
的單元格中查看我的數據,我正在使用MVC架構來保持代碼干凈
現在我有一個名為TimeSelModel
的 class 處理有 model function
它的結構是這樣的
struct Section<T> {
let model: [T]
}
struct TimeSelModel {
let hour: String
let minute: String
}
let dataSec0 = [
TimeSelModel(hour: "09", minute: ":30"),
TimeSelModel(hour: "17", minute: ":00")
]
let dataSec1 = [
TimeSelModel(hour: "12", minute: ":00"),
TimeSelModel(hour: "19", minute: ":00")
]
我以這種方式使用這些數據在collectionView
中使用它
private var data: [Section<TimeSelModel>] = []
private func fetchData() -> Void {
data = [Section(model: dataSec0), Section(model: dataSec1)]
}
func numberOfSections(in collectionView: UICollectionView) -> Int { data.count }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data[section].model.count }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TimeSelCell.cellID, for: indexPath) as! TimeSelCell
cell.dataModel = data[indexPath.section].model[indexPath.item]
return cell
}
現在我需要在一個單獨的 function 中將string
與我正在使用的 model 值進行比較
例如,我需要比較 model 值中的值“12”的string
let dataSec0 = [
TimeSelModel (hour: "09", minute: ": 30"),
TimeSelModel (hour: "17", minute: ": 00")
]
let dataSec1 = [
TimeSelModel (hour: "12", minute: ": 00"),
TimeSelModel (hour: "19", minute: ": 00")
]
將它放入我的 controller 的最佳和最干凈的方法是什么?
由於您在問題中有一個示例,然后在此處的評論中有一個不同的示例,因此有兩種方法可以獲取data
數組中某個時間的索引。
let hourValue = "12"
if let index = data.firstIndex { section in section.model.contains { $0.hour == hourValue } } {
let section = data[index]
//...
}
和
let timeValue = "17:00"
if let index = data.firstIndex { section in section.model.contains { $0.time == timeValue } } {
let section = data[index]
//...
}
最后一個示例使用了我添加到TimeSelModel
的計算屬性
struct TimeSelModel {
let hour: String
let minute: String
var time: String {
"\(hour):\(minute)"
}
}
請注意,它添加了一個“:”,因為我認為在分鍾字符串中包含冒號不是一個好主意,而不是“:00”或“:00”,它應該只是“00”。 (甚至可以爭辯說小時和分鍾應該是整數,但這不在此答案的 scope 范圍內)
另請注意,此答案基於我對Section
類型的解釋。
字符串與myTime.hour < "12"
的 unicode 值相當。
這意味着"0" < "1"
為真
但是"2" < "12"
是假的
In your case, you should compare strings with the Foundation's function https://developer.apple.com/documentation/foundation/nsstring/1408732-compare and give the options
parameter .numeric
: https://developer.apple.com/documentation /foundation/nsstring/compareoptions/1415530-numeric
switch myTime.hour.compare("12", options: [.numeric]) {
case .orderedAscending:
// myTime.hour < "12"
case .orderedSame:
// myTime.hour == "12"
case .orderedDescending:
// myTime.hour > "12"
}
但我建議使用 Int 或 TimeInterval 更改您的 model 並使用 function 將您的 model 轉換為您想要的可讀字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.