advanced ios lab file
Case study No:1
Introduction of Swift language
Swift is a modern, open-source programming language developed by Apple for macOS, iOS, watchOS, and tvOS. It was first released in 2014 and has quickly gained popularity among developers due to its ease of use, safety, and performance.
Here are some key features of the Swift programming language:
Easy to learn: Swift was designed to be an easy-to-learn language, with a simple and intuitive syntax that is similar to many other popular programming languages such as C, Objective-C, and Python.
Safe: Swift was designed with safety in mind, to prevent common programming errors such as buffer overflows, null pointer exceptions, and other memory-related issues. Swift includes features like optionals and value types to make it easier to write safe code.
Fast: Swift is a highly performant language that can be used to write fast and efficient code. It was designed with performance in mind, and includes features like low-level control, optimization, and powerful data structures.
Interoperable: Swift can be used with existing Objective-C code, making it easy to integrate Swift into existing projects or work with legacy codebases. Swift can also be used with popular third-party libraries and frameworks, making it a highly interoperable language.
Open-source: Swift is an open-source language, meaning that its source code is available for anyone to view, modify, and contribute to. This has led to a vibrant community of developers working on improving the language and its tools.
Some popular use cases for Swift include developing native iOS apps, macOS apps, watchOS apps, and tvOS apps. It can also be used for server-side development, with frameworks like Vapor and Kitura enabling developers to build web applications and APIs with Swift.
Overall, Swift is a powerful, easy-to-learn language that is well-suited for a wide range of applications and use cases. Its popularity is only expected to continue growing in the coming years, as more developers discover its benefits and begin using it in their projects
When you create a new Xcode project, you’ll see a dropdown to choose one of these two options:
Storyboards are interfaces built with visual drag and drop in the Editor Area using Interface Builder.
SwiftUI was released in late September 2019 as a new way to build user interfaces by writing code. Xcode 11 has a special Preview Canvas pane that shows your user interface change in real time as you write the code to modify your user interface.
Feature of Swift
Optional types: Swift allows developers to declare optional types for their variables and properties, which can be used to indicate that a value may be absent. This helps to prevent common runtime errors, such as null pointer exceptions.
Generics: Swift supports generic programming, which allows developers to write reusable code that can work with different types. This helps to reduce code duplication and improve code organization.
Closures: Swift supports closures, which are self-contained blocks of code that can be passed around and used in other parts of a program. Closures can be used to simplify code and improve its readability.
Type inference: Swift uses type inference to determine the type of a variable or expression, which can help to reduce the amount of code that needs to be written.
Fast and safe memory management: Swift uses Automatic Reference Counting (ARC) to manage memory, which means that it automatically manages the memory for objects in a program. This helps to prevent common memory-related errors, such as memory leaks.
Structs and enums: Swift supports value types, including structs and enums, which can be used to define custom data types. This makes it easier to write code that is more expressive and concise.
Multiple return types: Swift allows developers to return multiple values from a function using tuples, which can help to reduce the number of functions that need to be written.
Functional programming: Swift supports functional programming concepts, such as higher-order functions, map, filter, and reduce. This allows developers to write code that is more declarative and concise.
Overall, Swift is a highly expressive and modern language that offers many features that make it easy to use, safe, and highly productive for developers. Its many features help to make programming more efficient and reduce the likelihood of common error
Case study No:2 Difference between objective c and Swift language
|
|
Objective c language | Swift language |
|
|
|
|
|
1. Swift was introduced in 2014 by Apple as a modern successor to Objective-C.
2. It is a completely new language built from scratch.
3. Uses dot notation for method calls and member access. 4. Statically typed language with type inference.
5. Provides explicit nullability with optionals.
6. Automatic Reference Counting (ARC) manages memory automatically.
7. Uses a single file (.swift) for class implementation.
8. Emphasizes strong error handling with try-catch blocks.
9. Pointers are used behind the scenes, but their use is abstracted away. 10. Has its own package manager called Swift Package Manager (SwiftPM).
11. Includes modern language features like closures and generics.
12. No concept of categories; extensions are used to add functionality to existing types.
13. Uses ARC for automatic memory management.
14. No reliance on Objective-C runtime for dynamic features.
15. Property accessors are automatically synthesized.
16. Uses concise and expressive method names.
17. Offers a more streamlined and readable syntax compared to Objective-C.
18. Strong support for functional programming paradigms.
19. Swift is not compatible with C and C++ code directly.
20. Swift is the recommended language for iOS and macOS app development.
|
|
|
Practical No:1
Aim Design an iOS App of UISwitch using Swift language.
Software used: XCODE
Steps to perform UISwitch:
1.Open Xcode and create a new project (File -> New -> Project).
2.Select “App” under the “iOS” tab and click “Next”.
3.Choose the location where you want to save your project and click “Create”.
4.Open the Main.storyboard file and drag a “Switch” object from the “Object Library” onto the view controller’s canvas.
5.Select the switch and open the “Attributes Inspector” panel. Here, you can customize the switch appearance and behavior, such as its color, size, and whether it is initially on or off.
6.Control-drag from the switch to the view controller’s code to create an @IBOutlet connection. Give it a meaningful name, such as “mySwitch”.
7.Control-drag from the switch to the view controller’s code to create an @IBAction connection. Give it a meaningful name, such as “switchChanged”.
8.In the switchChanged function, use the isOn property of the switch to get its current state and perform any actions based on it. For example, you could update a label or toggle the visibility of other UI elements.
9.Run the app on a simulator or a physical device to test the switch behavior.
10. Done with development.
Now click on or hit Command+R button from keyboard to compile and run into simulator
Practical No: 2
Aim: Design an iOS App of UISlider using Swift language.
Software used: XCODE
Steps to perform UISlider:
1.Open Xcode and create a new project. Choose “Single View App” as the template and enter a name for your project.
2.Once your project is created, go to the Main.storyboard file and drag a UISlider from the Object Library onto the View Controller.
3.Customize the UISlider as desired. You can change the minimum and maximum values, set the initial value, change the color and size, and add any other desired features.
4.Create an outlet for the UISlider. Control-drag from the UISlider to the View Controller class, and give it a name. This will allow you to reference the UISlider in your code.
5.Add a target to the UISlider. Control-drag from the UISlider to the View Controller class, and choose “Action” as the connection type. Give the action a name, and choose the event you want to trigger the action (e.g. “Value Changed”).
6.Implement the action method in your View Controller class. This method will be called whenever the UISlider value changes. You can retrieve the current value of the UISlider using the value property, and then use it in your app as needed.
7.Run the app on a simulator or a physical device to test the switch behavior.
8. Done with development.
Now click on or hit Command+R button from keyboard to compile and run into simulator
Practical No: 3
Aim:-Design an iOS App of UIDatePicker using Swift language.
Software used: XCODE
Steps to perform UIDatePicker:
1.Open Xcode and create a new project by selecting “File” -> “New” -> “Project”.
2.Choose “Single View App” and give your project a name.
3.Select your preferred language (Swift in this case) and make sure that “Use SwiftUI” is unchecked.
4.Click “Next” and choose a location to save your project.
5.Once your project is created, open the “Main.storyboard” file.
6.Drag a “Date Picker” from the Object Library onto your storyboard.
7.Click on the Date Picker to select it and open the “Attributes Inspector”.
8.In the Attributes Inspector, you can customize the Date Picker’s appearance and behavior. You can set the mode to “Date”, “Time”, or “Date and Time”. You can also choose whether the Date Picker should display a countdown timer, and set the minimum and maximum dates that can be selected.
9.Once you’ve customized your Date Picker, you can add code to your View Controller to handle user interactions with it. For example, you can use the “valueChanged” event to update a label with the selected date or time.
10.Open the Assistant Editor and make sure that your View Controller is visible.
11.Control-drag from your Date Picker to your View Controller to create an outlet. This will allow you to reference the Date Picker in your code.
12.Create an IBAction function in your View Controller to handle the “valueChanged” event.
13.In the “datePickerChanged” function, you can use a DateFormatter to format the selected date, and then print it to the console. You can also update a label or other UI element with the selected date.
14.Build and run your app to test your Date Picker
Practical No: 4
Aim:-Design an iOS App of UIProgressView using Swift language.
Software used: XCODE
Steps to perform UIProgressView:
Step 1: Open XCODE and create a new project (Single View App).
Step 2: Open Main.storyboard and drag a Progress View from the Object Library to the View Controller.
Step 3: Set the Progress View properties, such as Progress Tint Color, Track Tint Color, and Progress.
Step 4: Create an IBOutlet for the Progress View in the ViewController.swift file.
Step 5: Create an IBAction for a button, which will simulate the progress.
Next step
Step 6: Run the app on a simulator or device and test the progress view.
Practical No5: Design an iOS App of UIAnimation using Swift language.
Software used: XCODE
Steps to perform UIAnimation:
1.Open Xcode and create a new iOS project.
2.In the project navigator, select the Main.storyboard file.
3.Drag a View element from the Object Library onto the canvas. This will be the main view of the app.
4.Set the background color of the view to white in the Attributes Inspector.
5.Drag an ImageView element onto the canvas and place it in the center of the view.
6.Set the image of the ImageView to an image of a ball.
7.Select the ImageView and open the Size Inspector. Set the width and height of the ImageView to 100.
8.Select the ImageView and open the Attributes Inspector. Set the content mode to Aspect Fit.
9.Add a top constraint to the ImageView to center it vertically in the view.
10.Add an outlet for the ImageView to the ViewController.swift file. Name the outlet “ballImageView”.
11.Add the following code to the ViewController.swift file:
Source code:
Import UIKit
Class ViewController: UIViewController {
@IBOutlet weak var ballImageView: UIImageView!
Override func viewDidLoad() {
Super.viewDidLoad()
animateBall()
}
Func animateBall() {
UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .autoreverse], animations: {
Self.ballImageView.transform = CGAffineTransform(translationX: 0, y: 200)
}, completion: nil)
}
}
12.Build and run the app on a simulator or a real device.
Practical No:6
Aim:- Design a iOS app of Calculator in Xcode Using Swift language
Software used: XCODE
Steps to performUICalculator:
Step 1: Create a New Project
- Open Xcode and select “Create a new Xcode project.”
- Choose “App” under the iOS section and select “Single View App.”
- Enter the desired product name, organization name, and other project details.
- Choose a location to save the project and click “Create.”
Step 2: Set Up the User Interface
- In the Project Navigator, open the Main.storyboard file.
- Delete the existing view controller by selecting it and pressing the Delete key.
- Drag and drop a new View Controller from the Object Library onto the canvas.
- Drag and drop a Label onto the view controller for displaying the calculation result.
- Drag and drop a Stack View onto the view controller for arranging the calculator buttons.- Customize the layout by adjusting the constraints and sizes of the elements.Step 3: Create IBOutlets and IBActions
- Open the Assistant Editor to display the view controller’s code alongside the storyboard.
- Control-drag from the Label to the view controller’s code to create an IBOutlet for it.
- Repeat the above step for each calculator button, creating IBOutlets for the buttons.
- Create IBActions for each button by control-dragging from the buttons to the code.
Step 4: Implement the Calculator Logic
- In the view controller’s code, create variables to store the current input and calculation result.
- Implement the IBActions for the calculator buttons to update the input variable accordingly.
- Implement the necessary arithmetic operations (addition, subtraction, multiplication, division) using the input and result variables.
- Update the Label’s text property with the current result after each calculation.
Step 5: Run the App
- Build and run the app using the Simulator or a connected iOS device.
- Interact with the calculator buttons to perform calculations.
- Verify that the Label displays the correct results based on the input and operations.
Source code:
Import UIKit
Class ViewController: UIViewController {
Var numberOnScreen: Double = 0;
Var previousNumber: Double = 0;
Var performingMath = false;
Var operation = 0;
@IBAction func numbers(_ sender: UIButton) {
If performingMath == true {
Label.text = String(sender.tag-1)
numberOnScreen = Double(label.text!)!
performingMath = false}
Else {
Label.text = label.text! + String(sender.tag-1)
numberOnScreen = Double(label.text!)!}}
@IBOutlet weak var label: UILabel!
@IBAction func buttons(_ sender: UIButton) {
If label.text != “” && sender.tag != 11 && sender.tag != 16{
previousNumber = Double(label.text!)!
if sender.tag == 12 { //Divide
label.text = “/”;}
If sender.tag == 13 { //Multiply
Label.text = “x”;}
If sender.tag == 14 { //Subtract
Label.text = “-“;}
If sender.tag == 15 { //Add
Label.text = “+”;}
Operation = sender.tag
performingMath = true;}
Else if sender.tag == 16 {
If operation == 12{ //Divide
Label.text = String(previousNumber / numberOnScreen)}
Else if operation == 13{ //Multiply
Label.text = String(previousNumber * numberOnScreen)}
Else if operation == 13{ //Multiply
Label.text = String(previousNumber * numberOnScreen)}
Else if operation == 14{ //Subtract
Label.text = String(previousNumber – numberOnScreen)}
Else if operation == 15{ //Add
Label.text = String(previousNumber + numberOnScreen)}}
Else if sender.tag == 11{
Label.text = “”
previousNumber = 0;
numberOnScreen = 0;
operation = 0;}}
Override func viewDidLoad() {
Super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.}
Override func didReceiveMemoryWarning() {
Super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.}}
Case study No:3 Write a case study of Playground
Install Xcode: Visit the Mac App Store and search for “Xcode” to download and install it on your Mac.
Launch Xcode: Open Xcode from your Applications folder or Launchpad.
3. Create a new playground:
- Click on “Create a new Xcode project” or go to File > New > Playground.
- Choose the “Blank” template or any other template that suits your needs.
- Select a location to save your playground project and provide a name for it.
4. Develop your playground:
- Once the playground project is created, you will see a single Swift file with the extension “.swift” in the project navigator.
- Edit the Swift code in the playground file to build your desired functionality, such as math operations or any other programming concepts you want to explore.
- You can write code directly in the playground file, and the results will be displayed in the right-hand pane in real-time.
5. Run and test your playground:
- To see the output and results of your code, click the “Run” button (a triangular play button) in the Xcode toolbar.
- The output will appear in the right-hand pane, and you can see the results of your code execution.
6. Interact with the playground:
- You can interact with your playground by adding input fields, buttons, sliders, or any other user interface elements to experiment and visualize the behavior of your code.
- Use the live view feature to create interactive user interfaces and see the changes in real-time.
7. Save and share your playground:
- Save your playground project regularly using File > Save or by pressing Command + S.
- You can share your playground project with others by zipping the project folder or by using version control systems like Git.
Remember, playground projects are typically meant for experimentation, learning, and quick prototyping. They provide an interactive and iterative environment for developing and testing code.
Practical No: 7
Aim: Write a program to check if a number is positive, negative, or zero
Source code:
// Program to check if a number is positive, negative, or zero
Let number = 10
If number > 0 {
Print(“The number is positive”)
} else if number < 0 {
Print(“The number is negative”)
} else {
Print(“The number is zero”)
}
Output
Practical No:8
Aim: write a program to check pass or fail using Swift language
Source code:
// program to check pass or fail
Let marks = 60
// use of ternary operator
Let result = (marks >= 40) ? “pass” : “fail”
Print(“You “ + result + “ the exam”)
Output
Practical No: 9
Aim: write a program bitwise AND oprator using Swift language
Source code:
//Bitwise AND Operator
var a = 12
var b = 25
var result = a & b
print (result) // 8
Output
Practical No: 10
Aim: write a Swift program to demonstrate the logical AND “&&” operator
Source code:
Import Swift;
Var num1=10;
Var num2=50;
Var num3=30;
If(num1 > num2 && num1 > num3)
{Print(“Num1 is largest number”);}
Else if(num2 > num1 && num2 > num3)
{ Print(“Num2 is largest number”);}
Else{Print(“Num3 is largest number”);}
Output
Practical No : 11
Aim: write a Swift program to demonstrate the logical OR (||) operator
import Swift;
var num1=10;
var num2=50;
var num3=10;
if(num1==num2 || num1==num3)
{ print("Hello");}
else{ print("Hii");}
Output
Practical No : 12
Aim: Write a Swift program to demonstrate the logical NOT (!) operator
Source code:
Import Swift;
Var num1=10;
Var num2=10;
If !(num1==num2)
{ Print(“Hello”);}
Else{ Print(“Hii”);}
Output
Practical No: 13
Aim:Write a program checking between two values which one is greater using Swift language
Source code:
Var a1:Int = 60;
If a1 > 42 {
/* if the condition is true then print */
Print(“1st Varable is greater than 42”);
}
Print(“The value of variable is \(a1)”)
Output
Practical No: 14
Aim: Write a Swift program illustrate the use of Nested if-else statement
Source code:
Import Swift
Var a = 100
Var b = 200
Var c = 300
If (a > b) {
If (a > c) { Print(“100 is Greater”)}
Else { Print(“300 is Greater”); }}
Else { If (b > c) {
Print(“200 is Greater”)
} Else { Print(“300 is Greater”); }}
Output
Practical No: 15
Aim:Write a Swift program to illustrate break statement declaring a mutable variable
Source code:
Var I = 1
Repeat
{ If (I == 10)
{Break }
Print(“Iteration number \(i)”)
I += 1
}while I < 20
Output
Practical No: 16
Aim:Write a Swift program to illustrate continue statement declaring variable
Source code:
Var I = 10
Repeat
{ I = I + 1
If (I == 15)
{ Continue }
Print(“Value of index is \(i)”)
} while I < 20
Output
Practical No 17
Aim: write a program for addition, subtraction and multiplication using Swift language
Source code:
Var a = 7
Var b = 2
// addition
Print (a + b)
// subtraction
Print (a – b)
// multiplication
Print (a * b)
Output
Practical No:18
Aim: write a program for Assignment oprator using Swift language
Source code:
// assign 10 to a
Var a = 10
// assign 5 to b
Var b = 5
// assign the sum of a and b to a
A += b // a = a + b
Print(a)
Output
Practical No: 19
Aim: Write a program for Comparison Operators using Swift language
Source code:
Var a = 5, b = 2
// equal to operator
Print(a == b)
// not equal to operator
Print(a != b)
Print(a > b)
// less than operator
Print(a < b)
// greater than or equal to operator
Print(a >= b)
// less than or equal to operator
Print(a <= b)
Output
Practical No:20
Aim: Write a program to Access Array Elements using Swift language
Source code:
Var languages = [“Swift”, “Java”, “C++”]
// access element at index 0
Print(languages[0]) // Swift
// access element at index 2
Print(languages[2]) // C++
Output
Practical No:21
Aim: Write a program to Add Elements to an Array by append method using Swift language
Source code:
Var numbers = [21, 34, 54, 12]
Print(“Before Append: \(numbers)”)
// using append method
Numbers.append(32)
Print(“After Append: \(numbers)”)
Output
Practical No:22
Aim: write a program to Add Elements to an Array by insert method using Swift language
Source code:
Var numbers = [21, 34, 54, 12]
Print(“Before Insert: \(numbers)”)
Numbers.insert(32, at: 1)
Print(“After insert: \(numbers)”)
Output
Practical No:23
Aim: Write a program to Remove an Element from an Array using Swift language
Source code:
Var languages = [“Swift”,”Java”,”Python”]
Print(“Initial Array: \(languages)”)
// remove element at index 1
Let removedValue = languages.remove(at: 1)
Print(“Updated Array: \(languages)”)
Print(“Removed value: \(removedValue)”)
Output
Practical No:24
Aim: write a program to Looping Through Array using Swift language
Source code:
// an array of fruits
Let fruits = [“Apple”, “Peach”, “Mango”]
// for loop to iterate over array
For fruit in fruits {
Print(fruit)
}
Output
Practical No:25
Aim: write a program to Find Number of Array Elements using Swift language
Source code:
Let evenNumbers = [2,4,6,8]
Print(“Array: \(evenNumbers)”)
// find number of elements
Print(“Total Elements: \(evenNumbers.count)”)
Output
Comments
Post a Comment