我把自己变成了一个playground --熟悉房产包装的榜样.

以下代码:

import Foundation

@propertyWrapper
struct Price {
    private var price: Double
    
    init() {
        self.price = 0.0
    }
    
    var wrappedValue: Double {
        get {
            return self.price
        }
        set {
            if newValue < 0.0 {
                self.price = 0.0
            } else if newValue > 10_000 {
                return
            } else {
                self.price = newValue
            }
        }
    }
}

struct Article {
    var vendor: String
    var name: String
    @Price var price: Double
}

var display = Article(vendor: "Asus", name: "X127", price: 139.0)
/*
 expression failed to parse:
 error: Playground.playground:33:60: error: cannot convert value of type 'Double' to expected argument type 'Price'
 var display = Article(vendor: "Asus", name: "X127", price: 139.0)
 */
print("\(display.vendor) Display costs \(display.price) Euro")

如果我用...

var display = Article(vendor: "Asus", name: "X127")
display.price = 129.99
print("\(display.vendor) Display costs \(display.price) Euro")
// Asus Display costs 129.99 Euro

...那么它就运行得很好.

What I'm I doing wrong with the constructor-initialization? What's the correct way to initialize the wrapper property?

What is going wrong within the first example in general?

推荐答案

如果希望第一个示例正常工作,则需要一个接受值的init,否则编译器将不知道如何将值139.0赋值给Price属性

init(wrappedValue: Double) {
    self.price = wrappedValue
}

请注意,参数标签为wrappedValue,以匹配具有相同名称的必需属性,从而可以分配默认值.

并且您还需要删除不带参数的现有init.这也是为什么您的第二个示例工作的原因,因为它是在Article构造函数中的price参数没有值时被调用的,这意味着它的工作方式与缺省值一样.

Swift相关问答推荐

如何在AudioKit中实现自定义音效 node ?

UICollectionViewCompostionalLayout Collectionview单元格宽度在重新加载数据后未正确调整大小

以编程方式使UIView居中,而不影响UIKit中其他UI类的位置

SwiftData:非法try 在不同上下文中的对象之间建立关系

如何在应用程序区域永久更改 NSCursor?

BLE 在 ESP32 和 Iphone 之间发送字符串

SwiftUI如何能够在Text中使用字符串字面量来创建LocalizedStringKey?

(Swift)混淆了函数内 for-in 循环的返回值和循环后(函数内)的返回值)

无法使用 RealityKit 播放 USDZ 动画

在 SwiftUI 中的 ForEach 中使用 id 时如何为数组设置动画索引

Swift UI 不重绘 NSViewRepresentable 包装的文本字段

Swift中的分段错误

在 Swift 中返回实例类型

无法使用锚激活约束

即使设置为从不也可以访问 iOS11 照片库

swift : 具有类型和值的枚举常量

你如何在 UIBarItem 中使用 setTitleTextAttributes:forState?

使用 DispatchTime.now() + float 延迟?

在 xcode8 中找不到 ModuleName-Swift.h 文件

Swift 中的 recursiveDescription 方法?