๐ฆMeasurement
import Foundation // Measurement
/* ------- Custom Extensions ------- */
extension Double {
/// usage: `6.ft`
var ft: Measurement<UnitLength> {
Measurement(value: self, unit: UnitLength.feet)
}
/// usage: `180.deg`
var deg: Measurement<UnitAngle> {
Measurement(value: self, unit: UnitAngle.degrees)
}
/// usage: `4.mยฒ`
var mยฒ: Measurement<UnitArea> {
Measurement(value: self, unit: UnitArea.squareMeters)
}
}
extension Measurement where UnitType: Dimension {
/// usage: `6.ft.in(.centimeters)`
func `in`(_ otherUnit: UnitType) -> Measurement<UnitType> {
converted(to: otherUnit)
}
}
// ----------------------------------------
// length
let h1 = Measurement(value: 6, unit: UnitLength.feet)
let h2 = h1.converted(to: UnitLength.inches)
let h3 = h1.converted(to: UnitLength.meters)
h1 == h2 // true
h2 == h3 // true
let h = 6.ft
let h4 = h.in(.centimeters)
"\(h) = \(h4)" // 6.0 ft = 182.8800...002 cm
// โ ๅ
ฉๅๆธฌ้ๅผ (Measurement) ไธ่ฝ็ดๆฅ้็ฎ๏ผ็ไพไฝฟ็จ่ตทไพ้ๅถไธๅฐใ
// let hSqaured = h * h
// angle
let degrees = Measurement(value: 180, unit: UnitAngle.degrees)
let radians = degrees.converted(to: .radians)
let a = 180.deg
let a1 = a.in(.radians)
"\(a) = \(a1)" // 180.0ยฐ = 3.1415...9798 rad
// area
let squareMeters = Measurement(value: 4, unit: UnitArea.squareMeters)
let squareCentimeters = squareMeters.converted(to: .squareCentimeters)
let b = 4.mยฒ
let b2 = b.in(.squareCentimeters)
"\(b) = \(b2)" // 4.0 mยฒ = 40000.0 cmยฒ
// volumn
let bushels = Measurement(value: 6, unit: UnitVolume.bushels)
let teaspoons = bushels.converted(to: .imperialTeaspoons)
ๅฎ็พฉ
struct Measurement<UnitType: Unit>
Last updated