## Kinderswift 8 Challenge Answers

Watch the video for any commentary. Here are two answers. There a lot of possible ones.

```func blueColor(blueVal:Int) -> UIColor {
let color = CGFloat(CGFloat(blueVal) / 255.0)
return UIColor(red: 0.0, green: 0.0, blue: color, alpha: 1.0)
}

blueColor(255)
blueColor(23)
blueColor(128)
```

```
//necessary code to run the answer
func pizzaArea(z:Double) ->Double {
//area of pizza : pi * z * z = a
let pi = 3.14159265358
return pi * z * z
}

func deepDishVolume(diameter:Double,height:Double){
let radius = diameter * 0.5
let area = pizzaArea(radius)
let volume = area * height
}

deepDishVolume(13, 2)

```

# Transcript

In our last lesson we learned about functions. Swift, and most modern programming languages are nothing more than writing groups of your own functions. In this lesson, we will write our own functions.

In our last lesson you may remember this function

```UIColor(white: alpha:)
```

Which made varying colors of gray. Let’s start by making our own custom function like it, but for various shades of red. Make a new playground, and in the playground type this:

```func myColorRed(myRed:CGFloat) -> UIColor{
return UIColor(red:myRed, green: 0.0, blue: 0.0, alpha: 1.0)
}
```

Let’s explain the parts of a function. Like we started variables with `var` or constants with `let`, we start functions with `func`. This tells Swift we are writing a function. We next give an identifier for the function, which will be its name. Generally, the identifier starts with a lower case letter.

Immediately after the identifier we have a parameter list surrounded by parentheses. If we have more than one parameter, we separate them with commas. Note each parameter is like an explicit assignment with var.

```
var myRed:CGFloat = 0
```

Instead of assigning any value though, the function will get a value when we use the function and place a value int he parameter.

We then write an arrow made from a dash and greater than symbol, followed by the type. This tells us the type of the value returned from the function. This function returns a value of type `UIColor`.

We then have curly braces surrounding some code. This is known as a code block. You will find that we use the curly braces a lot to make code blocks in Swift.

Inside the code block, usually the last line of the code, you will find return and a value. In this case we use the `UIColor` initializer to return a red color.

Let’s try this. Type these in

```
myColorRed(1.0)
myColorRed(0.5)
myColorRed(0.86)
myColorRed(0.92)
myColorRed(0.66)
```

And we get different values of red.

Let’s try a more complicated example. Type this:

```func pizzaArea(z:Double) -> Double {

// area of a pizza: pi * z * z = a
let pi = 3.14159265358
return pi * z * z
}
```

This finds the area of a circular pizza using `z` as a radius of circle. `z `is a `Double` and we return a `Double`. We set a constant of `pi`, and then return `pi` times `z` squared.

Try this function out.

```pizzaArea(3.0)
pizzaArea(6.0)
pizzaArea(12.5)
```

Most of the time we do not measure a pizza’s radius but it’s diameter. We say 14 inch diameter or 35cm diameter, not a 7 inch or 17.5 cm radius.

Some functions do not return a value, they do something else, such as print the results. There is a special function to print out results to the console, called `println`. You place a value or values separated by commas in the parameter and print line will print them to the console.

Let’s combine both the diameter problem and an example of a `println` function into one function. Add this to the playground

```func printPizzaArea(diameter:Double){
let radius:Double = diameter / 2.0
let area = pizzaArea(radius)
}
```

You will notice the arrow is missing. If we do not return a value, we do not add it to the function declaration. We do have a parameter diameter of Double.

In the code block, we find the radius by dividing the diameter by two. We find the area by using our already defined area function. Our third line prints the radius and area to the console.

For a fourteen inch pizza we can type this:

```printPizzaArea(14.0)
```

and it works, but we see nothing. You need to open the console click here to open it

and you will see a new window on the playground with our answer.

Now try a pizza at 35 cm

```printPizzaArea(35.0)
```

We get an answer. Our answer does not look very user-friendly though. In our next lesson we’ll look at Strings and formatting.

# Challenge Work

