Last active
May 5, 2023 07:59
-
-
Save cbess/3286530e51b50b8a9884bed0ce8e0175 to your computer and use it in GitHub Desktop.
Swift: Seconds to minutes and hours parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Represents parts of time | |
struct TimeParts: CustomStringConvertible { | |
var seconds = 0 | |
var minutes = 0 | |
/// The string representation of the time parts (ex: 07:37) | |
var description: String { | |
return NSString(format: "%02d:%02d", minutes, seconds) as String | |
} | |
} | |
/// Represents unset or empty time parts | |
let EmptyTimeParts = 0.toTimeParts() | |
extension Int { | |
/// The time parts for this integer represented from total seconds in time. | |
/// -- returns: A TimeParts struct that describes the parts of time | |
func toTimeParts() -> TimeParts { | |
let seconds = self | |
var mins = 0 | |
var secs = seconds | |
if seconds >= 60 { | |
mins = Int(seconds / 60) | |
secs = seconds - (mins * 60) | |
} | |
return TimeParts(seconds: secs, minutes: mins) | |
} | |
/// The string representation of the time parts (ex: 07:37) | |
func asTimeString() -> String { | |
return toTimeParts().description | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment