In: Computer Science
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
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:
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:
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. */