Swift Help

MACOS Assignments
Download Help Files
Video Help Files
Data Types
Operators
Comparison Operators
Assignment Operators
Logical Operators
Range Operators
Ternary Operators
Bitwise Operators
Declaring Variables
Declaring Constants
Printing on the Console
Referencing GUI Objects
Creating Objects
Creating Functions
arc4random_uniform()
If Else Statements
Switch Statements
For Loops
While Loops
arc4random()
Arrays
Dictionary
Built In Functions
Trimming white space from a String
Number Conversions with a String
Strings
Joining Strings (Concat)
Optionals
Screen Size
User Interface Objects
Play Music
==================== ====================

Data Types

==================== ==================== Type Swift name Short form How it’s used Integer Int Int For storing whole numbers and negative numbers, for Double Double Dbl To store decimal values like 12.54, 8.23, -2.68, 89.99, 3.14159 Boolean Bool Bool Used for storing true/false values. String String Str Strings are used to store text. You will need to put import UIKit at the top of your program ==================== ====================

Operators

==================== ==================== Binary operators need to have operands on both sides. 5 + 7 // 5 is an operand + is an operator 7 is an operand + - * / % (modulus or remainder) NOTE: Operators cannot operate on different types when you are using variables. You must convert the variables to matching types. Example: var x = 5 var y = 3.14159 var z = x + y // Not Ok (int + double) print(x + y) // Not Ok (int + double) var z = Double(x) + y // Ok var z = x + Int(y) You do not have to match types with constants. Example: print(7 + 3.14159) // Ok Also, you must be consistent with spaces. var x = 5 var y = 8 x + y Ok x+ y Not Ok x +y Not Ok x+y Ok ==================== ====================

Comparison Operators

