Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

This chapter is from the book

More on Parameters

You already know how to use parameters in functions. As discussed in the following sections, Swift also provides the following:

  • External parameter names
  • Default parameter values
  • Variadic parameters
  • In-out parameters
  • Functions as parameters

External Parameter Names

Usually you create a function with parameters and just pass them. However, external parameters must be written. Part of what makes Objective-C such a powerful language is its descriptiveness. Swift engineers wanted to also include that descriptiveness, and this is why the language includes external parameter names. External parameters allow for extra clarity. The syntax for including external parameter names in a function looks like this:

func someFunction(externalName internalName: parameterType) -> returnType {
  // Code goes here
}

The keyword func is followed by the name of the function. In the parameters of the function, there’s an extra name for the parameters. The whole parameter is an external name followed by an internal parameter followed by the parameter type. The return type of the function follows the function parameters, as usual.

Here’s a function that takes the names of two people and introduces them to each other:

func introduce(nameOfPersonOne nameOne: String, nameOfPersonTwo nameTwo: String) {
    println("Hi \(nameOne), I'd like you to meet \(nameTwo).")
}

Writing this function with external parameters makes it more readable. If someone saw a function called introduce, it might not provide enough detail for the person to implement it. With a function called introduce(nameOfPersonOne:,nameOfPersonTwo:), you know for sure that you have a function that introduces two people to each other. You know that you are introducing person one to person two. By adding two external parameters to the function declaration, when you call the introduce function, the nameOfPersonOne and nameOfPersonTwo parameters will appear in the call itself. This is what it looks like:

introduce(nameOfPersonOne: "John", nameOfPersonTwo: "Joe")
// Hi John, I'd like you to meet Joe.

By including external parameters in functions, you remove the ambiguity from arguments, which helps a lot when sharing code.

You might want your external parameters and internal parameters to have the same name. It seems silly to repeat yourself, and Swift thought it was silly, too. By adding the pound sign (#) as a prefix to an internal parameter name, you are saying that you want to include an external parameter using the same name as the internal one. You could redeclare the introduce function with shared parameter names, like so:

func introduce(#nameOne: String, #nameTwo: String) {
     println("Hi \(nameOne), I'd like you to meet \(nameTwo).")
}

This syntax makes it easy to include external parameters in functions without rewriting the internal parameters. If you wanted to call the introduce function, it would look like this:

introduce(nameOne: "Sara", nameTwo: "Jane")
// Hi Sara, I'd like you to meet Jane.

These external parameters aren’t required, but they do make for much greater readability.

Default Parameter Values

Swift supports default parameters unlike in Objective-C where there is no concept of default parameter values. The following is an example of a function that adds punctuation to a sentence, where you declare a period to be the default punctuation:

func addPunctuation(#sentence: String, punctuation: String = ".") -> String {
    return sentence + punctuation
}

If a parameter is declared with a default value, it will be made into an external parameter. If you’d like to override this functionality and not include an external parameter, you can insert an underscore (_) as your external variable. If you wanted a version of addPunctuation that had no external parameters, its declaration would look like this:

func addPunctuation(sentence: String, _ punctuation: String = ".") -> String {
    return sentence + punctuation
}

Now you can remove the underscore from the parameters. Then you can call the function with or without the punctuation parameter, like this:

let completeSentence = addPunctuation(sentence: "Hello World")
// completeSentence = Hello World.

You don’t declare any value for punctuation. The default parameter will be used, and you can omit any mention of it in the function call.

What if you want to use an exclamation point? Just add it in the parameters, like so:

let excitedSentence = addPunctuation(sentence: "Hello World", punctuation: "!")
// excitedSentence = Hello World!

Next you’re going to learn about another language feature that allows an unlimited number of arguments to be implemented. Let’s talk about variadic parameters.

Variadic Parameters

Variadic parameters allow you to pass as many parameters into a function as your heart desires. If you have worked in Objective-C then you know that doing this in Objective-C requires a nil terminator so that things don’t break. Swift does not require such strict rules. Swift makes it easy to implement unlimited parameters by using an ellipsis, which is three individual periods (...). You tell Swift what type you want to use, add an ellipsis, and you’re done.

The following function finds the average of a bunch of ints:

func average(numbers: Int...) -> Int {
    var total = 0
    for n in numbers {
        total += n
    }
    return total / numbers.count
}

It would be nice if you could pass in any number of ints. The parameter is passed into the function as an array of ints in this case. That would be [Int]. Now you can use this array as needed. You can call the average function with any number of variables:

let averageOne = average(numbers: 15, 23)
// averageOne = 19
let averageTwo = average(numbers: 13, 14, 235, 52, 6)
// averageTwo = 64
let averageThree = average(numbers: 123, 643, 8)
// averageThree = 258

One small thing to note with variadic parameters: You may already have your array of ints ready to pass to the function, but you cannot do this. You must pass multiple comma-separated parameters. If you wanted to pass an array of ints to a function, you can write the function a little differently. For example, the following function will accept one parameter of type [Int]. You can have multiple functions with the same name in Swift, so you can rewrite the function to have a second implementation that takes the array of ints:

func average(numbers: [Int]) -> Int {
    var total = 0
    for n in numbers {
        total += n
    }
    return total / numbers.count
}

Now you have a function that takes an array of ints. You might have this function written exactly the same way twice in a row. That works but we are repeating ourselves. You could rewrite the first function to call the second function:

func average(numbers: Int...) -> Int {
    return average(numbers)
}

Now you have a beautiful function that can take either an array of ints or an unlimited comma-separated list of ints. By using this method, you can provide multiple options to the user of whatever API you decide to make:

let arrayOfNumbers: [Int] = [3, 15, 4, 18]
let averageOfArray = average(arrayOfNumbers)
// averageOfArray = 10
let averageOfVariadic = average(3, 15, 4, 18)
// averageOfVariadic = 10

In-Out Parameters

In-out parameters allow you to pass a variable from outside the scope of a function and modify it directly inside the scope of the function. You can take a reference into the function’s scope and send it back out again—hence the keyword inout. The only syntactic difference between a normal function and a function with inout parameters is the addition of the inout keyword attached to any arguments you want to be inout. Here’s an example:

func someFunction(inout inoutParameterName: InOutParameterType) -> ReturnType {
  // Your code goes here
}

Here’s a function that increments a given variable by a certain amount:

func incrementNumber(inout #number: Int, increment: Int = 1) {
    number += increment
}

Now, when you call this function, you pass a reference instead of a value. You prefix the thing you want to pass in with an ampersand (&):

var totalPoints = 0
incrementNumber(number: &totalPoints)
// totalPoints = 1

In the preceding code, a totalPoints variable represents something like a player’s score. By declaring the parameter increment with a default value of 1, you make it easy to quickly increment the score by 1, and you still have the option to increase by more points when necessary. By declaring the number parameter as inout, you modify the specific reference without having to assign the result of the expression to the totalPoints variable.

Say that the user just did something worth 5 points. The function call might now look like this:

var totalPoints = 0
incrementNumber(number: &totalPoints, increment: 5)
// totalPoints = 5
incrementNumber(number: &totalPoints)
// totalPoints = 6

Functions as Types

In Swift, a function is a type. This means that it can be passed as arguments, stored in variables, and used in a variety of ways. Every function has an inherent type that is defined by its arguments and its return type. The basic syntax for expressing a function type looks like this:

 (parameterTypes) -> ReturnType

This is a funky little syntax, but you can use it as you would use any other type in Swift, which makes passing around self-contained blocks of functionality easy.

Let’s next look at a basic function and then break down its type. This function is named double and takes an int named num:

func double(num: Int) -> Int {
    return number * 2
}

It also returns an int. To express this function as its own type, you use the preceding syntax, like this:

(Int) -> Int

Here you add the parameter types in parentheses, and you add the return type after the arrow.

You can use this type to assign a type to a variable:

var myFunc:(Int) -> Int = double

This is similar to declaring a regular variable of type string, for example:

var myString:String = "Hey there buddy!"

You could easily make another function of the same type that has different functionality. Just as double’s functionality is to double a number, you can make a function called triple that will triple a number:

func triple(num:Int) -> Int {
    return number * 3
}

The double and triple functions do different things, but their type is exactly the same. You can interchange these functions anywhere that accepts their type. Anyplace that accepts (Int) -> Int would accept both the double or triple functions. Here is a function that modifies an int based on the function you send it:

func modifyInt(#number: Int, #modifier:(Int) -> Int) -> Int {
    return modifier(number)
}

While some languages just accept any old parameter, Swift is very specific about the functions it accepts as parameters.

Putting It All Together

Now it’s time to combine all the things you’ve learned so far about functions. You’ve learned that the pound sign means that the function has an external parameter named the same as its internal parameter. The parameter modifier takes a function as a type. That function must have a parameter that is an int and a return value of an int. You have two functions that meet those criteria perfectly: double and triple. If you are an Objective-C person, you are probably thinking about blocks right about now. In Objective-C, blocks allow you to pass around code similar to what you are doing here. (Hold that thought until you get to Chapter 6.) For now you can pass in the double or triple function:

let doubledValue = modifyInt(number: 15, modifier: double)
// doubledValue == 30
let tripledValue = modifyInt(number: 15, modifier: triple)
// tripledValue == 45

Listing 3.1 is an example of creating functions in Swift:

Listing 3.1 A Tiny Little Game

var map = [ [0,0,0,0,2,0,0,0,0,0],
            [0,1,0,0,0,0,0,0,1,0],
            [0,1,0,0,0,0,0,0,1,0],
            [0,1,0,1,1,1,1,0,1,0],
            [3,0,0,0,0,0,0,0,0,0]]

var currentPoint = (0,4)
func setCurrentPoint(){
    for (i,row) in enumerate(map){
        for (j,tile) in enumerate(row){
            if tile == 3 {
                currentPoint = (i,j)
                return
            }
        }
    }
}

setCurrentPoint()

func moveForward() -> Bool {
    if currentPoint.1 - 1 < 0 {
        println("Off Stage")
        return false
    }
    if isWall((currentPoint.0,currentPoint.1 - 1)) {
        println("Hit Wall")

        return false
    }
    currentPoint.1 -= 1
    if isWin((currentPoint.0,currentPoint.1)){
        println("You Won!")
    }
    return true
}

func moveBack() -> Bool {
    if currentPoint.1 + 1 > map.count - 1 {
        println("Off Stage")
        return false
    }
    if isWall((currentPoint.0,currentPoint.1 + 1)) {
        println("Hit Wall")
        return false
    }
    currentPoint.1 += 1
    if isWin((currentPoint.0,currentPoint.1)){
        println("You Won!")
    }
    return true
}

func moveLeft() -> Bool {
    if currentPoint.0 - 1 < 0 {
        return false
    }
    if isWall((currentPoint.0 - 1,currentPoint.1)) {
        println("Hit Wall")
        return false
    }
    currentPoint.0 -= 1
    if isWin((currentPoint.0,currentPoint.1)){
        println("You Won!")
    }
    return true
}

func moveRight() -> Bool {
    if currentPoint.0 + 1 > map.count - 1 {
        println("Off Stage")
        return false
    }
    if isWall((currentPoint.0 + 1,currentPoint.1)) {
        println("Hit Wall")
        return false
    }
    currentPoint.0 += 1
    if isWin((currentPoint.0,currentPoint.1)){
        println("You Won!")
    }
    return true
}

func isWall(spot:(Int,Int)) -> Bool {
    if map[spot.0][spot.1] == 1 {
        return true
    }
    return false
}

func isWin(spot:(Int,Int)) -> Bool {
    println(spot)
    println(map[spot.0][spot.1])
    if map[spot.0][spot.1] == 2 {
        return true
    }
    return false
}

moveLeft()
moveLeft()
moveLeft()
moveLeft()
moveBack()
moveBack()
moveBack()
moveBack()

This is a map game. This game allows the user to navigate through the map by using function calls. The goal is to find the secret present (the number 2). If the player combines the right moves in the move function, he or she can find the secret present. Your current status will read out in the console log.

Let’s step through this code:

  • Line 1: You have a multidimensional array map, which is an array within an array.
  • The function setCurrentPoint finds the 3, which is the starting point, and sets it as the current point.
  • You have four directional functions that move the current point’s x or y position.
  • In each of those functions you check whether you hit a wall using that isWall function.
  • In each of those functions you also move the player’s actual position.
  • After the position is moved you check whether you won the game by seeing whether you landed on a 2.
  • You can call each function one by one and the console will trace out whether you won or not. It will not move if you are going to hit a wall. It will also not move if you are going to go off stage.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020