[Swift 5.3] Learn from A Swift Tour Swift [Xcode 12.1] <10/28 under construction>

Introduction

(Reference ①) [A Swift Tour] (https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1) ↑ The main article on the Swift official website. (Reference ②) [Introduction to Swift Practice-iOS App Development to Start Now! Let's make a simple calculator by holding down the basic grammar] (https://eh-career.com/engineerhub/entry/2017/05/25/110000) ↑ For those who are not concerned with Swift 5.3. (Reference ③) [[Introduction to Swift] Let's understand the optional type] (https://fukatsu.tech/optional-swift) ↑ For those who want to understand the Optional type.

table of contents

making

A Swift Tour "Hello, world!" No matter what language you learn, there is always a program to create and run first. It is a program that just displays " Hello, world! " On the screen. In Swift, write as follows.

print("Hello, world!")

What you can see from this code is the simplicity of Swift. In Java, which is the same object-oriented language as Swift, write as follows.

java


class Hello {
 public static void main(String[] args) {
  System.out.print("Hello, world!");
 }
}

Even a program that just displays "Hello, world!" For Java takes 5 lines, while Swift only takes 1 line. Neither the main () function nor the ; (semicolon) at the end of the line is required.

Simple Values

Declaration of variables / constants

Use let to declare a ** constant ** and var to declare a ** variable **.

Hello,world!


var myVariable = 42  //variable:myVariable = 42
myVariable = 50   //variable:myVariable = 50(Overwrite value)
let myConstant = 42  //constant:myConstant = 42

print(myVariable, myConstant)  //Execution result: 50 42

Here, variables (including constants) have the concept of ** type **. Even in everyday life, integer is used to express" 25 ", and in science papers, the accuracy of numerical values is required, sosingle floating point number (float; single floating point number)double. For example, use a precision floating point number (double; double floating point number).

Type classification

The list of types is as follows. <Edit memo: Creating / embedding a diagram>

Primitive type

Numeric type

Integer type (integer type) ・ ・ ・ ** Represents an integer **

char (character) ・ ・ ・ 0 ~ 65,535 (= 2 ^ 16 ―― 1) byte ・ ・ ・ -128 (= -2 ^ 7) ~ 127 (2 ^ 7-1) short ・ ・ ・ -32,768 (= -2 ^ 15) ~ -32,767 (= 2 ^ 15 --1) int ・ ・ ・ -2,147,483,648 (= -2 ^ 31) ~ 2,147,483,647 (= 2 ^ 31 --1) long ・ ・ ・ -9,223,372,036,854,775,808 (= -2 ^ 63) ~       9,223,372,036,854,775,807(=2^63 - 1)

Floating point number type ・ ・ ・ ** Represents a real number **

float ・ ・ ・ ± 3.40282347E + 38 ~ ± 1.40239846E-45 double ・ ・ ・ ± 1.79769313486231507E + 378 ~        ±4.94065645841246544E-324

Logical type (boolean type) ・ ・ ・ ** Represents a logical value (true or false) **

boolean ・ ・ ・ True or False

Reference type

Array type: A set of variables of the same type is represented by []

Class type ・ ・ ・ Collect methods and data

Interface type ・ ・ ・ Implement a method

Null type ・ ・ ・ Does not refer to anything

You don't have to worry about the type suddenly. At first, you should decide and remember that integers are declared with int, real numbers are declared with double, and so on.

Features of Swift: Type inference and type conversion

Besides, the Swift compiler can infer types from the initializer. The code above also allows you to declare a variable without defining a type. Of course, you can also explicitly define the type (= type annotation), as in the following code. It's convenient to do type inference, but it can also cause ** bugs **, so try to ** explicitly define the type ** as much as possible.

Explicit type definition


let implicitInteger = 70   //Implicit(implicit)Type definition
let implicitDouble = 70.0  //Implicit type definition
let explicitDouble: Double = 70  //Explicit type definition

print(implicitInteger, implicitDouble, explicitDouble)
//Execution result: 70 70.0 70.0

`Swift` does not implicitly convert a type to another type. Therefore, if you write the following code, an error will be output.

error


let label = "The width is "
let width = 94
let widthLabel = label + width

print(widthLabel)
//Execution result:
// error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'

You cannot concatenate String type (= string) and Int type (= integer) with the + operator. You need to convert Int type to String type and then concatenate. Type conversion is performed as follows.

Type conversion


let label = "The width is "
let width = 94
let widthLabel = label + String(width)  //Convert Int type width to String type

print(widthLabel)
//Execution result: The width is 94

If you want to embed a value in a string, there is a way to display it without type conversion. Just enclose the value in () and write \ (backslash) just before (). The shortcut keys for \ on Mac are ⌥ (option) and \.

Embedding a value in a string


let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

print(appleSummary)
print(fruitSummary)
//Execution result:
// I have 3 apples.
// I have 8 pieces of fruit.

Multi-line string description

If you want to write a string that spans multiple lines, enclose it in " "" (double quotation) . If you enter Space or Tab to improve readability, the output result will also include Space or Tab. Since it is enclosed in " ", Space and Tab are also treated as one character string. Readability is reduced, but if you do not want to include it in the output result, write it on the left.

Multi-line string description


let quotation = """
  I said "I have \(apples) apples."
  And then I said "I have \(apples + oranges) pieces of fruit."
"""

print(quotation)
//Execution result:
//   I said "I have 3 apples."
//   And then I said "I have 8 pieces of fruit."

Arrays and dictionaries

To generate a array or adictionary, enclose the index or key in []. Each component is listed with , (comma).

Array / dictionary generation


//Array generation
var shoppingList = ["catfish", "water", "tulips",]   //Type inference
shoppingList += [bread]   //Add components(append)
shoppingList[1] = "bottle of water"   //Component updates

var wishList: [String] = ["salmon", "soda", "violet",]  //Type annotation

print(shoppingList[1])
print(shoppingList[3])
print(wishList[0])
//Execution result:
// bottle of water
// bread
// salmon

//Dictionary generation
var occupations = [   //Type inference
  "Malcolm": "Captain",
  "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"  //Key"Jayne"Add
occupations["Kaylee"] = "Engineer"  //Key"Kaylee"Update

var currency: [String: String] = [  //Type annotation
  "JPN": "yen",
  "USA": "dollar",
]

print(occupations["Jayne"]?)
print(occupations["Kaylee"]?)
print(currency["USA"]?)
//Execution result:
// Public Relations
// Engineer
// dollar

The output of the component based on the index of ** array ** is described as print (array variable name [index]), while the output of the value based on the key of ** dictionary ** is print. (Dictionary name ["key"]?) . The reason for adding ? to the end when printing the dictionary value is that theprint ()function only accepts variables of type non-Optional type (which does not allow references to = nil) as arguments. ..

Features of Swift: Existence of "Optional type"

The big difference between array and dictionary is ** the "type" of the return value **. If you try to output an index that does not exist in the array, you will get a ** runtime error **. On the other hand, Dictionary outputs the value of Optional type (allows reference to = nil). Below is a program of array and dictionary designed to output non-existent components. Pay attention to the execution result.

Difference between array and dictionary error output


var errArray = [0, 1, 2,]
print(errArray[3])  //Output of non-existent components
//Execution result:
// Fatal error: Index out of range

var errDictionary = [
  "zero": 0,
  "one": 1,
  "two": 2,
]
print(errDictionary["two"])   //Output of existing components
print(errDictionary["three"])  //Output of non-existent components
//Execution result:
// Optional(2)  #Prompted to unwrap the return value
// nil  #Prompted to unwrap the return value

The dictionary outputs ** results ** while throwing an error. This error can be resolved by writing ? at the end of the argument of the **print ()function and performing a type conversion (unwrap) from Optional type to non-Optional type **. However, if you set print (errDictionary ["three "]?), ** nil is not allowed even though the value is nil **, so the following ** runtime error is output. ** It will be done.

Output result of non-Optional type variable with value nil


Fatal error: Unexpectedly found nil while unwrapping an Optional value

Advantages of introducing Optional type and how to use it

In Swift, the value is basically returned as Optional type. The reason is simple. By introducing Optional type and making it a specification that ** returns a grammatical error with the number of target lines **, the part that can cause a bug (the line containing = Optional type variable) can be specified. It will be easier to identify.

There are other benefits to using the Optional type. The A Swift Tour introduces how to use the Optional type as follows.

if-let syntax


var optionalName: String? = "John Appleseed"
var greeting = "Hello"   //As an initialization, the greeting is"Hello"I will return

if let name = optionalName {   //However, a person with a name(=Variable optionalName!= nil)If you say hello
    greeting = "Hello, \(name)"  // "Hello, (name)"To return with
}

print(greeting)
//Output result:
// Hello, John Appleseed

Below 10/31-Currently under construction According to the `if-let` syntax, if the value of` Optional type` is `nil`, the value of greeting remains the initializer and contains some value.

python



EOT

Recommended Posts

[Swift 5.3] Learn from A Swift Tour Swift [Xcode 12.1] <10/28 under construction>
Call a C function from Swift
Programming beginners learn PHP from a Java perspective-variables-
Call a program written in Swift from Processing (Java)