0

So, i try to create a property wrapper that strips a phone number from unwanted characters and add a country code to it:

@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
}

Now, when i try to create a var like this @MSISDN var msisdn: String = "69 (4615)-11-21" i get the following errors

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"
            ^

If i try to do it in two steps like below, everything works.

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

Could anyone do my a huge favour and break it down for me please?

Victor Benetatos
  • 396
  • 3
  • 12

1 Answers1

0

As of Xcode 14.1 this is still not supported. The newer message is:

Property wrappers are not yet supported in top-level code

The easy work-around is to just put your code in a struct:

//@MSISDN var phN = "69 (4615)-11-21"
   struct workAround {
       @MSISDN var phN = "69 (4615)-11-21"
   }
   print (workAround().phN)`
Bill
  • 1,588
  • 12
  • 21