Default Optional Parameter in Swift Function

Default optional parameter in Swift function

Optionals and default parameters are two different things.

An Optional is a variable that can be nil, that's it.

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).

How to pass a function as an optional parameter Swift

You can easily define a default value for a function as parameter:

func foo(completion: () -> Void = { }) {
completion()
}

You could also have it be nil by default:

func foo(completion: (() -> Void)? = nil) {

When it's an optional closure, you'll have to call it like this:

completion?()

How to make function that some parameters not required in when call it in iOS Swift 3?

You just have to make them nilable.

func myMethod(name name: String? = nil, age age: Int? = nil) {
print(name!)
}

Notice: when yo make parameters optional, you have to be careful about how to unwrap them. usually using if let syntax is helpful.

func myMethod(name name: String? = nil, age age: Int? = nil) {
if let name = name {
print(name)
}
}

you can also provide default value for them:

func myMethod(name name: String? = "Donald", age age: Int? = 10) {
print(name!)
}

SwiftUI view with optional default parameter

Here you go... just define the variables of your View, give them default and you can call them with two different intializations

struct ContentView: View {

var body : some View {
DividerItem(text: "Hello World", isBold: true)
DividerItem(text: "Hello Second World")
}
}


struct DividerItem : View {

var text : String
var isBold = false

var body : some View {
Text(text)
.fontWeight(self.isBold ? .bold : .medium)
}
}

Optional Default Parameter in Swift

You'll have to use Optional strings String? as your argument type, with default values of nil. Then, when you call your function, you can supply a string or leave that argument out.

func test(string: String? = nil, middleString: String? = nil, endString: String? = nil) -> Void {
let s = string ?? ""
let mS = middleString ?? ""
let eS = endString ?? ""
// do stuff with s, mS, and eS, which are all guaranteed to be Strings
}

Inside your function, you'll have to check each argument for nil and replace with a default value there. Using the ?? operator makes this easy.

You can then call your function by supplying all arguments, no arguments, or only the ones you want to include:

test(string: "foo", middleString: "bar", endString: "baz")
test()
test(string: "hello", endString: "world")

Is it possible to have parameters that aren't used as arguments?

You (everyone, really) would really benefit from reading the Swift book, cover to cover.

What you're looking for is called a default value.

func test(paramA: String = "Your default value here") {}

or

func test(paramA: String? = nil) {}

The former is simpler, but more limited. For example, you can't distinguish rather the default value "Your default value here" was used, or whether the caller passed in their own value, which happens to be "Your default value here"). In my experience, the distinction is seldom required, but it's good to call out just in case.

In the latter case, you have the flexibility to handle the optional in many more ways. You could substitute a default value with ??, do conditional binding, map it, etc.

What is the cleanest way in swift to use an optional in a function parameter when nil should return a specific default value?


var anOptionalInt: Int?
let aSpecificDefaultReturnValue: Float = 0.99
let result = anOptionalInt.map { iTake(aNonOptional: $0) } ?? aSpecificDefaultReturnValue

You can use the fact that the Swift Optional enum has a map function, and couple it with the nil coalescing operator:

  • Optional.map looks inside your optional 'box' and (if it finds something in the box) uses the transform you supply to alter your value, or ignores the transform if you have nothing inside the box (i.e. a nil).
  • The nil coalescing operator ?? basically says 'return everything left of me if that thing is not-nil, otherwise return everything right of me'.

How to conveniently pass parameters only if they are not nil in swift?

Create two functions:

someInitialiser(paramA: String?, paramB: Int?) {
someInitializer(paramA: paramA ?? "defaultA", paramB: paramB ?? 23)
}

someInitialiser(paramA: String, paramB: Int) {
...
}

You are really overthinking the problem. If you want default values for nil, then ?? is the correct solution. If you don't want to use it outside the function, then you have to let the parameters to be optional and use ?? inside.



Related Topics



Leave a reply



Submit