Review of 2021 swift interview Basics


Swift can import C + + Object C (C’s super) cocoa (Object C framework). Swift is a case sensitive language, so uppercase and lowercase letters are different.
Type safety: different types of assignment will be detected at runtime, and an error will be marked; Let constant var variable
import Cocoa

var varA = 42
varA = “This is hello”
Print (vara) type inference: infer the type of the current variable according to the following assignment, let meaningoflife = 42
//Meaningoflife will be inferred as int type
Variable output: insert the variable print (“(name’s official website address is: (site)”) with a backslash and parentheses. Swift optional type: optional is an enumeration containing two cases, none and some (T), which is used to indicate that there may or may not be a value var optionenter: int?
var optionalInteger: Optional<Int>

var num:String?
Var num: optional < double > forced resolution: swift “!” (unpacking). When the optional type has a value, no error will be reported, otherwise an error will be reported. You can unpack with optional binding or optional chain, so that no error will occur; var myString:String?

myString = “Hello, Swift!”

if myString != nil {
//Forced resolution
print( myString! )
Print (“mystring value is nil”)

Automatic parsing
You can use exclamation marks (!) when declaring optional variables Replace the question mark (?). In this way, the optional variable does not need an exclamation point (!) when used To get the value, which will be parsed automatically.
var myString:String!

myString = “Hello, Swift!”

if myString != nil {
Print (“mystring value is nil”)

Optional binding: if there is a value, assign optional to this variable / constant; If there is no value, it will not run and report an error
if let constantName = someOptional {

Optional chain: note that there is a “question mark”, which is an optional chain: all codes after the “question mark” will run only when the code before the “question mark” has a value. This does not affect the basic data type of album, because whether this line returns nil or uppercase album names, it is an optional string.

let album = albumReleased(year: 2006)?.uppercased()
print(“The album is (album)”)

Nil merge operator “??”: it works as if you would say, “use the value of a if you can, and use the value of B if a is nil.

let num = A ?? B

Swift literal: refers to a value that can directly indicate its type and assign a value to a variable, such as a specific number, string or Boolean value

Define enumeration

enum name {
case Sunday
case Monday
case Saturday

var user = name.Sunday

user = .TUESDAY

switch user {

case .Sunday:
Print (“Sunday”)
case .Monday:
Print (“Monday”)
case .TUESDAY:
Print (“Tuesday”)
Print (“Wednesday”)
Print (“Thursday”)
case .FRIDAY:
Print (“Friday”)
case .Saturday:
Print (“Saturday”)


Enumerate related values

enum Student{
case Name(String)
case Mark(Int,Int,Int)
var studDetails = Student.Name(“Runoob”)
var studMarks = Student.Mark(98,97,95)

switch studMarks {
case .Name(let studName):
Print (“the student’s name is: (studname).”)
case .Mark(let Mark1, let Mark2, let Mark3):
Print (“student’s grades are: (mark1), (Mark2), (Mark3).”)

Enumerate raw values
The original value can be a string, character, or any integer or floating-point value. Each original value must be unique in its enumeration declaration.
When enumerating with the original value as an integer, you do not need to explicitly assign a value to each member, and swift will automatically assign a value to you.

enum Month: Int {
case January = 1, February, March, April, May, June, July, August, September, October, November, December

let yearMonth = Month.May.rawValue
Print (“the digital month is: (Yearmonth)”) Number month: 5

Structure application: structure instances always define your custom data types through value passing.

  • The main purpose of structs is to encapsulate a small number of related simple data values.
  • It is reasonable to expect that when a structure instance is assigned or passed, the encapsulated data will be copied rather than referenced.
  • Any value type attribute stored in the structure will also be copied, not referenced.
  • The structure does not need to inherit the properties or behaviors of another existing type.

Value transfer: when assigning a value, the copied value is transferred. Modifying the previous or the latter value will not affect the other value Structure enumeration value face variable

func test() {
var age = 18

var age2 = age

age = 20

age2 = 30




Reference passing: when passing, the address assigned to the previous instance is the same address. Modifying any one will affect the previous instance
Class omits 1. In the function of the structure, you need to modify its own attributes. You need to modify the function with mutating, but the class does not
2. The essence of mutating is to modify the implicit parameter self with inout
3. The parameter decorated with inout uses an address, not a value, but a reference
4. Mutating modifies functions and inout modifies parameters

Because a class is a reference type, there may be multiple constants and variables referencing a class instance in the background at the same time.
In order to determine whether two constants or variables refer to the same class instance, swift has built-in two identity operators:

Identity operator===

Returns true if two variables refer to the same instance

No identity operator==

Returns true if two variables refer to different instances

class SampleClass: Equatable {
let myProperty: String
init(s: String) {
myProperty = s
func ==(lhs: SampleClass, rhs: SampleClass) -> Bool {
return lhs.myProperty == rhs.myProperty

let spClass1 = SampleClass(s: “Hello”)
let spClass2 = SampleClass(s: “Hello”)

if spClass1 === spClass2 {// false
Print (“reference the same class instance (spclass1)”)

if spClass1 !== spClass2 {// true
Print (“reference different class instances (spclass2)”)

Reference different class instances sampleclass

Lazy: deferred storage attribute. The stored value is calculated only when it is called for the first time. Deferred storage attribute is generally used to:
Delay object creation.
When the value of a property depends on other unknown classes

class sample {
lazy var no = number() // varKeywords are required

class number {
Var name = “runoob swift tutorial”

var firstsample = sample()
The greatness of the property observer swift

Before the willset property is set
After the didSet property is set, it is called.
Willset and didset observers are not called during property initialization

class Samplepgm {
var counter: Int = 0{
Print (“counter: (newtotal)”)
if counter > oldValue {
Print (“counter – oldvalue”)
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
Type properties
Static keyword static to define the type attribute of the value type, which is similar to the instance attribute. The type attribute is accessed through the dot operator (.) Come on. However, type properties are obtained and set through the type itself, not through instances. Examples are as follows:

struct StudMarks {
static let markCount = 97
static var totalCount = 0
var InternalMarks: Int = 0 {
didSet {
if InternalMarks > StudMarks.markCount {
InternalMarks = StudMarks.markCount
if InternalMarks > StudMarks.totalCount {
StudMarks.totalCount = InternalMarks

var stud1Mark1 = StudMarks()
var stud1Mark2 = StudMarks()

stud1Mark1.InternalMarks = 98

stud1Mark2.InternalMarks = 87

The keyword final prevents types from being overridden. Overriding enumerable constructors of types

enum TemperatureUnit {
//Kelvin, Celsius, Fahrenheit
case Kelvin, Celsius, Fahrenheit
init?(symbol: Character) {
switch symbol {
case “K”:
self = .Kelvin
case “C”:
self = .Celsius
case “F”:
self = .Fahrenheit
return nil

let fahrenheitUnit = TemperatureUnit(symbol: “F”)
if fahrenheitUnit != nil {
Print (“this is a defined temperature unit, so initialization succeeded.”)

let unknownUnit = TemperatureUnit(symbol: “X”)
if unknownUnit == nil {
Print (“this is not a defined temperature unit, so initialization failed.”)

Destructors generally release themselves, but files that operate resources themselves need to be released before the class is released

deinit {
//Perform the deconstruction process

For example, if you create a custom class to open a file and write some data, you may need to close the file before the class instance is released.

Weak and unowned references

When the closure and captured instances always refer to each other and are always destroyed at the same time, the capture in the closure is defined as no primary reference.

Conversely, when the capture reference may sometimes be nil, the capture within the closure is defined as a weak reference.
If the captured reference will never be set to nil, you should use an unowned reference instead of a weak reference. class HTMLElement {

let name: String
let text: String?

lazy var asHTML: () -> String = {
    [unowned self] in
    if let text = self.text {
        return "<\(>\(text)</\(>"
    } else {
        return "<\( />"

init(name: String, text: String? = nil) { = name
    self.text = text

deinit {
    Print ("\ (name) destructed")


//Create and print an HtmlElement instance
var paragraph: HTMLElement? = HTMLElement(name: “p”, text: “hello, world”)

//The HtmlElement instance will be destroyed and the message printed by its destructor will be visible
paragraph = nil

Swift type conversion

Wift language type conversion can determine the type of instance. It can also be used to detect whether an instance type belongs to an instance of its parent or child class.

Type conversion in swift is implemented using is and as operators. Is is is used to detect the type of value, and as is used to convert the type.
Type conversion can also be used to check whether a class implements a protocol.

Swift access control

Public can access any entity in the module, and others can access it by referencing the module
Internal can access any entity in its own module, but others cannot access the entity of the source file in the module (default)
Fileprivate is private in the file and can only be used in the current source file.
Private can only be accessed in a class. It cannot be accessed outside the scope of the class or structure.

Public is the highest access level and private is the lowest access level.

Enumeration type access
The access levels of members in the enumeration inherit from the enumeration. You cannot declare different access levels for members in the enumeration separately.

Subclass access
The access level of a subclass must not be higher than that of the parent class. For example, if the access level of the parent class is internal, the access level of the child class cannot be declared public.

Recommended Today

Lagrange interpolation — Python

Data analysis Data cleaning: missing value processing, 1 deleting records2 data interpolation3 no treatment Data in and code in resource package in Chapter4 \ demo \ data \ cataling_ sale. xls Common interpolation methods Interpolation Lagrange interpolation According to mathematical knowledge, for n known points on the plane (no two points), n-1 polynomial can be […]