2015-10-18 28 views
0

我有當前時間和這個時間陣列。我想確定下一次到最近的時間。Swift數組。試圖根據當前時間在陣列中查找下一次

let date = NSDate() 
let calendar = NSCalendar.currentCalendar() 
let components = calendar.components([.Hour, .Minute], fromDate: date) 
let hour = components.hour 
let minutes = components.minute 
let currentTime = "\(hour)" + ":" + "\(minutes)" //output 15:24 

let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"] 

回答

0
let date = NSDate() 
let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"] 

// create a method to convert your time to minutes 
func stringToMinutes(input:String) -> Int { 
    let components = input.componentsSeparatedByString(":") 
    let hour = Int((components.first ?? "0")) ?? 0 
    let minute = Int((components.last ?? "0")) ?? 0 
    return hour*60 + minute 
} 

//create an array with the minutes from the original array 
let timesMinutesArray:[Int] = timesArray.map { stringToMinutes($0) } 

let dayMinute = stringToMinutes("15:24") 
// filter out the times that has already passed 
let filteredTimesArray = timesMinutesArray.filter{$0 > dayMinute } 

// get the first time in your array 
if let firstTime = filteredTimesArray.first { 
    // find its position and extract it from the original array 
    let item = timesArray[timesMinutesArray.indexOf(firstTime)!] // "15:40" 
} 

如果你需要,你還可以創建一個擴展,在你的代碼的任何地方使用它如下:

extension String { 
    var hourMinuteValue: (hour:Int,minute:Int) { 
     guard 
      let hour = Int(componentsSeparatedByString(":").first ?? ""), 
      let minute = Int(componentsSeparatedByString(":").last ?? "") 
      where componentsSeparatedByString(":").count == 2 
      else { return (0,0) } 
     return (hour,minute) 
    } 
    var dayMinute:Int { 
     return hourMinuteValue.hour*60 + hourMinuteValue.minute 
    } 
} 

let time = "15:24" 

let times = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"] 

let minutes = times.map{ $0.dayMinute } 

let filteredMinutes = minutes.filter{ $0 > time.dayMinute } 

if let firstTime = filteredMinutes.first { 
    let item = times[minutes.indexOf(firstTime)!] // "15:40" 
} 
+1

完美。感謝您的回覆。 – matarali

相關問題