Question

Using Swift playground and / or the command line for macOS (open Xcode, create a new...

Using Swift playground and / or the command line for macOS (open Xcode, create a new Xcode project, macOS, command line tool), practice the following exercises:

Exercise: Swift Variables

  1. Declare 2 variables/constants with some random values and any name of your choice
  2. Considering these 2 variables, one as a value of PI and other as a radius of circle, find the area of circle
  3. Print the area of circle
  4. Declare a string variable explicitly with value “Northeastern”.
  5. Declare a string variable implicitly with value “Smartphone”.
  6. Concatenate both the strings and print it
  7. Declare a variable explicitly with a value of 12
  8. Declare a variable implicitly with a value of 2
  9. Calculate the value of 12 to the power of 2 and print it
  10. Declare an emoji (any emoji of your choice: command + control + space to access emojis) variable with the value “iPhone”.
  11. Declare another emoji variable with the value “iPhone\u{301}”
  12. Declare a variable that stores the value you get after applying the == operator on the emojis declared in 10) and 11).

Exercise: Swift Arrays

  1. Declare an empty Array of type String and initialize it with 3 values
  2. Append the array with [“Boston” “New York”] to the array declared above
  3. Insert the string “San Francisco” at the 3rd index without overwriting the already existing value (Rearrange the indices)
  4. Use removeAt to remove any value from the array.
  5. Print the final count of the array

Exercise: Swift Loops

  1. Declare an empty Array of Integers.
  2. Initialize the array with even numbers between 1 and 100.
  3. Using the for-in loop print out all the numbers along with the sum of their digits.
  4. Using a repeat while loop add 3 to each number.
  5. Declare a string and cast it to an Array of characters. Iterate over this array to print out the characters along with their indices.

Exercise: Swift Functions

  1. Create a function named “add” that takes two parameters of type double and returns the sum of the two numbers
  2. Create a function named “subtract” that takes two parameters of type int and returns the difference of the two numbers
  3. Create a function name “multiply” that takes two parameters of type Float and returns the product of the two numbers
  4. Make sure that the three functions created above work by testing them
  5. Create a function named “test” that takes a parameter of type Int and returns sum, difference and multiplication of its digits(The function must return multiple parameters)

Exercise: Conditions

  1. You are given a fridge that knows when your food is going bad. You know that milk spoils after 21 days and eggs after 10 days. Given milkAge and eggsAge, write a function to determine if you should throw the milk, the eggs or both away or not. If you can keep both, print “you can still use your milk and eggs”. If you should throw away the milk, print “you should throw away the milk”. Similarly for the eggs.
  2. Write a function that takes in three variables “first, “second” and “third” that checks if at least two variables have the same value. If true, print “two values are at least identical” else print “the values are different”.

Exercise: Swift Dictionary and Tuples

  1. Create an array of dictionaries in which each dictionary in the array contains the keys “firstName” and “lastName”. Create an array with a name of your choosing that contains only the values for “firstName” in each dictionary.
  2. Using the array of dictionaries created previously, this time create an array that contains the values for “firstName” and “lastName” in each dictionary separated by a delimiter of your choice.
  3. Create a datatype called MyTuple using the typealias feature of swift. It should be a tuple containing 2 Strings (String , String).
  4. Declare and initialize a tuple with any values of your choice.
  5. Print both values of the tuple individually in the console.

Exercise: Swift Optionals

  1. let optvar : Int = nil Correct the error in this line of code.
  2. let unwrapme : String? = nil

let unwrappedValue : String = unwrapme!

The code snippet shown above will crash. Rewrite it with Optional Binding.

3 - Declare any optional variable of any type with the Optional keyword.

4 - var value1 : Int?

var defaultValue : Int = 7

Print the value of value1 to the console. If it contains nil use assign defaultValue to it.

i) Write a simple if-else block to do so.

ii) Use the nil coalescing operatior.

4-     If let name = txtname.text {

If let address = txtaddress.text {

sendToServer(name , address)

}

else {

print (“No address provided”)

}

}

else {

print (“No name provided”)

}

Rewrite this piece of code using 2 guard statements.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the solution:

Exercise: Swift Variables

var PI:Double = 3.141 //declare and initialize the pi value
var radius:Double = 5 //declare and initialize the radius value
var area:Double = PI * (radius * radius) //calculate the area of circle
print("Area of circle is: ",area) //print the area of circle

sample output:

Area of circle is: 78.525

var str1:String = "Northeastern" //declare and initialize the str1 value
var str2:String = "Smartphone"//declare and initialize the str2 value
var str3:String = str1+str2 //concatinate str1 and str2
print("Concatinated string are:",str3) //print

sample output:

Concatinated string are: NortheasternSmartphone

var n1:Int //declare and n1 variable implicitly
n1 = 12
var n2:Int = 2 //declare and initialize the n2 value

var n3 = pow(12,2)
print("\(n1) power of \(n2) is:",n3) //print

sample output:

12 power of 2 is: 144

var emoj1:String = "?"
var emoj2:String = "iPhone\u{301}"

print("Emoji \(emoj1) and iphone emoj is \(emoj2) " )

sample output:

Emoji ? and iphone emoj is iPhoné

Exercise: Swift Arrays:

var arr = [String]() //decalre the array
arr = ["Boston","New", "York"] //initialize the value to the array
arr.append("San Francisco") //insert the string at third position to array
print(arr) //print the array
arr.remove(at: 0) //remove the string from 0 index
print(arr) //print the array
print(arr.count) //count the array

sample output:

["Boston", "New", "York", "San Francisco"]
["New", "York", "San Francisco"]
3

Add a comment
Know the answer?
Add Answer to:
Using Swift playground and / or the command line for macOS (open Xcode, create a new...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hi need this solved using Swift Programming ! Exercise - Failable Initializers Create a Computer struct with two properties, ram and yearManufactured, where both parameters are of type Int. Create a...

    Hi need this solved using Swift Programming ! Exercise - Failable Initializers Create a Computer struct with two properties, ram and yearManufactured, where both parameters are of type Int. Create a failable initializer that will only create an instance of Computer if ram is greater than 0, and if yearManufactured is greater than 1970, and less than 2017. Create two instances of Computer? using the failable initializer. One instance should use values that will have a value within the optional,...

  • Write a simple Java program with the following naming structure: Open Eclipse Create a workspace called...

    Write a simple Java program with the following naming structure: Open Eclipse Create a workspace called hw1 Create a project called hw1 (make sure you select the “Use project folder as root for sources and class files”) Create a class called Hw1 in the hw1 package (make sure you check the box that auto creates the main method). Add a comment to the main that includes your name Write code that demonstrates the use of each of the following basic...

  • In a project named 'DogApplication', create a class called 'Dog' 1. declare two instance variables in...

    In a project named 'DogApplication', create a class called 'Dog' 1. declare two instance variables in 'Dog' : name (String type) age (int type) 2. declare the constructor for the 'Dog' class that takes two input parameters and uses these input parameters to initialize the instance variables 3. create another class called 'Driver' and inside the main method, declare two variables of type 'Dog' and call them 'myDog' and 'yourDog', then assign two variables to two instance of 'Dog' with...

  • Here is the code from the previous three steps: #include <iostream> using namespace std; class Student...

    Here is the code from the previous three steps: #include <iostream> using namespace std; class Student { private: //class variables int ID; string firstName,lastName; public: Student(int ID,string firstName,string lastName) //constructor { this->ID=ID; this->firstName=firstName; this->lastName=lastName; } int getID() //getter method { return ID; } virtual string getType() = 0; //pure virtual function virtual void printInfo() //virtual function to print basic details of a student { cout << "Student type: " << getType() << endl; cout << "Student ID: " << ID...

  • Create a new program in Mu and save it as ps4.5.1.py and take the code below...

    Create a new program in Mu and save it as ps4.5.1.py and take the code below and fix it as indicated in the comments: # Write a function called phonebook that takes two lists as # input: # # - names, a list of names as strings # - numbers, a list of phone numbers as strings # # phonebook() should take these two lists and create a # dictionary that maps each name to its phone number. For #...

  • Create a console application project and solution called “ConsoleWorkWithData.” using C# Create the following variables with...

    Create a console application project and solution called “ConsoleWorkWithData.” using C# Create the following variables with data type: a. FirstName: string data type b. LastName: string data type c. Student ID: int data type d. BirthDate: data time data type e. Grade: decimal data type Write all values in these variables to the screen in this format: a. --------------------------------------------------------- b. My name is Rieser Angie c. I’m a new student, and this is my first program d. ************************************** e. My...

  • this is done i swift playgrounds, how to i go about doing this? confused how i...

    this is done i swift playgrounds, how to i go about doing this? confused how i would add to it since ita a constant "let" Create a variable total of type Double set to 0. Then loop through the dictionary, and add the value of each integer and double to your variable's value. For each string value, add 1 to the total. For each boolean add 2 to the total if the boolean is true, or subtract 3 if it's...

  • DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to...

    DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to add new phone contacts, display a list of all contacts, search for a specific contact by name, delete a specific contact. The program should provide the user with a console or command line choice menu about possible actions that they can perform. The choices should be the following: 1. Display list of all contacts. 2. Add a new contact. 3. Search for a contact...

  • 1. Create a new class called ReversibleArray. 2. In the class header, add the code <T>...

    1. Create a new class called ReversibleArray. 2. In the class header, add the code <T> immediately to the right of the class name. 3. Give this class two private instance variables: T[] array and int count 4. Create a constructor which takes in one parameter of type T[] and assign that parameter's value into this.array. Set count as the length of the array. 5. Add a toString() method that outputs the array values in the format: elem0, elem1, elem2,...

  • Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this...

    Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this file, include your assignment documentation code block. After the documentation block, you will need several import statements. import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; Next, declare the Lab12 class and define the main function. public class Lab12 { public static void main (String [] args) { Step 2: Declaring Variables For this section of the lab, you will need to declare...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT