ZeroChow
ZeroChow

Reputation: 442

How can I set a string variable and make it always lowercase?

I want to set a string variable and want to keep it always lowercase.

This is my code :

var alwaysLowercaseString : String? {

    didSet{
        alwaysLowercaseString = alwaysLowerCaseString!.lowercaseString
    }
}

But when I use it, it goes into a infinite loop. How can I solve this problem?

Upvotes: 2

Views: 305

Answers (3)

Dan Beaulieu
Dan Beaulieu

Reputation: 19954

I stand corrected, this is the correct approach. LeoDabus deserves the credit for this answer:

var alwaysLowercaseString : String? {
    
    didSet{
   
    alwaysLowercaseString = alwaysLowercaseString?.lowercaseString
      print(alwaysLowercaseString)
    }
}

Upvotes: 4

Pavel Stepanov
Pavel Stepanov

Reputation: 957

Since Swift 5.1 there's a possibility to use property wrappers. Roughly speaking, this mechanics allows us to modify the value each time it is set

@propertyWrapper struct Lowercased {
    var wrappedValue: String {
        didSet { wrappedValue = wrappedValue.lowercased() } // here the magic happens
    }

    init(wrappedValue: String) {
        self.wrappedValue = wrappedValue.lowercased() // we have to do it manually here because in init property observers are not triggered
    }
}

final class Test {
    @Lowercased var cantMakeMeUpperCase = ""
}

let test = Test()
test.cantMakeMeUpperCase = "CAN I?"
print(test.cantMakeMeUpperCase) // prints "can i?"

Upvotes: 1

NSGangster
NSGangster

Reputation: 2447

var alwaysLowercaseString : String? {

    didSet{
        if alwaysLowercaseString != alwaysLowerCaseString!.lowercaseString {
            alwaysLowercaseString = alwaysLowerCaseString!.lowercaseString
        }
    }
}

This checks so if the lowercase string is already lowercase it won't change the value of alwaysLowercaseString again so you won't call didSet infinitely. It will break after alwaysLowercaseString is set to lowercase.

Upvotes: 3

Related Questions