Question

In: Computer Science

I need swift programming code and instruction of app Named Shortest path. Please explain at the...

I need swift programming code and instruction of app Named Shortest path. Please explain at the end of the code how to run the app on Xcode. Thanks

Solutions

Expert Solution

Swift is a powerful and intuitive programming language for macOS, iOS, watchOS, tvOS and beyond. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.

Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain. Even better, you don’t even need to type semi-colons. Inferred types make code cleaner and less prone to mistakes, while modules eliminate headers and provide namespaces. To best support international languages and emoji, Strings are Unicode-correct and use a UTF-8 based encoding to optimize performance for a wide-variety of use cases. Memory is managed automatically using tight, deterministic reference counting, keeping memory usage to a minimum without the overhead of garbage collection.

struct Player {
    var name: String
    var highScore: Int = 0
    var history: [Int] = []

    init(_ name: String) {
        self.name = name
    }
}

var player = Player("Tomas")

Declare new types with modern, straightforward syntax. Provide default values for instance properties and define custom initializers.

extension Player {
    mutating func updateScore(_ newScore: Int) {
        history.append(newScore)
        if highScore < newScore {
            print("\(newScore)! A new high score for \(name)! ?")
            highScore = newScore
        }
    }
}

player.updateScore(50)
// Prints "50! A new high score for Tomas! ?"
// player.highScore == 50

Add functionality to existing types using extensions, and cut down on boilerplate with custom string interpolations.

extension Player: Codable, Equatable {}

import Foundation
let encoder = JSONEncoder()
try encoder.encode(player)

print(player)
// Prints "Tomas, games played: 1, high score: 50”

Quickly extend your custom types to take advantage of powerful language features, such as automatic JSON encoding and decoding.

let players = getPlayers()

// Sort players, with best high scores first
let ranked = players.sorted(by: { player1, player2 in
    player1.highScore > player2.highScore
})

// Create an array with only the players’ names
let rankedNames = ranked.map { $0.name }
// ["Erin", "Rosana", "Tomas"]

Perform powerful custom transformations using streamlined closures.

These forward-thinking concepts result in a language that is fun and easy to use.

Swift has many other features to make your code more expressive:

  • Generics that are powerful and simple to use
  • Protocol extensions that make writing generic code even easier
  • First class functions and a lightweight closure syntax
  • Fast and concise iteration over a range or collection
  • Tuples and multiple return values
  • Structs that support methods, extensions, and protocols
  • Enums can have payloads and support pattern matching
  • Functional programming patterns, e.g., map and filter
  • Native error handling using try / catch / throw

Designed for Safety

Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, memory is automatically managed, and enforcement of exclusive access to memory guards against many programming mistakes. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries. This means that when you make a copy of something with that type, you know it won’t be modified elsewhere.

Another safety feature is that by default Swift objects can never be nil. In fact, the Swift compiler will stop you from trying to make or use a nil object with a compile-time error. This makes writing code much cleaner and safer, and prevents a huge category of runtime crashes in your apps. However, there are cases where nil is valid and appropriate. For these situations Swift has an innovative feature known as optionals. An optional may contain nil, but Swift syntax forces you to safely deal with it using the ? syntax to indicate to the compiler you understand the behavior and will handle it safely.

extension Collection where Element == Player {
    // Returns the highest score of all the players,
    // or `nil` if the collection is empty.
    func highestScoringPlayer() -> Player? {
        return self.max(by: { $0.highScore < $1.highScore })
    }
}

Use optionals when you might have an instance to return from a function, or you might not.

if let bestPlayer = players.highestScoringPlayer() {
    recordHolder = """
        The record holder is \(bestPlayer.name),\
        with a high score of \(bestPlayer.highScore)!
        """
} else {
    recordHolder = "No games have been played yet.")
}
print(recordHolder)
// The record holder is Erin, with a high score of 271!

let highestScore = players.highestScoringPlayer()?.highScore ?? 0
// highestScore == 271

Features such as optional binding, optional chaining, and nil coalescing let you work safely and efficiently with optional values.

Consider the weighted, undirected graph above. Let’s say that we want to find the shortest path from node a to node e. We know that we’re going to start at node a, but we don’t know if there is a path to reach it, or if there are many paths to reach it! In any case, we don’t know which path will be the shortest one to get to node e, if such a path even exists.

Dijkstra’s algorithm does require a bit of initial setup. But, before we get to that, let’s take a quick look at the steps and rules for running Dijkstra’s algorithm. In our example graph, we will start with node a as our starting node. However, the rules for running Dijkstra can be abstracted out so that they can be applied to every single node that we’ll traverse through and visit in an effort to find the shortest path.

The abstracted rules are as follows:

  1. Every time that we set out to visit a new node, we will choose the node with the smallest known distance/cost to visit first.
  2. Once we’ve moved to the node we’re going to visit, we will check each of its neighboring nodes.
  3. For each neighboring node, we’ll calculate the distance/cost for the neighboring nodes by summing the cost of the edges that lead to the node we’re checking from the starting vertex.
  4. Finally, if the distance/cost to a node is less than a known distance, we’ll update the shortest distance that we have on file for that vertex.

These instructions are our golden rules that we will always follow, until our algorithm is done running.

Running Your App in the Simulator or on a Device

Launch your app in a simulated iOS, tvOS, or watchOS device, or on a device connected to your Mac.

Overview

