Home Can I make it simpler turning an integer into a string in a specific format using Swift?
Reply: 0

Can I make it simpler turning an integer into a string in a specific format using Swift?

user1896
1#
user1896 Published in July 15, 2018, 9:12 pm

In my audio app, I am playing audio using a progress slider bar -- in the UI, I want to show the amount of time the episode has played. Here's how I am doing that.

   @objc func updateSlider(){

        Slider.value = Float(audioPlayer.currentTime)

        func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
            return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
        }

        let example = (Float(audioPlayer.currentTime))
        let myIntValue = Int(example)
        self.goneTime.text = String(Float(describing: myIntValue)

This code updates a label dynamically but it does it in the format of (Int, Int, Int) as specified. Example Output: (1, 5, 20) when I want 1:5:20.

I have tried to modify the format (Int / Int / Int) which is flagged as an error.

A workaround -- but an ugly one -- I found using this Swift 3 answer: using .replacingOccurrencesOf. From the documentation, it says you can replace one part of the string at a time.

So I change my code to:

 func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
            return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
        }

    let example = (Float(audioPlayer.currentTime))
    let myIntValue = Int(example)

    let updated = secondsToHoursMinutesSeconds(seconds: myIntValue)

    let updated2 = String(describing: updated)

    let str2 = updated2.replacingOccurrences(of: ",", with: ":", options:
        NSString.CompareOptions.literal, range: nil)

    let str3 = str2.replacingOccurrences(of: "(", with: "", options:
        NSString.CompareOptions.literal, range: nil)

    self.goneTime.text = str3

This works ok but is there a best practice to simplify these types of modifications? New to Swift and learning.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.251758 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO