ming chen
ming chen

Reputation: 680

How to concise the following swift code like kotlin do?

example swift code

func example(someInt:Int, someNullableInt:Int?)->String{
  let firstString = convertAnIntegerToStringButTakesOnlyNonNullInt(someInt)
  let secondString: String?
  if let nowItsNotNull = someNullableInt{
    secondString = convertAnIntegerToStringButTakesOnlyNonNullInt(nowItsNotNull)
  } else {
    secondString = nil
  }
  return firstString.append(secondString ?? "")

}

while the Kotlin code can be more concise like below:

fun example(someInt:Int, someNullableInt:Int?):String = someNullableInt?.let{
 convertAnIntegerToStringButTakesOnlyNonNullInt(someInt)+convertAnIntegerToStringButTakesOnlyNonNullInt(it)
  } ?: convertAnIntegerToStringButTakesOnlyNonNullInt(someInt)

How do I concise my swift code like the kotlin one?

Upvotes: 0

Views: 80

Answers (2)

user652038
user652038

Reputation:

This pattern is Optional.reduce, but that method is not included in the standard library. You will need to include it in your own package.

someNullableInt.reduce(convertAnIntegerToStringButTakesOnlyNonNullInt(someInt)) {
  convertAnIntegerToStringButTakesOnlyNonNullInt($1) + $0
}
public extension Optional {
  /// Modify a wrapped value if not `nil`.
  /// - Parameters:
  ///   - makeResult: arguments: (`resultWhenNil`, `self!`)
  /// - Returns: An unmodified value, when `nil`.
  func reduce<Result>(
    _ resultWhenNil: Result,
    _ makeResult: (_ resultWhenNil: Result, _ self: Wrapped) throws -> Result
  ) rethrows -> Result {
    try map { try makeResult(resultWhenNil, $0) }
    ?? resultWhenNil
  }
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 271175

?.let translates to map in Swift, so the Kotlin code translates to:

func example(someInt:Int, someNullableInt:Int?) -> String {
    someNullableInt.map {
        convertAnIntegerToStringButTakesOnlyNonNullInt(someInt) +
        convertAnIntegerToStringButTakesOnlyNonNullInt($0)
    } ?? convertAnIntegerToStringButTakesOnlyNonNullInt(someInt)
}

This can be made shorter:

func example(someInt:Int, someNullableInt:Int?)->String{
    convertAnIntegerToStringButTakesOnlyNonNullInt(someInt) +
    (someNullableInt.map(convertAnIntegerToStringButTakesOnlyNonNullInt) ?? "")
}

Upvotes: 2

Related Questions