Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Defining functions

Creating constants Создание константы | Printing values and working with string interpolation | Printing values and working with string interpolation | Converting values | Converting values Преобразование значения | Writing if statements | Writing if statements Написание если заявления | Using the switch statement | Using the switch statement Использование Переключатель | Creating loops in Swift |


Читайте также:
  1. Accessing the Special Functions
  2. Complete set by a basic differential-phase HF defense of WL-110 kV with the functions of reserve defense
  3. Complete set of automation of management a switch 110 kV with the functions DBRS, ARI, FLD (fixing of line disconnecting)
  4. Complete set of automation of management a switch 330 kV with the functions of DBRS, ARI
  5. Complete set of basic differential defense of WL-110 kV (transmission of signal on fibre-optic communication line) with the functions of reserve defense
  6. Courts and Their Functions
  7. Defining and instantiating classes

 

- As in all languages in Swift we want to take sections of our code and wrap the up into modular, reusable pieces, giving those pieces a name. So here is how we write and call our own functions. Now for those of you who are pure object oriented folks and you're trumping up a bit to define your own classes and thinking "Well, I don't need no stinking functions, "everything I write will be a method of a class." Well let me assure you, we'll get to that very soon. But for now assume that everything I'm about to say in the next few minutes about functions is 100 percent relevant when we create our own classes.

So in Swift the necessary keyword is func, so first here's the simplest kind of function, one that takes no input and returns no value, it just performs some behavior. Now notice I have a set of empty parenthesis after the function name, parenthesis may be optional in many places in Swift, but not here. These parenthesis have meaning, I'm being explicit that my function has no input parameters and by convention we use CamelCase for function names in Swift.

Now to call this, not surprisingly, we simply use the function name and again, parenthesis are required when calling to explicitly say we are attempting to pass no values into this function. So, let's next add an input parameter so that we can pass a value inside. So, we've got a function definition and inside the parenthesis we provide information about what data we are passing in, we must provide a name and a type for each parameter and we use the colon here, the type annotation, the same way as when defining variables and constants in Swift, the colon means "is type of", so here our input parameter called name is of type String.

So we can then use that parameter inside the body of the function and to call it you just pass in a literal or a variable of the right type. Now if we wanted to define multiple input parameters what you're going to do then is just separate them with a comma, but both of them need both a name and the type separated by the colon. When calling a function defined this way we just pass in the right data separated by a comma. However there is a vital point to understand about parameters in Swift, folks.

Remember I've said how important constants are in Swift, well by default an input parameter to a function is treated as a constant, not a variable. Let me say that again in Swift, by default, an input parameter is a constant, not a variable, so if I wrote a function definition like this, where we're passing in an input parameter called age and it's of type Int if i try and change that, I'm going to get a compile error because this parameter is a constant.

If I do need to change this value, I could either create a new variable inside my function and copy the value in or there is an option to explicitly make an input parameter into a variable by adding in the keyword var in front of it in the parameter list. It's yet another place where Swift is very specific and will default to immutable values or unchangeable values unless you explicitly tell it otherwise. Next up, if this is how we pass information in, how do we return a value form our function? In many C style languages, you write your return types at the beginning of the function, but not in Swift.

In Swift, the return type of the function comes after any input parameters are defined, so after the parenthesis whether or not we are passing any information into this, we then add a return arrow, the dash and greater then sign and after that, the type, are we returning a string, are we returning an integer, whatever needs to be returned. We don't need a name here, we just need a type. So when you are reading through Swift code it is this return arrow that is the indicator that this function returns a value of some kind.

If you have this return arrow, your function then must have a reachable return statement that will actually return a data type of this kind. So we then call it and we could accept the value coming back from this function into a variable or a constant or we could just use the result of calling this directly in some other statement, like here, a println statement. So next up, how about defining a default value for an input parameter and this is very easy to do but it will require a slight change when we are calling the function. Here's what I mean by that, we begin with a simple function called myFunction, inside the parameter list I'm going to have a parameter of type String and then use the equals John Doe to provide this default initial value, this looks very similar to defining a variable although interestingly type inference does not occur here, I cannot omit the colon type when you're defining the parameters.

So how about when we call this function, well here is the interesting thing, if I just try and call it and pass in a value, this would have worked before we provided the default value but will no longer work now. The important point to understand is that when you start to add default values into your function definitions, and you then want to call the function but not use the default value, you must then name your argument. So this is what I mean by that, we can just call the function passing in nothing, that's perfectly acceptable it will then use the default value of John Doe.

If I want to call it and pass in a value to replace that default, I must provide a named argument, we must use the name of the parameter, in our case it is name, then a colon, then the value, we must explicitly name this piece of data, telling Swift what parameter this value is intended for. Now, this might seem a little odd, having to name our parameters when calling our function, after all there is only one parameter in this function, surely it should understand what this piece of data is intended for, but the reason for this is that if we have multiple parameters defined in a function, let's say we have a function defined with two parameters, a and b, both being given default values of 10 and 50 and then when we call it, what happens if we just pass in a single value? In this case passing in 99, is that meant to replace the default value of a or of b? So this would give you a compile error, you can pass in a single value and you could do it for a, so a:99 or one for b which is 200 or you could pass in a and b, naming both of those parameters, but as soon as you start providing default values for your parameters you need to name the information when you are passing it in.

Some languages might support the optional values by having commas and leaving values blank, but in Swift the way we do that is not only naming parameters when defining the function, but naming our arguments when calling our function. Now thankfully, Xcode will help you autocomplete this information once your functions are defined, so it's very easy to write and it does make for very readable code, this is one of the few nods in Swift to Objective-C where you also name your arguments when calling methods All right, so there are more things that we can do with functions but this is certainly enough to move on and in the next section we're going to move past basic strings and integers and start to explore more complex types in Swift like collections and working with typles and closures.

 

 


Дата добавления: 2015-08-20; просмотров: 90 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Creating loops in Swift Создание петель в Swift| Defining functions Определение функции

mybiblioteka.su - 2015-2024 год. (0.007 сек.)