This article mainly introduces the iOS interview question -Swift, for everyone’s study or work has a certain reference learning value, interested partners can understand oh

Introduction to Swift,

Swift is a new programming language released by apple at WWDC in June 2014. It draws on the language features of JS,Python,C#,Ruby and so on. It looks scripted

Advantages of Swift:

  1. Swift is more secure, it’s a type-safe language.
  2. Swift is easy to read, with simple syntax and file structure.
  3. Swift is easier to maintain and has a clearer structure when files are separated.
  4. Swift has less code and a concise syntax that saves a lot of redundant code
  5. Swift is faster and performs better

How do Swift and OC call each other?

Swift calls the OC code

Create a target-bribridge-header. h bridge file and import the OC dock file from the Joe file

OC calls the Swift code

H file. If Swift needs to be called by OC, @objc should be used to modify the method or attribute

What’s the difference between a class and struct

In Swift,class is a reference type (pointer type) and struct is a value type

Value types

Value types are copied as they are passed and assigned; Assigning a value to a var or let or passing a parameter to a function directly copies all contents of the file. This is similar to copying and paste operations on a file, and a new copy of the file is created. Belong to deep copy

Value types: structures, such as enumerations, are stored and manipulated in stack space

Reference types

Reference types use only one “point” of the reference object; Assigning a value to a var, let, or function makes a copy of the memory address, similar to making a copy of a file (shortcut, link) that points to the same file. Belongs to a shallow copy

Reference types: Such as Class, are stored and manipulated in heap space

Class and struct

  1. Classes have the following capabilities that structs do not
  2. Class can be inherited, and subclasses can use the features and methods of their parent class
  3. Conversions can examine and interpret an instance object at run time
  4. Class can use deinit to release resources
  5. A class can be referenced more than once

Struct advantage: Small structure, suitable for copying operations, compared to a class instance referenced multiple times, structs are more secure without worrying about memory leaks

What is available in Swift (Optional)

  1. In Swift, selectable is used to express the case where a variable is empty, and when a variable is empty, its value is nil
  2. Put a question mark after the type name? To define a lectotype
  3. Either a value type or a reference type can be a selectable variable
var name: String? Var age: Int? Print (name, age) // Print nil, nilCopy the code

Swift, what is generics?

Generics are designed to increase the flexibility of code. They can be variables or methods that correspond to any type of code. Generics parameterize types, increasing code reuse and reducing code volume

Func swap<T>(a: inout T, b: inout T) {(a, b) = (b, a)}Copy the code

What is the difference between open, public, internal, fileprivate and private?

Swift has five levels of access control permissions, from highest to lowest: Open, public, Internal, Fileprivate, and private

They follow the basic rules: high-level variables are not allowed to be defined as members of lower-level variables. For example, a private class is allowed to contain public String values, whereas lower-level variables can be defined in higher-level variables.

Open: has the highest level of access to classes and methods that can be accessed and overridden in any module. Public: has the highest level of access to classes and methods that can be accessed and overridden in any module. **internal:** Default permissions, only allowed in the current module, can be inherited and overridden, not allowed in other modules fileprivate: modified objects can only be accessed in the current file; Private: indicates the lowest level of access permission. Access is only allowed within a defined scope

Key words :Strong,Weak,Unowned difference

  1. The memory management mechanism of Swift is the same as that of OC, which is ARC management mechanism. Strong, Weak are used in the same way as OC
  2. Unowned(no host reference), a strong reference is not generated, but the memory address of the instance is still stored after the destruction of the instance (similar to unsafe_unretained in OC). Attempts to access the retained reference after the destruction of the instance may result in runtime errors (wild Pointers)

How to understand copy-on-write?

Value type (such as :struct). When copied, the copied object and the original object actually point to the same object in memory, and a new object is created in memory if and only if the copied object is modified

  1. To improve performance, Struct, String, Array, Dictionary, and Set adopt Copy On Write technology
  2. For example, a copy operation is performed only when there is a write operation
  3. Swift ensures optimal performance for assignment operations of library value types, so there is no need to avoid assignment in order to ensure optimal performance

What is attribute observation

Property observation refers to the monitoring and response of property properties within the current type. Property observation is a feature in Swift, which has two types, willSet and DIDSet

var title: String {
    willSet {
        print("willSet", newValue)

    }
    didSet {
        print("didSet", oldValue, title)
    }
}
Copy the code

WillSet will pass a newValue, which is called newValue by default

DidSet passes old values, oldValue by default setting property values in the initializer does not trigger willSet and didSet

Why does Swift design String,Array, and Dictionary as value types

The value type operates on the stack, while the reference type operates on the heap. The stack operation is only the movement of a single pointer, while the on-heap operation involves merging, shifting, and relinking. Swift is designed in this way to reduce the number of memory allocations and reclaims on the heap Copy-on-write minimizes value transfer and copy overhead

How to design some methods in protocol in Swift as optional?

  1. By adding @objc in front of the protocol and method, and then adding the optional keyword in front of the method, you essentially change the protocol to OC
@objc protocol someProtocol {
  @objc  optional func test()
}
Copy the code
  1. Use extensions to specify alternative methods. In SWIFT, protocol extensions can define default implementations of some methods
protocol someProtocol {
    func test()
}

extension someProtocol{
    func test() {
        print("test")
    }
}
Copy the code

What is the difference between comparing initialization methods (init) in Swift and OC

The swift initialization method is more strict and accurate. The Swift initialization method needs to ensure that all non-optional member variables are initialized, and swFIT has added the convenience and required keywords to modify the initializer

  • Convenience provides only a convenient initializer that must be initialized using a specified initializer
  • Required forces a subclass to override an initialization method decorated in its parent class

What is the difference between comparing protocol in Swift and OC

Similarities: Both can be used as proxies; Differences: The protocol in Swift can also abstract the interface and realize protocol-oriented, thus greatly improving the programming efficiency. The Protocol in Swift can be used for value type, structure and enumeration.

What is the difference between introspection in SWIFT and OC

Introspection in OC is the operation of determining whether an object belongs to a class. There are two ways

[obj iskinOfClass:[SomeClass class]]
[obj isMemberOfClass:[SomeClass class]]
Copy the code

In Swift, since many classes do not inherit from NSObject, Swift uses IS to determine whether a class belongs to a type. Is can apply not only to classes, but also to enums and structs

What is function overloading? Does Swift support function overloading?

Function overloading means that the function name is the same but the number of parameters is different, or the parameter type is different, or the parameter label is different. The return value type has nothing to do with function overloading. Swift supports function overloading

Enumerations in Swift, the distinction between associated values and raw values?

Associated values – Sometimes it is useful to store enumerated member values associated with other types of variables

// associative Value enum Date {case digit(year: Int, month: Int, day: Int) case string(string)}Copy the code

Raw values — Enumerators can be pre-associated with default values of the same type, called: raw values

// original value enum Grade: String {case perfect = "A" case great = "B" case good = "C" case bad = "D"}Copy the code

The above is the full text, I hope to help you

Citation: Original address