본문 바로가기
프로그래밍/Swift

Swift함수, 초 단위 값을 hh:mm으로 표현하기(with CustomStringConvertible)

by Mr-후 2022. 6. 9.
반응형

오늘은 스위프트의 함수를 하나 정리해서 올려 두고자 한다. 
어제 UI작업을 하던 중, 서버로부터 받은 7200초라는 값을 시:분으로 표현을 하고자 괜찮은 방법이 있는지 검색을 해보니 적당한 extension과 protocol이 있어 정리를 해 둔다. 

 

CustomStringConvertible 이란 프로토콜은 사용자기 지정한 문자열로 변환이 가능한 프로토콜이다. 이 프로토콜을 정의하고 시와 분으로 나눠 사용자 정의 서식 문자열로 리턴하면 깔끔하게 사용할 수 있다. 

<코드> 

public struct TimeParts: CustomStringConvertible {
    public var hours = 0
    public var minutes = 0
    public var description: String {
        return NSString(format: "%02d:%02d", hours, minutes) as String
    }
}

extension Int {
    public func toTimeParts() -> TimeParts {
        let seconds = self
        let mins = (seconds % 3600) / 60
        let hours = seconds / 3600
        return TimeParts(hours: hours, minutes: mins)
    }
}

 

사용하는 예시는 다음과 같다. 

//운동시간
let timePart = Int(item.thisWeekSumTimeExercised).toTimeParts()
self.lblExer.text = timePart.description
반응형