After you create a project, you can build and run your app on a simulated or real device without needing to lay out the user interface or write code. You may connect a real device to your Mac using a cable, or for iOS or tvOS apps, connect it over WiFi after you pair it with Xcode. For macOS apps, choose a scheme, then click the Run button in the toolbar.

Choose a Scheme

A scheme is a collection of settings that specify the targets to build, the build configuration, and the executable environment for an app. There's a scheme for each product (app, library, or framework) in your project. For projects that build an app, choose the scheme that matches your app's name from the scheme menu in the toolbar. For watchOS apps, choose the WatchKit App target as the scheme.

Select a Simulated Device

For iOS, tvOS, and watchOS apps, you can choose a simulated device, under [Platform] Simulators, from the run destination menu next to the scheme menu in the toolbar.

Select a Real Device

Before you distribute your app, launch it on a real device. Connect the device to your Mac, and choose the device in the run destination menu. For macOS versions of an iPad app, choose My Mac (the Mac running Xcode) as the device.

If you choose a real device, add your Apple ID in Accounts preferences and assign the project to a team on the Signing & Capabilities pane of the project editor. A single individual constitutes a one-person team. For macOS apps, you need to code sign the app if you enable certain capabilities. If you belong to the Apple Developer Program, you need to register the device before you can run the app.

Run the App

Click the Run button to build and run the app on the selected simulated or real device. View the status of the build in the activity area of the toolbar.

If the build is successful, Xcode runs the app and opens a debugging session in the debug area. Use the controls in the debug area to step through your code, inspect variables, and interact with the debugger.

If you choose a simulated device as the run destination, the Simulator launches and displays a simulation of the device family you chose.

*/ If the build is unsuccessful, click the indicators in the activity area to read the error or warning messages in the Issue navigator. Alternatively, choose View > Navigators > Show Issue Navigator to view the messages.

When you're done testing the app, click the Stop button in the toolbar. */


Related Solutions

"swift Create a SwiftUI project named DogBreeds based on the Contacts app. The app should be...
"swift Create a SwiftUI project named DogBreeds based on the Contacts app. The app should be named DogBreeds. The app will display 10 dog images and names in a lis"
Below is the linear programming for the Shortest Path Problem. Considering the second contraint in the...
Below is the linear programming for the Shortest Path Problem. Considering the second contraint in the mathematical model : ∑ixji−∑ixij=0∀j≠s,j≠t What is the logic behind this contraint? To make sure there is only one solution To make sure that the path is connected between the nodes To make sure the variable stays binary This contraint is redundant and not necessary Which of the following statements are true? (select all that apply) The shape of a student t-distribution curve depends on...
Below is the linear programming for the Shortest Path Problem. Considering the second contraint in the...
Below is the linear programming for the Shortest Path Problem. Considering the second contraint in the mathematical model : ∑ixji−∑ixij=0∀j≠s,j≠t What is the logic behind this contraint? To make sure there is only one solution To make sure that the path is connected between the nodes To make sure the variable stays binary This contraint is redundant and not necessary Which of the following statements are true? (select all that apply) The shape of a student t-distribution curve depends on...
"Write in swift code only please, Create a SwiftUI project named DogBreeds based on the Contacts...
"Write in swift code only please, Create a SwiftUI project named DogBreeds based on the Contacts app. The app should be named DogBreeds. The app will display 10 dog images and names in a list"
Question 3 Below is the linear programming for the Shortest Path Problem. Considering the second contraint...
Question 3 Below is the linear programming for the Shortest Path Problem. Considering the second contraint in the mathematical model : ∑ i x ji −∑ i x ij =0∀j≠s,j≠t What is the logic behind this contraint? 1) To make sure there is only one solution 2) To make sure that the path is connected between the nodes 3) To make sure the variable stays binary 4) This contraint is redundant and not necessary Question 4 Which of the following...
I need the JAVA code for a 4 function calculator app on andriod studio - The...
I need the JAVA code for a 4 function calculator app on andriod studio - The requirements are the following : - The only buttons needed are 0-9, *, /, +, -, a clear, and enter button - Implement the onclicklistener on the main activity - The calcuator should use order of operations (PEMDAS) - It should be able to continue from a previous answer (Ex: If you type 2+6 the calculator will display 8. If you then multiple by...
Note: I need a code and other requirement Note: programming language is c++ If you need...
Note: I need a code and other requirement Note: programming language is c++ If you need more information, please clarify what information you want. consider solving the equation sin(x) - e^(-x) = 0 write a computer program to solve the given equation using: 1- bisection method 2- fixed-point method 3- newton's intervals: {0,1},{1,2},{2,3},{3,4},{4,5},{5,6},{6,7},{7,8},{8,9},{9,10} choose accuracy E = 10^(-5) Make sure you document your program Requirement : 1- Mathematical justification 2- algorithem description 3- code (program) with documentation 4-output: roots ,...
hot use blutooth on your app stimulation to connect to a device. xcode swift. please inclide...
hot use blutooth on your app stimulation to connect to a device. xcode swift. please inclide a code if possible.
I need matlab code for digital watermarking using SVD. Please explain each step
I need matlab code for digital watermarking using SVD. Please explain each step
I need a program(code) in any programming language that performs the following operations: union, concatenation and...
I need a program(code) in any programming language that performs the following operations: union, concatenation and conversion DFA-NDFA.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT