Pascal
Pascal

Reputation: 1305

How to take out parts of a string in swift

I want to take out a part of my String and afterwords I want to save it in a new String.

var key = "Optional("rFchd9DqwE")"

So my String equals now to Optional("rFchd9DqwE"). Now I want to take out the part rFchd9DqwE from this String and save it back in the variable "key". Is there a simple way to do this?

Upvotes: 1

Views: 217

Answers (1)

Duncan C
Duncan C

Reputation: 131418

If you have code like this:

var aString: String? = "rFchd9DqwE"

let b = "\(aString)"

Then the problem is that you are doing it wrong. The "Optional()" bit in your output is telling you that you passed in an optional type instead of a string type.

What you should do is something like this instead:

var aString: String? = "rFchd9DqwE"

if let requiredString = aString
{
  let b = "\(requiredString)"
}

the "if let" part is called "optional binding". It converts aString from an optional to a regular String object and saves the result in the new constant requiredString. If aString contains a nil, the code inside the braces is skipped.

Another way to do this would be to use the nil coalescing operator:

var aString: String? = "rFchd9DqwE"

let b = "\(aString ?? "")"

The construct aString ?? "" returns the string value of aString if it's not nil, or replaces it with the value after the ?? if it is nil. In this case it replaces nil with a blank.

Upvotes: 3

Related Questions