Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift .uppercaseString or .lowercaseString property replacement

Tags:

swift

Since Strings in Swift no longer have the .uppercaseString or .lowercaseString properties available, how would i go about performing that function?

If i have for example:

var sillyString = "This is a string!" let yellyString = sillyString.uppercaseString let silentString = sillyString.lowercaseString 

I would like to take sillyString and mutate it into either uppercase or lowercase. How would i go about doing that now?

Thanks in advance!

like image 308
Don Alejandro Avatar asked Oct 07 '14 21:10

Don Alejandro


People also ask

How do I convert a string to lowercase in Swift?

Swift String lowercased() The lowercased() method converts all uppercase characters in a string into lowercase characters.

How do I create a lowercase character in Swift?

To convert a String to Lowercase in Swift, use String. lowercased() function. Call lowercased() function on the String. The function returns a new string with the contents of the original string transformed to lowercase alphabets.


1 Answers

Xcode 6.0 / Swift 1.0

String is bridged seamlessly to NSString, so it does have uppercaseString and lowercaseString properties as long as you import Foundation (or really almost any framework since they'll usually import Foundation internally. From the Strings and Characters section of the Swift Programming Guide:

Swift’s String type is bridged seamlessly to Foundation’s NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.


Xcode 6.1 / Swift 1.1

As @newacct pointed out, in Xcode 6.1 / Swift 1.1, uppercaseString and lowercaseString are in Swift's String class so you don't need to use the ones defined in NSString. However, it's implemented as an extension to the String class in the Foundation framework so the solution is still the same: import Foundation

In a playground:

import Foundation  var sillyString = "This is a string!" // --> This is a string! let yellyString = sillyString.uppercaseString // --> THIS IS A STRING! let silentString = sillyString.lowercaseString // --> this is a string! 

Swift 3.0

In a playground:

import Foundation  var sillyString = "This is a string!" // --> This is a string! let yellyString = sillyString.uppercased() // --> THIS IS A STRING! let silentString = sillyString.lowercased() // --> this is a string! 
like image 111
Mike S Avatar answered Sep 23 '22 22:09

Mike S