Rohan Bhale
Rohan Bhale

Reputation: 1345

Declaring a Swift Character type that could hold only ASCII characters?

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

Answers (1)

Gustavo Vollbrecht
Gustavo Vollbrecht

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

Related Questions