If you’d like an assignment until next time here’s two things to try:

Make a `blueColor` function which returns a blue color as a `UIColor` from an `Int` value from 1 to 255.

Make a function to calculate the volume of a deep dish pizza and print the radius, area and height to the console. . Use a diameter and height parameter and the area function we already defined. A hint is the volume is the height time the area.

I’ll post the answers in another video

## KinderSwift 7: Introduction to Functions

This session we will learn about functions by making colors with UIColor.

# Transcript

Welcome to lesson 7 of KinderSwift.

In our last lesson we used this

```Double (2)
```

to convert a `Int` into a `Double` and this

```Int (2.5)
```

to convert a D`ouble` into a `Int`. Both of these are functions.

Functions take the data within the parentheses and change it into something else.

Most of Swift is made up of using or creating functions. There are math functions such as this one:

```sqrt(100.0)
```

Which calculates the square root of 100 or this that calculates ten to the power of 3

`pow(10.0,3.0)`

Here we have more than two numbers in the parentheses separated by commas. Each of these is a parameter. A function may have any number of parameters.

Functions are not just for numbers. For example this:

`UIColor(white: 0.5, alpha: 1.0)`

Is a function with two parameters. Often you will see identifiers for the parameters, in this case `white` and `alpha`. This function makes different colors between black and white.

Here is a function with four parameters.

`UIColor(red: 1.0, green: 0.8, blue: 0.2, alpha: 1.0)`

This function has a range. The parameters can be from 0 to 1.0. We will need to find documentation to tell us this though. Often you can get to the documentation by clicking the mouse button while hitting option while on a keyword. You can get the most information by clicking the Class reference link.

Functions may have other expressions, even functions or variables inside them. Often colors get described as values of Red green and blue in a range from 0 to 255. We might have a color described by. (255, 90, 00). We need to divide by 255 to get a range of 0 to 1. We can write that like this:

`UIColor(red: 255.0/255.0, green: 90.0/255.0, blue: 0, alpha: 1.0)`

Parameters do have type. We can guess that the `UIColor` function has the type `Double`,but we would be wrong. It has a new type for us `CGFloat`. `CGFloat` is a floating point number like Double, but used for computer graphics.

Let’s try a variable. Type this:

```var myRed = 255.0/255.0
UIColor(red: myRed, green: 0.8, blue: 0.0, alpha: 1.0)```

you get an error.

`myRed` is the wrong type. It is a `Double` not a `CGFloat`. We have to declare it `CGFloat` to work here. Compilers like Swift are very fussy about this. `CGFloat` and `Double` might look the same to us, but not to Swift.

Add a type to `myRed`,

```var myRed:CGFloat = 255.0/255.0
```

and everything is okay.

How can we tell what type to use? One way is we watch autocomplete type the statement for us: Try it, Type this

```UIColor(
```

We get this:

You’ll see that the parameters give their type, just like we assigned types with var and let. `UIColor` uses `CGFloats`.

You will also notice something else. there are a lot of functions named `UIColor`, but with very different parameters. Most of these you will never use, but there a few you might. We’ll discuss which ones in a few lessons when we start making user interfaces.

There are so many functions for `UIColor` because is `UIColor` is a type. You might have noticed we broke the rule about a lowercase letter for an identifier in a lot of these functions such as `Int()` or `Double(),` though `sqrt()` and `pow()` are both lowercase.

Ones with capital letters are all special functions called Initializers. They set the initial value of a type. Usually we assign them like this:

```var myColor = UIColor(red: 1.0, green: 0.8, blue: 0.2, alpha: 1.0)
```

We can then use `myColor` later in our program. Like `Int` or `Double` sometime we use them once to cast a type without assigning them.

For example I can cast `myBlue` which is a Double into a `CGFloat` if I need to in my `UIColor` function like this:

```var myRed:CGFloat = 255.0/255.0
var myBlue = 200.0/255.0
UIColor(red: myRed, green: 0.8, blue: CGFloat(myBlue), alpha: 1.0)
```

