user6510422 - 7 months ago 305

iOS Question

I get the following error when using code for an extension, I'm not sure if they're asking to just use a different operator or modify the values in the expression based on an internet search.

Error: % is unavailable: Use truncatingRemainder instead

Extension code:

`extension CMTime {`

var durationText:String {

let totalSeconds = CMTimeGetSeconds(self)

let hours:Int = Int(totalSeconds / 3600)

let minutes:Int = Int(totalSeconds % 3600 / 60)

let seconds:Int = Int(totalSeconds % 60)

if hours > 0 {

return String(format: "%i:%02i:%02i", hours, minutes, seconds)

} else {

return String(format: "%02i:%02i", minutes, seconds)

}

}

}

The error(s) occur when setting the minutes and seconds variables.

Answer

`CMTimeGetSeconds()`

returns a floating point number (`Float64`

aka
`Double`

), and for those the remainder operator `%`

was removed in
Swift 3. What you probably want is

```
let totalSeconds = Int(CMTimeGetSeconds(self)) // Truncate to integer
```

or

```
let totalSeconds = lrint(CMTimeGetSeconds(self)) // Round to nearest integer
```

to get an integer value. Then the next lines simplify to

```
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
```

To explain the error message: In Swift 2 you could compute the remainder of a floating point division as

```
let rem = 2.5 % 1.1
print(rem) // 0.3
```

In Swift 3 this is done with

```
let rem = 2.5.truncatingRemainder(dividingBy: 1.1)
print(rem) // 0.3
```

Source (Stackoverflow)