O'Reilly logo

Beginning Swift Programming by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

APPENDIX Exercise Answers

CHAPTER 1

Exercise 1

	let months = 12
	let daysInWeek = 7
	let weeks = 52

Exercise 2

	var gender = "Female"
	var weight = 102.5      // in pounds
	var height = 1.72       // in meters
	var DOB = "09/25/1970"  // mm/dd/yyyy

Exercise 3

	println("Gender: \(gender)")
	println("Weight: \(weight) pounds")
	println("Height: \(height) meters")
	println("DOB: \(DOB)")

Exercise 4

	var weight = 102.5      // in pounds
	var str = "Your weight is \(weight) pounds"

CHAPTER 2

Exercise 1

The problem with the code is that weightInPounds is inferred to be of type Int, which will cause the error when using it to multiply other Double values.

The first way to fix this is to ensure that you assign a floating‐point value to weightInPounds so that the compiler can infer it to be of type Double:

	var weightInPounds = 154.0
	var heightInInches = 66.9
	var BMI = (weightInPounds / pow(heightInInches,2)) * 703.06957964
	println(BMI)

The second approach is to explicitly declare weightInPounds as a Double:

	var weightInPounds:Double = 154
	var heightInInches = 66.9
	var BMI = (weightInPounds / pow(heightInInches,2)) * 703.06957964
	println(BMI)

The third approach is to explicitly perform a cast on weightInPounds and heightInInches when performing the calculations:

	var weightInPounds = 154
	var heightInInches = 66.9
	var BMI = (Double(weightInPounds) / pow(Double(heightInInches),2)) * 703.06957964
	println(BMI)

Exercise 2

The output for the following statements is as follows. (The statements in bold ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required