Swift Language Tutorial for Beginner 2 - Data Type

In Swift Language Tutorial for Beginner 1 - Variable and Constant, we learned about Swift’s built-in data types, and this time we’ll take a look at the basic data types in Swift.

Built-in type summary

First, let’s take a look at Swift’s built-in data types through a mind map

Built-in type of Swift

As you can see, the built-in types in Swift are basically the same as in other high-level languages. Relative to C/C++, Java, the less common are tuple types and optional types (also available after Java 8)。 Each type name begins with an uppercase letter

Next, we’ll show the main points of each type (except tuples and optionals, which will be discussed separately later).

Integer

There are two categories, conforming and unsigned, and each class can be divided into thinner categories according to the length used for storage, the list is as follows:

Unsigned Integer

1
2
3
4
5
6
7
8

var a1 = UInt8.max // 255

var a2 = UInt16.max // 65535

var a3 = UInt32.max // 4294967295

var a4 = UInt64.max // 18446744073709551615

Signed integer

1
2
3
4
5
6
7
8
var maxInt8 = Int8.max     //127
var mimInt8 = Int8.min //-128
var maxInt16 = Int16.max //32767
var minInt16 = Int16.min //-32768
var maxInt32 = Int32.max //2147483647
var minInt32 = Int32.min //-2147483648
var maxInt64 = Int64.max //9223372036854775807
var minInt64 = Int64.min //-9223372036854775808

We can also use Int or UInt to directly define integer data, in which case different Ints and UInts of the machine will be mapped to different types, such as in 64-bit machines, Int maps to Int64, UInt maps to UInt64.

Floating-point type

Similar to other high-level languages, floating-point types are divided into single precision and double precision. as follows:

1
2
3
4
5
var b = MemoryLayout<Float>.size    //4 bytes
var b1 = MemoryLayout<Float32>.size //4 bytes
var b2 = MemoryLayout<Float64>.size //8 bytes
var b3 = MemoryLayout<Float80>.size //16 bytes
var c = MemoryLayout<Double>.size //8 bytes

When defining, scientific computation can be used

1
2
var sum = 1.25e3 //1.25*(10^3) = 1250
var sun2 = 0x1p3 //1*(2^3) = 8

You can also use the symbol “_” to split

1
2
3
var num1 = 001.23
var num2 = 1_000
var num3 = 1_000.1_001

Boolean

There are only two explicit values

1
2
var bool1 = true    
var bool2 = false

String

As in other languages, strings enclosed in double quotation marks are used. Stitching can be done directly by the “+” sign.

1
2
3
4
5
var str = "hello,playground"

str = "newValue"

str = str + "hello"

Next

Next, we’ll briefly introduce the basic control statements in Swift Swift Language Tutorial for Beginner 3 - Control statements.

本文标题:Swift Language Tutorial for Beginner 2 - Data Type

文章作者:Morning Star

发布时间:2022年01月10日 - 16:01

最后更新:2022年01月17日 - 07:01

原始链接:https://www.mls-tech.info/app/swift/swift-tutorial-2-basic-datatype-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。