> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/master/todo/custom-types/kilometersperhour.md).

# @KilometersPerHour

對於 Swift 沒有自動支援 Encode/Decode 的型別，我們可以利用 Property Wrapper 來讓自訂型別自動做編碼解碼的動作。

{% tabs %}
{% tab title="@KilometersPerHour" %}

```swift
@propertyWrapper
struct KilometersPerHour {
    var wrappedValue: Measurement<UnitSpeed>
}

extension KilometersPerHour: Codable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rawValue = try container.decode(Double.self)

        wrappedValue = Measurement(
            value: rawValue,
            unit: .kilometersPerHour
        )
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(wrappedValue.value)
    }
}
```

{% endtab %}

{% tab title="📘 參考" %}

* [x] [Formatting numbers in Swift](https://www.swiftbysundell.com/articles/formatting-numbers-in-swift) - Sundell
* [x] [How to convert units using Unit and Measurement](https://www.hackingwithswift.com/example-code/system/how-to-convert-units-using-unit-and-measurement) - Hacking with Swift
  {% endtab %}

{% tab title="🍎 官方" %}

* [Foundation](https://developer.apple.com/documentation/foundation) > [Units and Measurement](https://developer.apple.com/documentation/foundation/units_and_measurement)&#x20;
  * [Measurement](https://developer.apple.com/documentation/foundation/measurement)
    {% endtab %}

{% tab title="👥 相關" %}

* [📦 Measurement](/ios/appendix/notes/measurement.md)
  {% endtab %}
  {% endtabs %}