Another name for a type is a Class. While there really is no difference between a class and a Type in Swift, the general rule is classes are more complex types. `UIColor` is a class which has its own functions and variables. Classes will be our focus for many of our upcoming lessons, but to get your feet wet, I’ll introduce another type of function: A class method.

`UIColor` has a lot of class methods, many without parameters. Instead it has a blank parentheses pair. You use class methods by stating its type then a dot, then the function. for example there is this:

```UIColor.blackColor()
```

and this

```UIColor.greenColor()
```

There are many more of these. Before the next lesson play around with some of the UIColor Class methods and the Red:green:blue:alpha: initializer. You can scroll for them in autocomplete or you can use this list:

Next time we’ll make our own functions.

## KinderSwift 6: Types and Casting

In this lesson we cover how to explicitly type an identifier and how to use casting to force its type.

# Transcript

Welcome back to kinderswift. episode 6. In our last lesson, we left off with this not working:

```//can't mix types:
//doubleResult = myDouble + myInteger
```

Swift does not let you mix types. This lesson we will learn a little more about types and then how we can get this to work.

We already saw how to declare a double and an integer automatically. We call this implicit typing. In implicit typing, Swift guesses at the type.
so when we type:

```var myInteger  = 0
```

the lack of a decimal point makes Swift guess this is an integer. Similarly

```var myDouble = 0.0
```

the decimal point makes Swift guess that `myDouble` is type `Double`. We can also explicitly declare

```var myInteger:Int = 5
var myDouble:Double = 5
```

You will see that Swift accepts both. `myInteger` is 5 and `myDouble` is 5.0 , even though we left off the decimal point `myDouble` is a `Double`. The difference is after the identifier we added a colon, then a type.

We know two types so far: Int for integers and Double for doubles. The colon forces Swift to make the identifier that type without guessing.

I can force a `Int` 5 to be a `Double` 5.0. Can I declare a `Double` as an `Int`? Try this:

```var myOtherInteger:Int = 5.0
```

We get an error. Erase the decimal point and everything is fine.

```var myOtherInteger:Int = 5
```

No, we cannot assign a `Double` to an Int`.`

So for a little test what would this statement do?

```myDouble = 3.5
myInteger = myDouble
```

Try it. type it in.

If you guessed we would get an error assigning a double to an integer, you are correct.
since you know that, you can be pretty certain this will also have an error:

```myInteger = 4
myDouble = myInteger
```

What if you did want to assign integers to doubles and vice versa. What if you needed to add an integer to a double? There is a way called type casting. We take the value and force it to be a certain type. We do this by giving the type and then enclosing the value in parentheses

comment out the error lines using // type this:

```Int(4.5)
Double(3)
```

We see in the results we get a value of 4 and a value of 3.0. `Int` casting will cut off the part after the decimal point, `Double` just adds one. We can use casting on variables too. Uncomment the lines we just commented. Now change them to:

```myDouble = Double(myInteger)
```

and

```myInteger = Int(myDouble)
```

Now they work. Now we can fix our problem from before.

```var doubleResult = myDouble + myInteger
```

How would you fix this?

We want a result of Double. We have a `Double` and an `Int` in the equation. Most likely we will change `myInteger` to `Double` like this.

```var doubleResult = myDouble + Double(myInteger)
```

The way we cast `Int()` and `Double()` uses something called functions. In our next lesson we’ll discuss using functions a little bit more — including a few colorful ones.

## Swift Swift: Using Auto Layout with Size Classes

Last week we looked at the basics of auto layout, this week, we learn

• Diagonal Control Drag
• Using the layout error  panel for misplaced layouts
• Introduce Size Classes
• Make a different layout for iPhone in portrait with Size Classes

# Transcript

Hello, I’m Steve from MakeAppPie.com. In this video we are going to learn some more about Auto Layout and how to use Xcode’s new size classes feature. We’ll start with the completed project from the last video, so you might want to check that out first:

In the last project we made a universal app like this:

It works the same for iPhone and iPad. It also works the same for each device in both landscape and portrait. Size classes let us customize certain devices or orientations for a different layout than this generic layout.

