【问题标题】:Can you get __FUNCTION__ from the caller?你能从调用者那里得到 __FUNCTION__ 吗?
【发布时间】:2015-12-22 15:25:19
【问题描述】:

例子:

@noreturn func setOnlyPropertyGetterError(__function__: String) {
   fatalError("\(__function__) is set-only")
}

var property: Property {
   get {setOnlyPropertyGetterError(__FUNCTION__)}
   set {//useful work}
}

我们可以避免通过__FUNCTION__吗?

【问题讨论】:

    标签: swift macros fatal-error


    【解决方案1】:

    我认为这是您想要实现的目标:

    @noreturn func writeOnlyProperty(propertyName: String = __FUNCTION__) {
        fatalError("Property \(propertyName) is write-only")
    }
    
    class Foo {
        var blackHole: Int {
            get { writeOnlyProperty() }
            set { print("Consuming value \(newValue)") }
        }
    }
    
    let foo = Foo()
    foo.blackHole = 1       // Prints "Consuming value 1"
    let bar = foo.blackHole // Produces fatal error "Property blackHole is write-only"
    

    【讨论】:

    • 哦,这很奇怪。谢谢!然而,在这些计算属性的时代,“读取”和“写入”并不准确。
    猜你喜欢
    • 2017-01-25
    • 2022-09-25
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多