3

I know it is possible to do this like so:

let intValue: Int? = rawValue == nil ? Int(rawValue) : nil

Or even like this:

var intValue: Int?

if let unwrappedRawValue = rawValue {
    intValue = Int(unwrappedRawValue)
}

However I'm looking to find out if there's a way to do this in one expression, like so:

let intValue: Int? = Int(rawValue) // Where Int() is called only if rawValue is not nil
Korpel
  • 2,432
  • 20
  • 30
Jack Wilsdon
  • 6,706
  • 11
  • 44
  • 87
  • you want if intValue is not nil to be assigned with the rawValue? – Korpel Oct 17 '15 at 23:45
  • I want `intValue` to be `Int(rawValue)` if `rawValue` is not nil, otherwise if `rawValue` is nil I want `intValue` to be nil. – Jack Wilsdon Oct 17 '15 at 23:47
  • You can explicitly unwrap it if you are sure it's not nil but other than that your two ways do their job. May i ask what exactly you are trying to make? Or this is a generic question? – Korpel Oct 17 '15 at 23:49
  • It's a generic question, I was just wondering if there's a more 'swift-y' way of doing it. – Jack Wilsdon Oct 17 '15 at 23:49
  • 2
    the most swifty way and the one most developers tend to use is the second one you wrote. The one with the if let statement – Korpel Oct 17 '15 at 23:50
  • You can also have a look at optional chaining to get a bit more to the "heart" of optionals – Korpel Oct 17 '15 at 23:52

2 Answers2

5

Similarly as in Getting the count of an optional array as a string, or nil, you can use the map() method of Optional:

/// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
@warn_unused_result
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?

Example:

func foo(rawValue : UInt32?) -> Int? {
    return rawValue.map { Int($0) }
}

foo(nil) // nil
foo(123) // 123
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
-2

So in order to answer your question and here you can have some optional cases as follows : your first one:

let intValue: Int? = rawValue == nil ? Int(rawValue) : nil

your second one:

var intValue: Int?

if let unwrappedRawValue = rawValue {
    intValue = Int(unwrappedRawValue)
}

third case:

var intValue : Int?
if intValue !=nil
{
//do something
}

fourth case if you are sure the value is not nil

var intValue : Int?
intValue!

The last case will crash your application in case it's value is nil so you might use it for debugging purposes in the future. I suggest you have a look on those links for optional binding and optional chaining from apple's manual

optional Chaining

full apple guide for swift

and to finish with answering your comment section question most developers tend to use this method:

var intValue: Int?

if let unwrappedRawValue = rawValue {
    intValue = Int(unwrappedRawValue)
}

cause it seems to be the most type safe. Your call.

Korpel
  • 2,432
  • 20
  • 30