# Preview Devices

{% tabs %}
{% tab title="extension" %}
有了下列的 extension：

```swift
import SwiftUI

extension PreviewDevice {
    // ⭐️ `PreviewDevice` conforms to `ExpressibleByStringLiteral`
    static let iPhone13ProMax: PreviewDevice = "iPhone 13 Pro Max"
    static let iPhone13Pro   : PreviewDevice = "iPhone 13 Pro"
}
```

就可以使用下列語法：

```swift
.previewDevice(.iPhone13Pro)    // ⭐️ use static member
```



使用下列 extension：

```swift
extension View {
    /// .previewDevice(deviceName)
    public func previewDevice(_ deviceName: String) -> some View {
        previewDevice(PreviewDevice(rawValue: deviceName))
    }
}
```

則可用下列語法：

```swift
// string constant
let deviceName = "iPhone X"
.previewDevice(deviceName)    // ⭐️ not a string literal
```
{% endtab %}

{% tab title="解說" %}
[.previewDevice()](https://developer.apple.com/documentation/swiftui/view/previewdevice\(_:\)) 要接收一個 [PreviewDevice?](https://developer.apple.com/documentation/swiftui/previewdevice) 參數，但可以使用：

```swift
.previewDevice("iPhone XS Max")
```

的語法，是因為 [PreviewDevice](https://developer.apple.com/documentation/swiftui/previewdevice) conforms to [ExpressibleByStringLiteral](https://developer.apple.com/documentation/swift/expressiblebystringliteral)



如果直接使用下列語法會產生錯誤：

```swift
.previewDevice(deviceName)    // var deviceName = "iPhone X"
```

因為 `deviceName` 是一個 String variable，並不是 String literal。&#x20;



所以如果不做任何擴充，我們只能使用：

```swift
.previewDevice(PreviewDevice(rawValue: deviceName))
```
{% endtab %}

{% tab title="📘 手冊" %}
* SwiftUI Tutorials ⟩ [Sec. 8: Generate Previews Dynamically](https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation#Generate-Previews-Dynamically) - Step 2
* [SwiftUI](https://developer.apple.com/documentation/swiftui) ⟩ [Previews in Xcode](https://developer.apple.com/documentation/swiftui/previews-in-xcode)
  * View ⟩ [.previewDevice(\_:)](https://developer.apple.com/documentation/swiftui/view/previewdevice\(_:\))
  * [PreviewDevice](https://developer.apple.com/documentation/swiftui/previewdevice) (<mark style="color:red;">**struct**</mark>)
{% endtab %}
{% endtabs %}
