ios Swift PropertyWrapper,无法初始化变量

mlnl4t2r  于 2022-11-19  发布在  iOS
关注(0)|答案(1)|浏览(343)

因此,我尝试创建一个属性 Package 器,它可以将电话号码从不需要的字符中剥离出来,并向其中添加一个国家/地区代码:

@propertyWrapper
struct MSISDN {

private var _wrappedValue: String

public var wrappedValue: String {
    get {
        return fullMsisdn
    }
    set {
        _wrappedValue = newValue
    }
}

private var cleaned: String {
    return cleanStr(str: _wrappedValue)
}

private var fullMsisdn: String {
    return withCountryCode(cleaned)
}

private func cleanStr(str: String) -> String {
    return str.replacingOccurrences(of: "[ \\-()]", with: "", options: [.regularExpression])
}

private func withCountryCode(_ msisdn: String) -> String {
    guard msisdn.count == 10 && msisdn.starts(with: "69") else { return msisdn }
    
    return "+30\(msisdn)"
}

init(wrappedValue: String) {
    self._wrappedValue = wrappedValue
}

现在,当我尝试创建一个类似于@MSISDN var msisdn: String = "69 (4615)-11-21"的var时,我得到以下错误

error: msisdn.playground:71:17: error: closure captures '_msisdn' before it is declared
    @MSISDN var ms: String = "69 (4615)-11-21"
                ^

msisdn.playground:71:17: note: captured value declared here
    @MSISDN var msisdn: String = "69 (4615)-11-21"
            ^

如果我试着像下面这样分两步来做,一切都会好的。

@MSISDN var msisdn: String
msisdn = "69 (4615)-11-21"

有谁能帮我一个大忙,帮我把它分解一下吗?

bvuwiixz

bvuwiixz1#

截至Xcode 14.1,仍不支持此功能。更新的消息是:
Property wrappers are not yet supported in top-level code
简单的解决方法是将代码放在一个结构体中:

//@MSISDN var phN = "69 (4615)-11-21"
   struct workAround {
       @MSISDN var phN = "69 (4615)-11-21"
   }
   print (workAround().phN)`

相关问题