If you click the width and height size class you will get a popup with a bunch of squares on it. This allows you to set the size class you want to work with.

There are three sizes for size classes: compact, any, and regular. Any is the generic size that works with anything. Our current layout, as we can see on the bottom the story board is width:any height:any. This layout is for all cases.

iPhones and the iPod touch are the compact size in both landscape and portrait, with one exception.

For both width and height, iPad is the regular size. The width in landscape is regular for an iPhone 6+.

In our application, we will change the location of the three buttons from above and below the text file to left side of the text field for the compact iPhones in landscape, and leave them the way they are in portrait. For the iPad and iPhone 6, we’ll move all three buttons to the top of the screen in our next video.

In the storyboard, click the width:any height:any button on the bottom of the storyboard. Move the square to any width, compact height for a iPhone in landscape.

Set up Xcode with the preview mode to have the phones in landscape so we can check them as we go through the steps. if you have the file browser open, you may want to close it to give yourself more room. Keep the document outline open.

To start let’s move the text view to the new location. Select the text view in the document outline. Select clear constraints in the constraints resolver. Drag the left handle so the view is less wide than the cheese button. We want to have a relationship to the pizza label, not the cheese button, so we can’t use the pin menu. Control drag from the text view to the label and release. select Vertical Spacing.

Since we will be moving the done button, we want a relationship with the bottom of the container, not the button. We also want a relationship with the right margin. We can do both at once with a diagonal drag. Control-drag from the text view to the bottom right corner. Xcode give us both trailing and bottom constraints. Shift click the Bottom space to container margin and Trailing space to container margin, then press return. Xcode adds both constraints.

As the warning indicates, we still have one more constraint to go, but we will get to that in a minute. Clear the constraints on the Cheese button. Move it under the pepperoni button.

Select pin and pin the cheese to the pepperoni 10 points away and the left margin 0 points away. Update the frames to the new constraints.

As you can see in the preview window, the buttons are now too small. Let’s fix the height first. Control drag from Cheese to Pepperoni and shift-select equal widths and equal heights. Remember pepperoni has an explicit width of 64, so that will make both 64 points high.

We get several layout error, but we can see in the preview that they are now the right width. Note on the preview that the text view has disappeared. That’s because we still didn’t set its width, which we’ll do as an equal width to the buttons, and have a space between them of 10 points.

Control drag from the pepperoni button to the text view. Shift select Horizontal spacing and equal widths, then press return. We get more errors. Click on the horizontal spacing constraint we just made, and in the inspector change the constant to 10 and press tab.

The preview shows we have the correct horizontal spacing but the storyboard shows errors. You’ll notice a small error indicator in the upper right corner of the inspector. If you click it, you will see your errors. All are misplaced views.

Select cheese on the storyboard, and click update frames for the selection. That fixes that.

You can also resolve misplaced views in the error panel. Select the warning icon for pepperoni and a pop up lets you update the frame. Select Update Frame and click Fix Misplacement. Now pepperoni is correct.

Go back to the document outline and select the text view. Scroll to the constraints and change the top space to 10 points and the bottom space to 20. Select Text View in the outline and in the resolver Update selected frames

We need to lay out the done button next, which is now under the text view.  In the outline, select the Done button. Clear its constraints.

In the done button. we won’t bleed off the edge this time. We will instead align it with the other buttons. Pin the done button to the left margin with 0 and the bottom to 20. Update the frame.

You can control drag from the outline too, for cases where you can’t see you frame. Control drag from the done button in the outline to the text view. select horizontal spacing. Now in the inspector change trailing space to text view to 10.

Lets set the size of the button. Control drag from the done button to the pepperoni button. Select equal widths and equal heights. We get a constraint error which is just a misplaced view. Click the icon and fix the misplacement.

We’ve completed the re-arrangement for the iPhone and iPod touch. In the preview, rotate the device, and you will see that it only arranges itself like this in landscape.

Go over to the iPad, and it ignores this.

The iPhone 6 plus is not happy though. This is okay for now, because in out next lesson, we are going to make a different layout for regular width any height layouts.