1

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?

Pascal
  • 1,255
  • 5
  • 20
  • 44
  • you'll probably want to use a regex or substring. Here is a [post on substrings](http://stackoverflow.com/questions/28182441/swift-how-to-get-substring-from-start-to-last-index-of-character). – Rick Smith May 08 '15 at 22:00
  • 3
    You should better figure out *why* you have "Optional" in the string. Most probably you did not unwrap an optional value before. – Martin R May 08 '15 at 22:05

1 Answers1

3

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    This is what's known as an "[**XY problem.**](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)" Eric D. gave you a solution to the question you asked, but it's the wrong way to go about it. – Duncan C May 08 '15 at 22:43
  • @PascalAckermann the problem is really really not solved. You need to in accept the other answer. It is very wrong to be doing this. – Fogmeister May 08 '15 at 22:49
  • @EricD. No worries. It's easy to fall into traps like this :-) at least you realised what the actual problem is. If you can't get the answer deleted then you could always edit your answer. – Fogmeister May 08 '15 at 22:53