==================== ==================== > >= < <= == != Example: var x:Int = 25 var y:Int = 8 if x > y { print(String(x) + " is greater than " + String(y)) // or print("\(x) is greater than \(y))" } ==================== ====================

Assignment Operators

==================== ==================== = += -= *= /= %= &&= ||= NOTE: The ++ and -- operators have been removed. ==================== ====================

Logical Operators

==================== ==================== // Not And Or ! (not operator) && (and operator) || (or operator) Examples: !true is false !false is true 5 > 4 is true 5 >= 4 is true 5 < 4 is false ==================== ====================

Range Operators

==================== ==================== 5...8 // 5 6 7 8 5..<8 // 5 6 7 Example: for i in 5...8 { print(i) } ==================== ====================

Ternary Operators

==================== ==================== condition ? do true : do false print("Largest number is \(x > y ? x : y)") // Example: // if x = 5 and y = 7 var x = x > y ? 5 : 8 // x will be 8 ==================== ====================

Bitwise Operators

==================== ==================== ~x = 2's complement & = bitwise and | = bitwise or ^ = exclusive or << = shift left >> = shift right &= |= ^= <<= >>= =================== ===================

Declaring Variables

=================== =================== A variable name must start with a letter or an underscore. You can then use other letters, underscores, or digits in your variable name. However, you cannot use any special characters in a name. It is best to give a variable a beginning value, unless it could be undefined later. If you do NOT assign a beginning value, it will be an Optional type. var variableName: Int = 50 OR var variableName = 50 YOU CAN NOT SAY var variableName YOU CAN SAY var variableName:Int! YOU CAN SAY var variableName:Int? YOU CAN SAY var variableName:Int (but you must assign it a value later) var x: Int = 50 OR var x = 50 var y: Int! // no value assigned (an optional) // You will need to unwrap it to use as an int var y: Int? // no value assigned (an optional) // You will need to unwrap it to use as an int // It is best to use if let y = y { } var y // this will NOT work (it must have a data type) var z: Int = 85 OR var x = 85 var a: Double = 25.7 OR var a = 25.7 var msg: String = "Hello World" OR var msg = "Hello World" var found = true (or false) OR var found: Bool = true var index: Int! (an optional must unwrap or use if let ...) index = 5 if index != nil { // index variable has a value assigned to it } else { // index variable has no value assigned to it } NOTE: You can generally avoid doing this by simply assigning a value when you declare your variable. var index: Int? // unknown value (another optional) index = 3 var treeArray = ["Oak", "Pine", "Yew", "Birch"] if index != nil { print(treeArray[index!]) // index is unwrapped } else { print("index does not contain a value") } var index: Int? index = 3 var treeArray = ["Oak", "Pine", "Yew", "Birch"] if let myvalue = index { print(treeArray[myvalue]) } else { print("index does not contain a value") } =================== ===================

Declaring Constants

=================== =================== If you do NOT plan to change a variable, you should make it a constant with let let variableName = 5 OR let variableName: Int = 5 let x = 5 let title = "On Golden Pond" let msg: String = "Hello" ======================= =======================

Printing on the Console

======================= ======================= We can use \(variablename) to print out the value of variablename. This is known as interpolation. Use terminator:"" to stay on the same line. Example: print("Hello", terminator:" ") print("World") // prints Hello World Example 1: // prints x is 5 var x = 5 print("x is \(x)") Example 2: // prints Hello World print("Hello World") Example 3: // prints The message is Bye. Wow! var msg = "Bye" print("The message is \(msg). Wow!") Example 3: // prints 5 + 4 is 9. I thought it was 9. print("5 + 4 is \(5+4). I thought it was 9.") We can also convert the value of a variable to a String Example 1: // prints x is 5 var x = 5 print("x is " + String(x)) Example 2: // prints The message is Bye. Wow! var msg = "Bye" print("The message is " + msg + ". Wow!") Example 3: // prints The message is Bye. Wow! x is 5. e is 2.71. var msg = "Bye" var x = 5 var e = 2.71 print("The message is %@. Wow! x is %d. e is %.2f.", msg, x, e) ======================= =======================

Referencing GUI Objects

======================= ======================= @IBOutlet var outputLabel: UILabel! @IBOutlet var userTextField: UITextField! var str = userTextField.text! outputLabel.text = str var numberAsString = userTextField.text! if let number = Int(numberAsString) { // do something useful with this number // the number is a valid number at this point } else { // show an error to the user } // Clearing a Text Field userTextField.text = "" // NOTE: DO NOT PUT A SPACE " " in a Text Field ================ ================

Creating Objects

================ ================ import Foundation // to inherit, do // class Person: SuperClass // where SuperClass is the name // of the class that you want to inherit class Person { var firstName = "" // or var firstName: String var lastName = "" // or var lastName : String var age = 0 // or var age: Int // etc. init() { firstName = "" lastName = "" age = 0 } init(firstName:String, lastName:String, age:Int) { self.firstName = firstName self.lastName = lastName self.age = age } func getFirstName() -> String { return firstName } func getAge() -> Int { return age } func printMessage() { print "Hello" } // a class or static function // you call class functions by using the name // of the class // var color = Person.getFavoriteColor() class func getFavoriteColor() -> String { return "Red" } } In order to create a Person object you can: // creates a variable that can refer to a Person object var person: Person // creates the Person object person = Person() OR person = Person("Sue", "Baker", 16) OR person = Person(firstName:"Sue", lastName:"Baker", age:16) var firstName = person.getFirstName() Example: A Book class ===================== import Foundation class Book { var title: String = "" var author: String = "" var description: String = "" } ==================== ====================

Creating Functions

==================== ==================== func name of function (_ variableName: variableType, _ variableName: variableType, ... ) -> return type { // Function code } See the following link for more help. https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html ========================================================= Example: an example with no parameters and no return type func sayHello() { print("Hello Swift") } } sayHello() // prints Hello Swift ========================================================= ========================================================= // an example with 2 parameters and a String return type NOTE: _ name means that we do NOT use a label in the call statement func buildMessage(_ name: String, _ count: Int) -> String { return("\(name), you are customer number \(count).") } // a call statement with NO labels let message = buildMessage("John", 100) print(message) // prints John, you are customer number 100. ========================================================= ========================================================= // an example with 2 parameters and a String return type // NOTE: There is no _ before the variable func buildMessage(name: String, count: Int) -> String { return("\(name), you are customer number \(count)") } // a call statement with labels let message = buildMessage(name:"John", count: 100) ========================================================= ========================================================= func buildMessage(name: String, _ count: Int) -> String { return("\(name), you are customer number \(count)") } let message = buildMessage(name:"John", 100) ========================================================= ========================================================= func buildMessage(username name: String, count: Int) -> String { return("\(name), you are customer number \(count)") } When declared in this way, the external parameter name must be referenced when calling the function: let message = buildMessage(username: "John", count: 100) ========================================================= ========================================================= func buildMessage(username name: String, usercount count: Int) -> String { return("\(name), you are customer number \(count)") } ========================================================= ========================================================= func buildMessage(name: String = "Customer", count: Int ) -> String { return ("\(name), you are customer number \(count)") } let message = buildMessage(count: 100) print(message) ========================================================= ================================= =================================

arc4random_uniform()

================================= ================================= NOTE: This is deprecated in 4.2. Int and Double objects now have a similar method. ========================================================= Example: -------- //get a random number between 0-100 randomNumber = Int(arc4random_uniform(101)) ========================================================= Methods: -------- arc4random_uniform(101) ========================================================= let ran = arc4random() // some Int number let ran = arc4random_uniform(100) // 0...99 let ran = arc4random_uniform(6) // 0...5 let ran = arc4random_uniform(6) + 1 // 1...6 let ran = arc4random_uniform(52) // 0...51 let ran = arc4random_uniform(52) + 1 // 1...52 ================================= ================================= Read from the console ================================= ================================= // this is no longer supported // as of Swift 3 for iOS apps. // However, it is supported for console apps. var response = readline(); ================================= =================================

if else

================================= ================================= if boolean expression { // Swift code to be performed when // expression evaluates to true } ========================================================= var j = 5 if j > 0 { some_code() } ========================================================= ========================================================= var disc = b*b - 4*a*c; if disc > 0 { } else if disc == 0 { } else { } ========================================================= ========================================================= if totalSpent > discountThreshold { discountPercent = 10 } ========================================================= ========================================================= let x = 9 if x == 10 { print("x is 10") } else if x == 9 { print("x is 9") } else { print("x is not 9 or 10") } ========================================================= ================================= =================================

Switch

================================= ================================= switch expression { case match1: statements case match2: statements case match3, match4: statements default: statements } ========================================================= Example: let value = 4 switch (value) { case 0: print("zero") case 1: print("one") default: print("Integer out of range") } ========================================================= ========================================================= Example: let value = 1 switch (value) { case 0, 1, 2: print("zero, one or two") case 3: print("three") case 4: print("four") case 5: print("five") default: print("Integer out of range") } ========================================================= ========================================================= switch (temperature) { case 0...49: print("Cold") case 50...79: print("Warm") case 80...110: print("Hot") default: print("Temperature out of range") } ========================================================= ========================================================= let temperature = 54 switch (temperature) { case 0...49 where temperature % 2 == 0: print("Cold and even") case 50...79 where temperature % 2 == 0: print("Warm and even") case 80...110 where temperature % 2 == 0: print("Hot and even") default: print("Temperature out of range or odd") } ========================================================= ========================================================= let temperature = 10 switch (temperature) { case 0...49 where temperature % 2 == 0: print("Cold and even") fallthrough case 50...79 where temperature % 2 == 0: print("Warm and even") fallthrough case 80...110 where temperature % 2 == 0: print("Hot and even") fallthrough default: print("Temperature out of range or odd") } ========================================================= ================================= =================================

For Loops

================================= ================================= for constant name in collection or range { // code to be executed } ========================================================= Example: index would be 1 2 3 4 5 for index in 1...5 { print("Value of index is \(index)") } ========================================================= ========================================================= Example: index would be 1 2 3 4 for index in 1..<5 { print("Value of index is \(index)") } ========================================================= ========================================================= Example: index would be 5 4 3 2 1 for index in (1...5).reversed() { print("Value of index is \(index)") } ========================================================= ========================================================= Example: index would be 0 2 4 6 8 10 for index in stride(from:0, to:10, by:2) { print("Value of index is \(index)") } ========================================================= ========================================================= Example: i would be 0 1 2 3 4 let numbers = [2, 3, 5, 7, 9] for i in numbers.indices { print("Value of index is \(i)") } ========================================================= ========================================================= Example: num would be 2 3 5 7 9 let numbers = [2, 3, 5, 7, 9] for num in numbers { print("Value of number is \(num)") } ========================================================= ================================= =================================

While Loops

================================= ================================= You can break out of a loop with the keyword break You can continue a loop with the keyword continue (come through again). while condition { // Swift statements go here } ========================================================= var x = 0 while x != 5 { // do something x = x + 1 } ========================================================= ========================================================= var myCount = 0 while myCount < 100 { myCount = myCount + 1 } ========================================================= ================================= ================================= repeat loops (or do while loops) ================================= ================================= repeat { // Swift statements here } while conditional expression In the repeat ... while example below the loop will continue until the value of a variable named i equals 0: ========================================================= var i = 10 repeat { --i } while (i > 0) ========================================================= ================================= =================================

arc4random()

================================= ================================= (this has been deprecated for Swift 4.2) let ran = arc4random() // some Int number let ran = arc4random_uniform(100) // 0...99 let ran = arc4random_uniform(6) // 0...5 let ran = arc4random_uniform(6) + 1 // 1...6 let ran = arc4random_uniform(52) // 0...51 let ran = arc4random_uniform(52) + 1 // 1...52 ================================= =================================

Arrays

================================= ================================= See more at: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html Example 1: ---------- var players = [String]() players.append("Bill") players.append("Sue") players.append("Jill") players[0] = "Tim" for player in players { print(player) } Example 2: ---------- var players:[String] = ["Bill", "Sue", "Jill"] players[0] = "Tim" for player in players { print(player) } Methods: -------- append(object) - adds a new object to the end of the list you can also do list += [object] insert(object, at:1) - inserts the object at position 1 swapAt(1,3) - swaps the elements at postions 1 and 3 sort() - sorts the elements from small to large min() - returns the smallest element max() - returns the largest element remove(at:2) - removes the element at position 2 removeAll() - removes all elements from the list removeFirst() - removes and returns the first element removeLast() - removes and returns the last element popLast() - removes and returns the last element (Optional) first - returns the object in the zero position (Optional) last - returns the object in the last position (Optional) startIndex - accesses property, value of starting index endIndex - accesses property, value of ending index isEmpty - accesses property, value of true if empty count() - returns the number of elements in the list reversed() - returns the array in the reversed order ========================================================= var myArray: [String] = ["One", "Two", "Three"] print (myArray[0]) print (myArray[1]) print (myArray[2]) var entries = myArray.count ========================================================= ========================================================= var myArray: [String] = ["One", "Two", "Three"] myArray.append("Four") myArray.append("Five") myArray.append("Six") ========================================================= ========================================================= var myArray: [String] = ["One", "Two", "Three"] myArray += ["Four", "Five", "Six"] ========================================================= ========================================================= var myArray: [String] = ["Two", "Three"] myArray.insert("One", atIndex: 0) ========================================================= ========================================================= var myArray: [String] = ["One", "Two", "Three"] myArray.removeAtIndex(1) for myString in myArray { print(myString, terminator:" ") // stays on same line } ========================================================= ================================= =================================

Arrays 2D

================================= ================================= Example 1: ---------- var numbers = [ [80, 90, 95], [83, 87, 91], [93, 95, 97] ] for r in 0..<numbers.count { for c in 0..<numbers[r].count { print(numbers[r][c], terminator:" ") } print() // moves to the next line } Example 2: ---------- var numbers = [[Int]]() for _ in 1...3 { var row = [Int]() for _ in 1...4 { row.append(0) } numbers.append(row) } Example 3: ---------- var rectangles = [[Rectangle]]() for _ in 1...3 { var row = [Rectangle]() for _ in 1...4 { row.append(Rectangle(15,20)) } rectangles.append(row) } Example 4: ---------- var players = [[String]]() playersRow = ["Bill", "Sue", "Jill"] players[0].append(playersRow) playersRow = ["Sam", "Tia", "Bob"] players[1].append(playersRow) for r in 0..<players.count { for c in 0..<players[r].count { print(players[r][c], terminator:" ") } print() // moves to the next line } ================================= ================================= ================================= // Dictionary ================================= =================================

Dictionary (Associative Array)

Key Value Pairs ================================= ================================= ========================================================================= Example: var person: [String: String] = ["firstName": "John", "lastName": "Doe"] print(person["firstName"]) person["firstName"] = "Joe" // changes the name person["gender"] = "Male" // adds a new field person["gender"] = nil // removes the gender key and value for (myKey, myValue) in person { print(myKey + ": " + myValue) } ========================================================================= Example: var namesOfIntegers = [Int: String]() namesOfIntegers[0] = "zero" namesOfIntegers[1] = "one" namesOfIntegers[2] = "two" for number in namesOfIntegers.keys { print("Number: \(number)") } for numberAsString in namesOfIntegers.values { print("Number: \(numberAsString)") } Example Methods and Properties ============================== // creates a Dictionary (map) with three // key value pairs var numberMap = [0:"zero", 1:"one", 2:"two"] numberMap[3] = "Three" // adds a new key value pair to the map numberMap[4] = "for" // adds a new key value pair to the map numberMap[4] = "four" // modifies the value // unwraps numberMap[4] (if possible) // and stores it in variable value if let value = numberMap[4] { // NOTE: numberMap[4] is the value // as an Optional type print(value) // prints Four } if numberMap.isEmpty // returns false { // NOTE: this will not happen print("The map is empty") } print(numberMap.isEmpty) // prints false print(numberMap.count) // prints 5 print(numberMap.values) print(numberMap.keys) // creates a new Dictionary (map) with one key-value pair // var myDict = ["97822":"Bob Smith"] // or var myDict: [String:String] = ["97822":"Bob Smith"] var myDict = [String:String] () // instantiates a new map myDict["97822"] = "Bob Smith" // adds to the map print(myDict["97822"]!) // prints Bob Smith print(myDict["97822"]) // prints Optional("Bob Smith") print(myDict.count) // prints 1 print(myDict.isEmpty) // prints false myDict["97822"] = "Billy Smith" // mutates value print(myDict["97822"]!) // prints Billy Smith myDict["87345"] = "Don Adams" // adds a new element print(myDict["45786"]) // prints nil // print(myDict["45786"]!) // Run-time fatal error (crash) // NOTE: The value is always given back as an Optional ================================= ================================= =================================

Built In Functions

================================= ================================= ================================= import Foundation sqrt(25) pow(2,3) floor(23.7) ceil(23.7) abs(-21) max(10,20) min(10,20) Also, for pi, use: Double.pi Float.pi CGFloat.pi ================================= ================================= =================================

Trimming white space from a String

================================= ================================= ================================= // Swift 3 func trim(_ str: String) -> String { return str.trimmingCharacters(in: CharacterSet.whitespaces) } // Swift 4 func trim(_ str: String) -> String { return str.trimmingCharacters(in: .whitespaces) } ================================= ================================= =================================

Number Conversions with a String

================================= ================================= ================================= // converts a String that holds a number into an int let numberAsString:String = "30" let someNumber:Int = Int(numberAsString)! //30 // converts an Int to a String that holds the Int let number:Int = 30 let numberAsString = String(number) // To convert an Int to a Double, use Double(30) // You can also convert to other types like Float(30) // you can convert to other bases with String(Int, radix: base) let b2 = String(12, radix: 2) // converts 12 to "1100" let b8 = String(12, radix: 8) // converts 12 to "14" let b16 = String(12, radix: 16) // converts 12 to "c" ================================= ================================= =================================

Strings

================================= ================================= ================================= NOTE: YOU CAN NOT DIRECTLY ACCESS A CHARACTER IN A String See the following website for more help. https://swiftludus.org/swfit-strings-tutorial/ NOTE: In Swift 4, the characters property of the String class does NOT exist. So, instead of using str.characters.count, use str.count var str:String = "Abc" OR var str = "Abc" if str.isEmpty { // do something } var count = str.characters.count // version 3 var count = str.count // version 4 // count is 3 let upper = str.uppercased() // upper is "ABC" let lower = str.lowercased() // lower is "abc" // version 3 for character in str.characters { print(character) } // version 4 for character in str { print(character) } // version 3 for index in str.characters.indices { print("\(str[index])") } // version 4 for index in str.indices { print("\(str[index])") } Example: Swift 4 ================ let str = "sunday, monday, happy days" for char in str { print("Found character: \(char)") } Example: Swift 4 ================ var myIndex = str.startIndex while myIndex < str.endIndex { print(str[myIndex]) myIndex = str.index(after: myIndex) } Example: Swift 4 ================ for myIndex in myString.indices { print(myString[myIndex]) } Example: Swift 4 (BEST WAY) ================ let s = "Hello" for ch in s { print(ch) } // prints out ASCII characters for ch in s.utf8 { print(Int(ch)) } // converts an Int to a character let value = UnicodeScalar(97)! // must unwrap let ch = Character(value) print(ch) let b2 = String(12, radix: 2) // converts 12 to "1100" let b8 = String(12, radix: 8) // converts 12 to "14" let b16 = String(12, radix: 16) // converts 12 to "c" ================================= ================================= =================================

Optionals

================================= ================================= ================================= var age: Int? age = 23 print(age) // outputs Optional(23) print(age!) // outputs 23 // a safer way if let myAge = age { print(myAge) // outputs 23 print(myAge!) // compiler ERROR print(age) // outputs Optional(23) } ================================= var age: Int? age = 23 if let myAge = age { print(myAge) // outputs 23 } ================================== var age: Int! age = 23 print(age) // outputs 23 (auto unwrapped) if let myAge = age { print(age) // outputs 23 (auto unwrapped) print(myAge) // outputs 23 } var age: Int! // here goes the exclamation mark age = 23 print(age) // outputs 23 (auto unwrapped) ================================= ================================= =================================

Joining Strings (Concat)

================================= ================================= ================================= var first: String = “ro” var second: String = “bot” print(“\(first+second)”) var third: String = “\(first+second)” ================================= ================================= =================================

Base Arithmetic

Base 2, Base 8, Base 16 ================================= ================================= ================================= ========================================================= // Decimal to binary let d1 = 21 let b1 = String(d1, radix: 2) print(b1) // "10101" ========================================================= ========================================================= // Decimal to hexadecimal let d3 = 61 let h1 = String(d3, radix: 16, uppercase:true) print(h1) // "3d" ========================================================= ========================================================= // Hexadecimal to decimal (an Int) let h2 = "a3" let d4 = Int(h2, radix: 16)! print(d4) // 163 ========================================================= ================================= ================================= =================================

Screen Size

================================= ================================= ================================= // Define instance variables // (Under class ViewController) // define a variable for the screen size let screenSize:CGRect = UIScreen.main.bounds // define variables for the screen height and screen width var screenHeight = 0 var screenWidth = 0 // In a function, // you can get the values for these variables screenHeight = Int(screenSize.width) screenWidth = Int(screenSize.height) ================================= ================================= =================================

User Interface Objects

================================= ================================= ================================= Connecting a UILabel to a Reference Variable ============================================ // Hold down the control key and drag from your // UILabel to the winsLabel IBOutlet variable. // Now at runtime the variable winsLabel will refer // or point to the UILabel. // You can now refer to properties or variables inside // the UILabel object. @IBOutlet weak var winsLabel: UILabel! Accessing Variables (properties) of a UILabel Example 1: Modifying the text inside the Label winsLabel.text = "You Win!!!" Example 2: Accessing the text inside the Label var winsText = winsLabel.text Connecting a UITextField to a Reference Variable ================================================ // Hold down the control key and drag from your // UITextField to the firstNameTextField IBOutlet variable. // Now at runtime the variable firstNameTextField will refer // or point to the UITextField. // You can now refer to properties or variables inside // the UITextField object. @IBOutlet weak var firstNameTextField: UITextField! Accessing Variables (properties) of a UITextField Example 1: Modifying the text inside the TextField firstNameTextField.text = "Me" Example 2: Accessing the text inside the TextField var firstName = firstNameTextField.text Connecting a UIImageView to a Reference Variable ================================================ // Hold down the control key and drag from your // UIImageView to the frog IBOutlet variable. // Now at runtime the variable frog will refer // or point to the UIImageView. // You can now refer to properties or variables inside // the UIImageView object. // You can put an image on the ImageView by selecting // the image drop down box on the attributes panel. // The image file must first be dragged to the files area. @IBOutlet weak var frog: UIImageView! This code will update the frog's frame ====================================== // this gets the x value of the UIImageView let x = frog.frame.origin.x // get the frog's y value var y = frog.frame.origin.y // check to see if y is greater than 20 if y > 20 { // decrease y by 3 y = y - 3 } // this gets the width and height of the UIImageView let width = frog.frame.size.width let height = frog.frame.size.height // this resets the frame of the UIImageView object frog.frame = CGRect(x: x, y: y, width: width, height: height) Creating a Timer object ======================= // Create a Timer object as an instance variable (global to all functions) var timer = Timer() // Schedule the timer to start running // The timeInterval is the number of seconds to delay // selector: #selector(timerAction) defines the method to call each time // This would normally occur inside a button event. timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) // Stopping the timer timer.invalidate() @objc func timerAction() { // here we check to see if the gameOver variable // is false if gameOver { return // exits (quits) the function } // move stuff // check for collisions // check for a win and if so, update the screen, and // shut down the timer // check for a loss and if so, update the screen, and // shut down the timer } Getting the dimensions of the screen ==================================== // Define instance variables ============================ // defines a variable for the screen size let screenSize:CGRect = UIScreen.main.bounds // defines variables for the screen // height and screen width // which are set in the viewDidLoad() var screenHeight = CGFloat(0) var screenWidth = CGFloat(0) // In your viewDidLoad() method: ================================ screenWidth = CGFloat(screenSize.width) screenHeight = CGFloat(screenSize.height) ================================= ================================= =================================

Play Music

================================= ================================= ================================= You must import the AVFoundation library at the top of your ViewController.swift file. Put it beneath import UIKit import AVFoundation add this variable to your ViewController class right below class ViewController: UIViewController { var mySong: AVAudioPlayer? add this function to your ViewController class right below your variables func playMusic() { let path = Bundle.main.path(forResource: "mysong.mp3", ofType:nil)! let url = URL(fileURLWithPath: path) do { mySong = try AVAudioPlayer(contentsOf: url) mySong?.play() } catch { // couldn't load file :( print("Could not load the file mysong.mp3") } } call the playMusic() function in some action event playMusic() ===================================================== ===================================================== =====================================================

MACOS Assignments

===================================================== ===================================================== ===================================================== How do I write a Simple MacOS text based Program using print? 1) On the Welcome to Xcode screen, choose: Create a new Xcode project OR from the file menu choose: File --> New --> Project 2) Click on macOS in the Choose a template top bar and then click on Command Line Tool 3) Click on Next 4) Type in a product name. MySchedule Do NOT choose a Team. The Organization Name: your first and last name Organization Identier: com.yourlastname Leave the Bundle Identifier the same and make sure the language is Swift 5) Click on Next 6) In the next dialog, choose Documents for your save location and make sure you do NOT choose Source Control. 7) Click on Create How do I compile? Click on Product --> build OR Command --> B How do I run my program? Click on the Run Button in the upper left hand corner OR Command --> R ############################################################################ Your Name and Schedule (print) MacOS text based Program ############################################################################ Program #0 - Write a program that prints out your name and your schedule for this coming school year (use a separate line for each course). Remember the method is called print(). Example: print("Mr. Rosier") print() Sample Output: Mr. Rosier 1. Comp Sci Ind Study 2. Comp Sci Ind Study 3. Comp Sci Ind Study 4. Lunch 5. Comp Sci Ind Study 6. Comp Sci 2 Advanced 7. Comp Sci Ind Study 8. Comp Sci Ind Study ############################################################################ Welcome (Read from the keyboard, print, String concatenation (+) MacOS text based Program ############################################################################ Program #1 - Write a program that prompts the user to enter their first name. Print out Welcome first name! (use the + operator to join strings OR String interpolation \(str)) Example Code: print("Welcome") print() print() print("Enter your first name: ", terminator:"") var firstName = readLine(strippingNewline:true) if let firstName = firstName { // print your output here } Sample Output: Welcome Enter your first name: (user enters name like maybe Tom) Welcome Tom! ############################################################################ Welcome (Read from the keyboard, print, String concatenation (+) MacOS text based Program ############################################################################ Program #2 - Write a program that prompts the user to enter their first name. Then prompt the user to enter their last name. Print out Welcome, first name space last name! Example Code: print("Welcome") print() print() print("Enter your first name: ", terminator:"") var firstName = readLine(strippingNewline:true) // now prompt and read in the last name if let firstName = firstName, let lastName = lastName { // print your output here } Sample Output: Welcome Enter your first name: (user enters first name like maybe Tom) Enter your last name: (user enters last name like maybe Baker) Welcome, Tom Baker! ############################################################################ Area of a Rectangle (Read from the keyboard (input), print(), math operations) + - * / // % MacOS text based Program ############################################################################ Program #3 - Write a program that prompts the user for the length and width of a rectangle, calculates the area, and prints out: The area of the rectangle is ??? square units. Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Area of a Rectangle // FINISH ME // print a blank line // print a blank line // prompt for the length and read in the length print("Enter the length of a rectangle: ", terminator:"") var length = Int(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // prompt for the width and read in the width print("Enter the width of a rectangle: ", terminator:"") var width = Int(readLine(strippingNewline:true)!) // FINISH ME // print a blank line if let length = length, let width = width // shadow varibles { // FINISH ME // calculate the area and print it let area = 0 // replace 0 with ????? print("The area is \(area) square units.") // interpolation } Sample Output: Area of a Rectangle Enter the length of a rectangle: (user enters maybe 8) Enter the width of a rectangle: (user enters maybe 5) The area is 40 square units. ############################################################################ Area of a Triangle (Read from the keyboard (input), print(), math operations) MacOS text based Program ############################################################################ Program #4 - Write a program that prompts the user for the base and height of a triangle, calculates the area, and prints out: The area of the triangle is ??? Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Area of a Triangle // FINISH ME // print a blank line // print a blank line // prompt for the base and read in the base print("Enter the base of a triangle: ", terminator:"") var base = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // prompt for the height and read in the height print("Enter the height of a rectangle: ", terminator:"") var height = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line if let base = base, let height = height // shadow varibles { // FINISH ME // calculate the area of the triangle and print it let area = 0 // replace 0 with ????? print("The area is xxx square units.") // use interpolation } Sample Output: Area of a Triangle Enter the base of a triangle: (user enters maybe 8) Enter the height of a triangle: (user enters maybe 6) The area is 24.0 square units. ############################################################################ Area of a Circle (Read from the keyboard (input), print(), math operations) ############################################################################ MacOS text based Program Program #5 - Write a program that prompts the user for the radius of a circle, calculate the area, and then print out: The area of the circle is ???.???? square units. Use Double.pi for pi. NOTE: Use all Double types for your variables Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Area of a Circle // FINISH ME // print a blank line // print a blank line // prompt for the radius and read in the radius print("Enter the radius of a circle: ", terminator:"") var radius = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line if let radius = radius // shadow variable { // FINISH ME // calculate the area of the circle and print it let area = 0 // replace 0 with ????? print("The area of the circle is xxx square units.") // use interpolation } Sample Output: Area of a Circle Enter the radius of a circle: (user enters maybe 5) The area of the circle is 78.53975 square units. ############################################################################ Shooting Percentage (Read from the keyboard(input), print(), math operations) ############################################################################ MacOS text based Program Shooting Percentage #6 - Write a program that prompts the user for the number of shots made and the number of shots attempted. You can call your variables shotsMade and shotsAttempted. Find the shooting percentage: ( Use print("The shooting percentage is %.3f", shotsAttempted) ) ( Use the Double type for your variables or convert to a Double ) Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Shooting Percentage // FINISH ME // print a blank line // print a blank line // prompt for the number of shots made print("????????", terminator:"") var shotsMade = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // prompt for the number of shots attempted print("????????", terminator:"") var shotsAttempted = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME if let shotsMade = ????, let shotsAttempted = ?????? // shadow variables { // FINISH ME // calculate the shooting percentage and print it let shootingPercentage = 0 // replace 0 with ????? print("The shooting percentage is xxx") // use interpolation } Sample Output: Shooting Percentage Enter the number of shots made: (user enters maybe 4) Enter the number of shots attempted: (user enters maybe 8) The shooting percentage is .500 ############################################################################ Throwing Percentage (Read from the keyboard(input), print(), math operations) MacOS text based Program (also called passing percentage) ############################################################################ Throwing Percentage #7 - Write a program that prompts the user for the number of passes completed and the number of passes thrown. You can call your variables passesCompleted and passesAttempted. Find the throwing percentage: ( Use print("The throwing percentage is %.3f", passesAttempted) ) Sample Output: Throwing Percentage Enter the number of passes completed: (user enters maybe 4) Enter the number of passes thrown: (user enters maybe 8) The throwing percentage is .500 Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Throwing Percentage // FINISH ME // print a blank line // print a blank line // prompt for the number of passes completed print("????????", terminator:"") var passesCompleted = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // prompt for the number of passes attempted print("????????", terminator:"") var passesAttempted = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME if let passesCompleted = ????, let passesAttempted = ?????? // shadow variables { // FINISH ME // calculate the passing percentage and print it let passingPercentage = 0 // replace 0 with ????? print("The passing percentage is xxx") // use interpolation } ############################################################################ Celsius to Fahrenheit (Read from the keyboard(input), print(), math operations) MacOS text based Program ############################################################################ Program #8 - Write a program that prompts the user for the Celsius temperature, calculate the Fahrenheit temperature and then print out: The Fahrenheit temperature is ???.???? degrees. Use c = 5.0/9.0 *(f-32) to find the Celsius Use f = 9.0/5.0 * c + 32 to find the Fahrenheit Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Celsius to Fahrenheit // FINISH ME // print a blank line // print a blank line // prompt for the celsius temperator print("????????", terminator:"") var celsius = Double(readLine(strippingNewline:true)!) // NOTE: celsius is of type Optional with a Double inside // FINISH ME // print a blank line // FINISH ME if let c = ???? // c is the shadow variable of type Double { // FINISH ME // calculate the fahrenheit temperature let f = 0.0 // replace 0.0 with ????? print("The fahrenheit temperature is xxx degrees.") // use interpolation } else { // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: Celsius to Fahrenheit Enter the Celsius temperature: (user enters maybe 34) The Fahrenheit temperature is ???.???? degrees. ############################################################################ Winning Percentage (Read from the keyboard(input), print(), math operations) MacOS text based Program ############################################################################ Winning Percentage #9 - Write a program that prompts the user for the number of wins and the number of losses. You can call your variables wins and losses. Find the winning percentage: Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Winning Percentage // FINISH ME // print a blank line // print a blank line // prompt for the number of wins print("????????", terminator:"") var wins = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // prompt for the number of losses print("????????", terminator:"") var losses = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME if let wins = ????, let losses = ?????? // shadow variables { // FINISH ME // calculate the winning percentage and print it let winningPercentage = 0.0 // replace 0.0 with ????? print("The winning percentage is xxx") // use interpolation } else { // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: Winning Percentage Enter the number of wins: (user enters maybe 3) Enter the number of losses: (user enters maybe 7) The winning percentage is .300 ############################################################################ Surface Area of a Cube (Read from the keyboard(input), print(), math operations) MacOS text based Program ############################################################################ Program #10 - Write a program that prompts the user for the length of a side for a cube, calculate the surface area (6*side*side), and then print out: The surface area of the cube is ???.???? square units. You can use the double type or an integer type for your variables. Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Surface Area of a Cube // FINISH ME // print a blank line // print a blank line // prompt for the length of 1 side print("????????", terminator:"") var side = Double(readLine(strippingNewline:true)!) // NOTE: side is of type Optional with a Double inside // FINISH ME // print a blank line // FINISH ME if let side = ???? // side is the shadow variable of type Double { // FINISH ME // calculate the surface area of the cube let surfaceArea = 0.0 // replace 0.0 with ????? print("The surface area is xxx square units.") // use interpolation } else { // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: Surface Area of a Cube Enter the length of one side: (user enters maybe 4) The surface area is ???.???? square units ############################################################################ Batting Average (Read from the keyboard(input), print(), math operations) MacOS text based Program ############################################################################ Program #11 - Write a program that prompts the user for the number of hits, the number of at bats, and the number of walks. You can call your variables hits, atBats, and walks. Find the batting average and the slugging percentage: Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Batting Average // FINISH ME // print a blank line // print a blank line // FINISH ME // prompt for the number of hits print("????????", terminator:"") // FINISH Me // Create a variable called hits ??? ???? = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME // prompt for the number of at bats print("????????", terminator:"") // FINISH ME // Create a variable called atBats ??? ?????? = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME // prompt for the number of walks print("????????", terminator:"") var walks = Double(readLine(strippingNewline:true)!) // NOTE: walks is of type Optional with a Double inside // FINISH ME // print a blank line // FINISH ME if let hits = ????, let atBats = ????, let walks = ???? { // FINISH ME // calculate the batting average hits/atBats let battingAverage = 0.0 // replace 0.0 with ????? print("The batting average is xxx.") // use interpolation // FINISH ME // calculate the on base average // (hits + walks) / (atBats + walks) let onBaseAverage = 0.0 // replace 0.0 with ????? print("The on base average is xxx.") // use interpolation } else { // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: Batting Average Enter the number of hits: (user enters maybe 2) Enter the number of at bats: (user enters maybe 8) Enter the number of walks: (user enters maybe 2) The user's batting average is .250 The user's on base average is .400 ############################################################################ Slope of a Line (Read from the keyboard(input), print(), math operations, if else) MacOS text based Program ############################################################################ Program #12 - Write a program that prompts the user for two points (2D). You can call your variables x1,y1 and x2,y2. Find the slope of the line, and then print out: The slope of the line is ???.???? Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Slope of a Line // FINISH ME // print a blank line // print a blank line // *********************************************** // *********************************************** // We will get the coordinates of the first point // *********************************************** // *********************************************** // FINISH ME // prompt for the first x value print("????????", terminator:"") // FINISH Me // Create a variable called x1 ??? ???? = Double(readLine(strippingNewline:true)!) // FINISH ME // prompt for the first y value print("????????", terminator:"") // FINISH Me // Create a variable called y1 ??? ???? = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // *********************************************** // *********************************************** // We will get the coordinates of the second point // *********************************************** // *********************************************** // FINISH ME // prompt for the second x value print("????????", terminator:"") // FINISH Me // Create a variable called x2 ??? ???? = Double(readLine(strippingNewline:true)!) // FINISH ME // prompt for the second y value print("????????", terminator:"") // FINISH Me // Create a variable called y2 ??? ???? = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // *********************************************** // *********************************************** // We will see if the inputs are correct // *********************************************** // *********************************************** // FINISH ME if let x1 = ???, let y1 = ????, let x2 = ????, let y2 = ???? { // *********************************************** // *********************************************** // We will calculate the slope // *********************************************** // *********************************************** // FINISH ME // calculate the slope (y2 - y1) / (x2 - x1) let slope = 0.0 // replace 0.0 with ????? print("The slope of the line is xxx.") // use interpolation } else { // *********************************************** // *********************************************** // Let the user know there was an error in input // *********************************************** // *********************************************** // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: The Slope of a Line Enter the value for x1: (user enters maybe 1) Enter the value for y1: (user enters maybe 1) Enter the value for x2: (user enters maybe 2) Enter the value for y2: (user enters maybe 2) The slope of the line is ???.???? ############################################################################ Letter Grades (Read from the keyboard, print, math operations, if else if) MacOS text based Program ############################################################################ Program #13 - Write a program that prompts the user for a grade. Find the letter grade, and then print out: The letter grade is ?. You can use an integer type for your input variable. 95 and above - A 87 - 94 - B 75 - 86 - C 70 - 74 - D 69 and below - F Example Code: You can copy this code and paste into into your editor window. // FINISH ME // print Letter Grades // FINISH ME // print a blank line // print a blank line // *********************************************** // *********************************************** // We will get the numerical grade from the user // *********************************************** // *********************************************** // FINISH ME // prompt for the numerical grade print("????????", terminator:"") // FINISH Me // Create a variable called grade and // convert it to an Int ??? ???? = ???(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // *********************************************** // *********************************************** // We will see if the input is correct // *********************************************** // *********************************************** // FINISH ME if let grade = ????? { // *********************************************** // *********************************************** // We will find the letter grade // *********************************************** // *********************************************** // FINISH ME // we will print The letter grade is xxx print("The letter grade is xxx.") // use interpolation } else { // *********************************************** // *********************************************** // Let the user know there was an error in input // *********************************************** // *********************************************** // FINISH ME // use a print statement to let the user know that the input // was not correct } Sample Output: Letter Grades Enter the grade: (user enters maybe 82) The letter grade is a C ############################################################################ Factors of a Number (Read from the keyboard, print, math operations, if else, for loops) MacOS text based Program ############################################################################ Program #Extra Credit 1 Sample Output: ============== Factors of a Number Enter the number to find factors of: 15 The factors of 15 are: 1 3 5 15 Goodbye! // FINISH ME // print the title Factors of a Number // FINISH ME // print two blank lines // FINISH ME // prompt for the number that you want to find the // factors of print(????, ?????) // FINISH ME // use readLine to read in the number and convert it to an Int var number = ?????? // FINISH ME // print a blank line // FINISH ME // Use an if let statement to verify that number is indeed // an integer number if ???? = ????? // shadow variable { // FINISH ME // print The factors of xxx are: // and stay on the same line // xxx is to be replaced by the value of number // FINISH ME // find the factors and print them // we will try dividing by all numbers from 1 to number // the for loop will let divisor be // all numbers from 1 to number // divisor will be 1 the first time through the loop // divisor will be 2 the second time through the loop // divisor will be 3 the third time through the loop // etc. for divisor in 1...number { // FINISH ME // see if number can be divided evenly by divisor if ???? % ????? == 0 { // FINISH ME // print the divisor and a space but stay on // the same line } } // FINISH ME // print 2 blank lines // FINISH ME // print Goodbye! } else { // FINISH ME // print There was an error in your input. } ############################################################################ Prime Numbers (Read from the keyboard, print, math operations, if else, for loops) MacOS text based Program ############################################################################ Program #Extra Credit 2 // Sample output: Prime Numbers Enter a number to find if it is prime: 15 15 is NOT prime. Goodbye! Program ended with exit code: 0 // main.swift // PrimeMacOS import Foundation func isPrime(_ num:Int) -> Bool { // FINISH ME // Put your code here to find if num is prime // return true if it is prime else return false // HINT: Count the number of factors // A prime number has exactly 2 factors return false } // FINISH ME // print the title Prime Numbers // FINISH ME // print two blank lines // FINISH ME // prompt Enter a number to find if it is prime: print("Enter a number to find if it is prime: ", terminator:"") var number = Int(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME // Use an if let statement to verify that number is indeed // an integer number if ????? // shadow varible { // FINISH ME // call the func isPrime() to see if the number is Prime if ?????(number) { // and print out // xxx is prime or // where xxx should be the value of number } else { // print out // xxx is NOT prime // where xxx should be the value of number } // FINISH ME // print 2 blank lines // FINISH ME // print Goodbye! } else { // FINISH ME // print There was an error in your input. } ############################################################################ The GCF of Two Numbers (Read from the keyboard, print, math operations, if else, for loops) MacOS text based Program ############################################################################ Program #Extra Credit 3 // Sample output: The GCF of Two Numbers Enter the first number: 18 Enter the second number: 24 The greatest common factor of 18 and 24 is 6. Goodbye! // This is the function that finds the gcf for us func gcf(_ n1:Int, _ n2:Int) -> Int { let gcf = 1 // FINISH ME // add code to find the gcf of n1 and n2 // you will need to loop through all divisors from 1...n1 // each time through the loop you should divide n1 and n2 by // your loop variable (use % for your division). // if n1 and n2 are both divisible by the loop variable, then // save the loop variable in variable gcf for d in ??????? { if ????? && ???? { gcf = ? } } return gcf } // FINISH ME // print the title The GCF of Two Numbers // FINISH ME // print two blank lines // FINISH ME // prompt Enter the first number: print(???????, terminator:"") // FINISH ME // convert the text that the user typed in into an Int var n1 = ???(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME // prompt Enter the second number: print(??????, terminator:"") var n2 = ?????? // FINISH ME // print a blank line // FINISH ME // Use an if let statement to verify that n1 and n2 are indeed // integer numbers if let ??? = ???, let ??? = ??? // shadow variables { // FINISH ME // call the function gcf(n1, n2) to get the gcf // NOTE: The variable must be different than the // the function name which is gcf. var g = ????? // FINISH ME // print The greatest common factor of xx and xx is xxx. // NOTE: The first xx should be replaced with \(n1) // NOTE: The second xx should be replaced with ???? // NOTE: The xxx should be replaced with ???? // FINISH ME // print a blank line // FINISH ME // print Goodbye! } else { // FINISH ME // print There was an error in your input. } ############################################################################ Pay Checks(Read from the keyboard, print, math operations, if else, for loops) MacOS text based Program ############################################################################ Program #Extra Credit 4 // Sample output 1: Pay Check Enter the gross pay: 1000 Enter the social security tax rate: .06 Enter the other tax rate: .05 Gross Pay: 1000.00 SS Tax Amount:$60.00 Other Tax: $50.00 Net Pay: $890.00 Goodbye! func getSSTaxAmount(_ grossPay:Double, _ ssTaxRate:Double) -> Double { // FINISH ME // get the social security tax amount // multiply grossPay by ssTaxRate return ?????? } func getOtherTaxAmount(_ grossPay:Double, _ otherTaxRate:Double) -> Double { // FINISH ME // get the other tax amount // multiply grossPay by otherTaxRate return ?????? } func getNetPay(_ grossPay:Double, _ ssTaxRate:Double, _ otherTaxRate:Double) -> Double { return ?????? } // FINISH ME // print the title Pay Check ?????? // FINISH ME // print two blank lines ????? ????? // FINISH ME // prompt Enter the gross pay: print(??????, terminator:"") var grossPay = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line ????? // FINISH ME // prompt Enter the social security tax rate: print(?????, terminator:"") var ssTaxRate = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line ?????? // FINISH ME // prompt Enter the other tax rate: print(???????, terminator:"") var otherTaxRate = Double(readLine(strippingNewline:true)!) // FINISH ME // print a blank line ????? // FINISH ME // Use an if let statement to verify that grossPay, ssTaxRate // and otherTaxRate are indeed Double numbers if let grossPay = ??, let ssTaxRate = ??, let otherTaxRate = ?? // shadow variables { // FINISH ME // print out Gross Pay: and then the grossPay // grossPay will be rounded to two decimal places // and will replace the %.2f in the String that is printed. var output = String(format: "Gross Pay: %.2f", grossPay) ????? // FINISH ME // print a blank line ????? // FINISH ME // print out Social Security Tax: and then the tax that you pay let taxAmount = ?????? output = String(format: "SS Tax Amount:$%.2f", taxAmount) ????? // FINISH ME // print a blank line ?????? // FINISH ME // print out Other Tax: and then the other tax that you pay let otherTaxAmount = ????? output = String(format: "Other Tax: $%.2f", otherTaxAmount) ????? // FINISH ME // print a blank line ????? // FINISH ME // print out Net Pay: and then the net pay that you receive let netPay = ?????? output = String(format: "Net Pay: $%.2f", netPay) ?????? // FINISH ME // print a blank line ????? // FINISH ME // print Goodbye! ?????? } else { // FINISH ME // print There was an error in your input. ??????? } ############################################################################ Perfect Numbers(Read from the keyboard, print, math operations, if else, for loops) MacOS text based Program ############################################################################ Program #Extra Credit 5 // Sample output 1: Perfect Numbers Enter a number to check if it is perfect: 6 6 is a perfect number. Goodbye! // Sample output 2: Perfect Numbers Enter a number to check if it is perfect: 8 8 is NOT a perfect number. Goodbye! import Foundation func isPerfect(_ number:Int) -> Bool { // A perfect number has divisors that add up to the number, // not including the number itself. // For example, 6 is perfect since factors 1, 2, 3 add to 6. // FINISH ME // Define a variable to hold the number (your will need it later) // FINISH ME // Define a variable to hold the sum of the digits and set // it to zero // FINISH ME // use a while loop and loop // while your number is greater than 0 // start of loop { // 1. Each time through the loop use your mod operator (%) // to get the right most digit of your number (mod by 10) // 2. Add this right most digit to your sum // 3. Modify your number by dividing it by 10 (use \ 10) // end of loop } // FINISH ME // Check and see if your sum is equal to your original number // that you saved. // If it is, return true // otherwise return false return true } // FINISH ME // print the title Perfect Numbers // FINISH ME // print two blank lines // FINISH ME // prompt Enter a number to check if it is perfect: print(???, terminator:"") // now convert it to an Int var number = ???(readLine(strippingNewline:true)!) // FINISH ME // print a blank line // FINISH ME // Use an if let statement to verify that number is indeed an Int if let number = ????? // shadow variable { // Call your isPerfect method to see if the number is // indeed a perfect number. Pass to it your number. // If it is a perfect number, print out: // print("xxx is a perfect number.") // where xxx should be replaced with the value of your number // Otherwise print out: // print("xxx is NOT perfect number.") // where xxx should be replaced with the value of your number // FINISH ME // print a blank line // FINISH ME // print Goodbye! } else { // FINISH ME // print There was an error in your input. } ############################################################################ Print the vowels of a String (Read from the keyboard, print, slicing, for loops, if else, &&) SEE String link above for help on looping through the characters ############################################################################ Program EC6 - Write a program that prompts the user to enter a String. Print out each vowel in the String (a, e, i, o, u). You can use the String type for your variable. Stay in a loop until the user enters the empty String. Sample Output: The Vowels in a String Enter a String: (user enters maybe catalog) The vowels of catalog are: aao Enter a String: (user enters maybe computer) The vowels of computer are: oue Enter a String: (user enters maybe nothing) Goodbye! ############################################################################ Print the capital letters of a String (Read from the keyboard, print, slicing, for loops, if else, &&) ############################################################################ Program EC7 - Write a program that prompts the user to enter a String. Print out each capital letter in the String. Stay in a loop until the user enters the empty String. Sample Output: The Capital Letters in a String Enter a String: (user enters maybe CatALog) The capital letters of CatALog are: CAL Enter a String: (user enters maybe ComPuTer) The capital letters of ComPuTer are: CPT Enter a String: (user enters maybe nothing) Goodbye! ############################################################################ Base Two Numbers ############################################################################ Program EC8 - Write a program that prompts the user to enter a number. Print out the number in base 2. You can use the integer type for your variable. Write a function to find the result (String). Stay in a loop until the user enters 0 Examples: let b2 = String(12, radix: 2) // converts 12 to "1100" let b8 = String(12, radix: 8) // converts 12 to "14" let b16 = String(12, radix: 16) // converts 12 to "c" Base 2 numbers have only two digits, 0 and 1 Base 10 numbers have 10 digits, 0...9 Example 1: 0 1 0 1 1 0 <- binary digits 32 16 8 4 2 1 <- place value The binary number in base 10 is ?????????????? Example 2: 1 1 0 1 1 1 <- binary digits 32 16 8 4 2 1 <- place value The binary number in base 10 is ?????????????? Example 3: 0 0 1 1 1 1 <- binary digits 32 16 8 4 2 1 <- place value The binary number in base 10 is ?????????????? Sample Output: Base Two Numbers Enter a number: (user enters maybe 8) 8 in base 2 is 1000. Enter a number: (user enters maybe 15) 15 in base 2 is 1111. Enter a number: (user enters maybe 0) Goodbye! ======================================================= =======================================================

Download Help Files

======================================================= ======================================================= Lab 1 - Flashlight =============================================================== Lab 2 - Perimeter =============================================================== Lab 3 - Simple Calculator Download Lab SimpleCalculator.txt Download SimpleCalculator.png =============================================================== Lab 4 - Clock Time Download Lab ClockTime.txt Download ClockTime.png =============================================================== =============================================================== Lab 5 - Semester Grade App Download Lab SemesterGradeApp.txt Download SemesterGradeApp.png =============================================================== =============================================================== Lab 6 - Tic-Tac-Toe App Download Lab Tic-Tac-Toe-iOS.txt Download Tic-Tac-Toe.png =============================================================== =============================================================== Lab 7 - The Restaurant App The ThirdViewController.swift is for your map Download ThirdViewController.txt =============================================================== =============================================================== Lab 8 - The Move Me App Download Labi10 MoveMe-iOS.txt Download MoveMe.png Download explosion.mp3 Download ship.png =============================================================== Lab 9 - Bounce App Download Lab9 Bounce-iOS.txt Download Bounce-iOS.png =============================================================== Lab 10 - The Other Side Lab 10 - TheOtherSide-APP.txt TheOtherSide-APP.png bat.png cat.png witch.png =============================================================== ============== Lab 11 Frogger ================================== =============================================================== Lab 11 - FroggerApp.txt FroggerView.png frog.png carLeft.png carRight.png highway.png =============================================================== ============== Lab 12 AlienInvaders2 ========================== =============================================================== REMEMBER: ALL PICTURES AND THE MP3 FILE ARE COPYRIGHTED. YOU MAY NOT GIVE THESE AWAY, SELL THEM, OR USE THEM IN ANYWAY OTHER THAN FOR THIS ASSIGNMENT. YOU MAY NOT GIVE AWAY THE APP OR TRY TO UPLOAD IT TO THE APP STORE. HOWEVER, THE CODE FILE IS FREE. Remember that all pictures and sound files must be dragged to the file panel (on the left). Lab 4 - AlienInvaders2App.txt AlienInvaders2App.png Download ship.png Download alien.png Download bullet.png Download explosion.png Download nightSky.png Download barricade.png Download explosion.mp3 =============================================================== ============== Lab 13 ImproveYourTypingApp ==================== =============================================================== ImproveYourTypingApp.png ImproveYourTypingApp.txt Download nightSky.png Download explosion.png =============================================================== =============== Lab 14 - Practice Math ======================== =============================================================== Download PracticeMathApp.txt Download PracticeMathApp.png ============================================================= ============== Lab 15 Toss Them =========================== ============================================================= Download TheDiceApp.txt Download TheDiceApp-Screen.png =============================================================== =============================================================== =============================================================== =============================================================== ============== Lab 16 DictionaryArrayApp ===================== =============================================================== DictionaryArrayApp.png DictionaryArrayApp.txt =============================================================== ============================================================= ============== Lab 17 The Binary App =================== ============================================================= BinaryApp.txt BinaryApp.png =============================================================== ============== Lab 18 The Test Taker App =========++========== =============================================================== TestTakerApp.png TestTakerApp.txt =============================================================== =============================================================== =============================================================== ============================================================= ============== Lab 19 DogsSingleView ======================== ============================================================= DogsSingleViewApp.txt DogsSingleView-Screen.png =============================================================== =============================================================== ===============================================================
======================================================= =======================================================

Video Help Files

======================================================= =======================================================
How to Drag a Label onto a ViewController

How to Drag a TextField onto a ViewController
and Create an Outlet that refers to it

How to Drag a Button onto a ViewController and Create an Action Event


================================= ================================= ================================= Ideas for programs and path ================================= ================================= ================================= Sources: Hello Swift! - Manning Swift 4 For Absolute Beginners - Apress.com ================================= ================================= In playgrounds: ================================= ================================= import UIKit Introduction to the Swift Playground Introduce variables and types Introduce the print command Introduce calculations Introduce input Find the Area of a Rectangle Find the volume of a sphere Convert Temperatures Convert Distances Convert Measurements Show a number in base 2,8,16 Bitwise Operations fibonacci prime numbers Apps ---- The Animals app - No Code The name app - Enter your name and then display Hello Tom, welcome to Swift! Input two numbers, which number is bigger? Random Multiplication App ? x ? Guess the number app Rock, Paper, Scissors app Letter grades if else or switch Roman Numerals print your name 10 times (for loops) calculator Tic-Tac-Toe Magic Squares Hangman Encrypt Data etc. // put it into a class Distance class Person class Student class Convert class Website for using for loops https://www.natashatherobot.com/swift-alternatives-to-c-style-for-loops/ Website for iPad playgrounds https://www.apple.com/ca/swift/playgrounds/ // swift online resource (and you can buy the book if you want) https://www.raywenderlich.com/category/swift ================================= ================================= GUI Objects (Graphical User Interface UIButton, UILabel, UITextField UI ================================= ================================= import UIKit let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) myLabel.backgroundColor = UIColor.red myLabel.text = "Hello Swift" myLabel.textAlignment = .center myLabel.font = UIFont(name: "Georgia", size: 24) UIColor.red