Search code examples
iosswiftstringint

Convert String minutes seconds to Int


I've a string with minutes and seconds in format "minutes:seconds". For example, "5:36". I want to convert it to Int value. For example "5:36" string should be 336 Int value. How this can be done?


Solution

  • Here's a simple extension you can use which will validate the format of your input string too:

    import Foundation
    
    extension String {
    
        func toSeconds() -> Int? {
    
            let elements = components(separatedBy: ":")
    
            guard elements.count == 2 else {
                print("Provided string doesn't have two sides separated by a ':'")
                return nil
            }
    
            guard let minutes = Int(elements[0]),
            let seconds = Int(elements[1]) else {
               print("Either the minute value or the seconds value cannot be converted to an Int")
                return nil
            }
    
            return (minutes*60) + seconds
    
        }
    
    }
    

    Usage:

    let testString1 = "5:36"
    let testString2 = "35:36"
    
    print(testString1.toSeconds()) // prints: "Optional(336)"
    print(testString2.toSeconds()) // prints: "Optional(2136)"