swift
  1. swift-datatypes

Swift Data Types

Swift is a strongly typed programming language, which means that each variable or constant must have a defined type. Swift provides a wide range of data types for storing different kinds of data, including numbers, strings, and collections.

Syntax

Here are some of the basic data types in Swift:

// numbers
var number: Int = 42
var floatingPoint: Double = 3.14
var floatValue: Float = 3.14

// strings
var message = "Hello, Swift!"
var character: Character = "a"

// collections
var array: [Int] = [1, 2, 3]
var set: Set<String> = ["apple", "banana", "orange"]
var dictionary: [String: Int] = ["one": 1, "two": 2, "three": 3]

Example

Here is an example of using data types in Swift:

var age: Int = 30
var name: String = "John"
var height: Double = 5.8

print("\(name) is \(age) years old and is \(height) feet tall.")

Output

The output of this code will be:

John is 30 years old and is 5.8 feet tall.

Explanation

In the example above, we defined three variables with different data types: age is an integer, name is a string, and height is a double. We then used the print() function to display a message that includes the values of these variables.

Use

Data types are essential in Swift for storing and manipulating data. These data types can be used in various cases like performing calculations, manipulating strings, working with collections, and much more.

Important Points

  • Swift is a strongly typed programming language
  • Swift provides a wide range of data types for storing different kinds of data
  • Basic data type categories in Swift include numbers, strings, and collections
  • The variables created in Swift have to be initialized with a value before use
  • Swift provides type inference to automatically determine a variable's type based on the assigned value

Summary

Swift offers a wide range of data types to cater to almost all kinds of data available. From simple numbers to collections, Swift is a great choice for developing powerful iOS, macOS, watchOS and tvOS applications. By using the correct data type, Swift provides a more efficient and safer way of writing code.

Published on: