Colateral
Colateral

Reputation: 1801

String format optional parameter in Swift

Ola,

I don't have to much exp with the Swift language. I want to print into a String some variables and some of them are optional.

func onRegPin(timeOut: Int64, pin: String?)->()
{
  String(format: "Timeout: %d  Pin: %@", timeOut, pin!)
}

If the pin is nil at runtime I got some assert or something.

Is there a way to print this optional parameters using String ?

Upvotes: 4

Views: 14307

Answers (4)

Hamza Ansari
Hamza Ansari

Reputation: 3074

 func onRegPin(timeOut: Int64, pin: String?)->()
    {  if let pin = pin{
      String(format: "Timeout: %d  Pin: %@", timeOut, pin)
     }else{
      String(format: "Timeout: %d  No Pin ", timeOut)
      }
    }

UPDATE: Using default Parameter

func onRegPin(timeOut: Int64, pin:String?="No pin"){
  String(format: "Timeout: %d  Pin: %@", timeOut, pin!)
}

If pin is nil call function only with timeOut

onRegPin(3423)

else if pin is not nil:

onRegPin(3423, pin:"Pin")

Upvotes: 3

Colateral
Colateral

Reputation: 1801

Well the idea was to not check "pin" or to introduce a new var for casting, There is another solution like println:

String(format: "Timeout: %d Pin: %@", timeOut, "\(pin)")

Upvotes: 1

Eric Aya
Eric Aya

Reputation: 70096

What you need is to unwrap the Optional before using it. The standard way in Swift 1.2 is with if let (there's also "nil coalescing" like in @vadian's answer).

Also it looks like your function should return a String, in my example it's an Optional because it could fail:

func onRegPin(timeOut: Int64, pin: String?) -> String? {
    if let pinOK = pin {
        return String(format: "Timeout: %d  Pin: %@", timeOut, pinOK)
    }
    return nil
}

if let regpin = onRegPin(30, "test") {
    println(regpin)   // prints "Timeout: 30  Pin: test"
}

With Swift 2 (Xcode 7) it could be:

func onRegPin(timeOut: Int64, pin: String?) -> String? {
    guard let pinOK = pin else { return nil }
    return String(format: "Timeout: %d  Pin: %@", timeOut, pinOK)
}

if let regpin = onRegPin(30, pin: "test") {
    print(regpin)
}

Upvotes: 2

vadian
vadian

Reputation: 285059

You can do this:
pinValue is an empty string if pin is nil otherwise the unwrapped pin value

func onRegPin(timeOut: Int64, pin: String?)->()
{
  let pinValue = pin ?? ""
  String(format: "Timeout: %d  Pin: %@", timeOut, pinValue)
}

Upvotes: 4

Related Questions