Reputation: 1345
Swift's Character
data type is a very broad set and I have a use case where I need to declare a variable which can only hold ascii characters. The type should not be able to accept characters outside ascii.
Do we have any other in built data types that are suitable for my use case?
Or do I need to write a custom solution?
If it requires custom solution what are the best possible ways to achieve it?
Upvotes: 1
Views: 545
Reputation: 3256
As pointed in the question comments, it seems it's not possible to have a check on compile time.
A runtime solution could be:
You can check if a Character
is Ascii by <#Character#>.isASCII
, then you can create a custom class that only stores a value if the condition is satisfied.
struct CustomASCIIClass {
private var storedValue : Character? = nil
var value : Character? {
get {
return self.storedValue ?? nil
}
set (newValue) {
if (newValue?.isASCII ?? false) {
self.storedValue = newValue
} else {
// handle not possible value, throw something or make the variable to have nil value.
print("invalid: ", newValue)
}
}
}
}
Usage:
var a = CustomASCIIClass()
a.value = Character("A")
print(a.value) // Optional("A")
var b = CustomASCIIClass()
b.value = Character("😎")
print(b.value) // nil
Upvotes: 1