최소공배수 인지 아닌지 확인하는 Int 메서드. Int % Int == 0 과 동일
15.isMultiple(of: 3) // true
문자열에 매칭하는 부분을 찾아서 대체할때 사용한다.
let ohms = 567800040.0
let (divisor, suffix) = ohms >= 1_000_000 ? (1_000_000, "M") : ohms >= 1_000 ? (1_000, "k") : (1, "")
let ohmsRounded = String(format: "%.1f\(suffix)", ohms / Double(divisor) ).replacingOccurrences(of: ".0", with: "")
let float = 5.321
float.truncatingRemainder(dividingBy: 1.0) // .321
// 위는 float % 1.0 와 같으나, % 연산자는 float 이나 double 타입에 사용할 수 없음
// 그러므로 truncatingRemainder(dividingBy:) 를 사용해야함
// 함수 예시
func removeDecimalIfZero(for decimal: Decimal) -> String {
if decimal.truncatingRemainder(dividingBy: 1.0) == 0 {
return String(format: "%.0f, decimal)
} else {
return String(format: "%.1f, decimal)
}
}
extension Float {
var clean: String {
if self.truncatingRemainder(dividingBy: 1.0) == 0 {
return String(format: "%.0f, self)
} else {
return String(format: "%.1f, self)
}
}
}
stride → creates ranges .
[Int](stride(from: 1, to: n, by: 2))
// [1, 3, 5, ..., n - 2, n] <- INCLUDES end value n
returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.
for i in stride(from:5,through:1,by:-1) { print(i) } // 5 4 3 2 1
for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {
let degrees = Int(radians * 180 / .pi)
print("Degrees: \(degrees), radians: \(radians)")
}
stride returns a sequence from a starting value to, but not including an end value, stepping by the specified amount.