Skip to content

Swift

Using The XCode Playground

Hello World:

In Swift, the traditional “Hello World” program is very simple. Open Xcode and create a new project. Select “Command Line Tool” as the project template and choose “Swift” as the language. In the main.swift file, type the following code:

Click the “Run” button to build and run the program. You should see the output “Hello, World!” displayed in the console.

Basic Syntax:

In Swift, a function is defined using the following syntax:

For example, to define a function that adds two numbers, you could write:

You can also use the shorthand syntax for single-expression functions:

To call a function, you simply write the function name followed by the arguments in parentheses:

This will set the variable “result” to 5.

Classes and Objects:

In Swift, classes and objects are defined using the following syntax:

For example, to define a class that represents a person, you could write:

You can create an instance of a class using the following syntax:

You can access properties and call methods of the object using the “.” operator:

This will display the output “Hello, my name is John.” in the console.