lee
lee

Reputation: 8105

Input **nil** into the function swift

Supposed I have function:

cornerRadiusView(image, value:avalue, borderColor: color, borderWidth: avalue, isNeedBorder: false)

And sometimes when call this function I want to input nil for the fields which I not use. How to do that?

Upvotes: 2

Views: 99

Answers (1)

Shamas S
Shamas S

Reputation: 7549

If you have a function like this

cornerRadiusView(image, value:avalue, borderColor: nil, borderWidth: avalue, isNeedBorder: false)

In it anything that can be nil should be an Optional parameter, denoted by ?.

So it's function would look like

func cornerRadiusView(image: UIImage, borderColor: UIColor?, isNeedBorder: Bool)

An excerpt from Apple's Swift Documentation

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This restriction enables you to catch and fix errors as early as possible in the development process.

Upvotes: 2

Related Questions