1. 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:
- Swift is more secure, it’s a type-safe language.
- Swift is easy to read, with simple syntax and file structure.
- Swift is easier to maintain and has a clearer structure when files are separated.
- Swift has less code and a concise syntax that saves a lot of redundant code
- Swift is faster and performs better.
2. How do Swift and OC call each other?
- Swift calls to the OC code need to create one
Target-BriBridging-Header.h
The bridge file, in Joe file import need to call OC generation dock file can be - OC calls Swift code direct import
Target-Swift.h
If Swift needs to be called by OC, it needs to use @objc to modify the method or attribute
What is the difference between a class and a 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 of the reference objects
Point to the
; 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
4. Class and struct comparison, advantages and disadvantages?
Classes have the following functions that structs do not:
- Class can be inherited, and subclasses can use the features and methods of their parent class
- Conversions can examine and interpret an instance object at run time
- Class can use deinit to release resources
- A class can be referenced more than once
The advantage of struct:
- Structs are small and suitable for copying operations, making them safer than having a class instance referenced multiple times
- Don’t worry about memory leaks
5. Swift- Optional
- In Swift, selectable is used to express the case where a variable is empty, and when a variable is empty, its value is nil
- Put a question mark after the type name? To define a lectotype
- 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
6. Swift – generic?
- 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
7. Access control keyword open, public, internal, fileprivate, private difference?
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 access permission, which modifies classes and methods that can be accessed and overridden in any module.
- Public: the only difference between open and public is that it does not allow other modules to inherit or rewrite
- Internal: The default permission that can be accessed only in the current module and can be inherited or overridden, but not in other modules
- Fileprivate: The modified object is accessible only in the current file;
- Private: indicates the lowest level of access permission. Access is only allowed within a defined scope
8. Key words :Strong,Weak,Unowned
- 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
- 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). Attempting to access the retained reference after the destruction of the instance will cause runtime errors (wild Pointers).
9. 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.
- To improve performance, Struct, String, Array, Dictionary, and Set adopt Copy On Write technology
- For example, a copy operation is performed only when there is a write operation
- 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
10. 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 will pass the oldValue, oldValue by default
- Setting property values in an initializer does not trigger willSet and didSet
11. Why does Swift design String,Array,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
12. How to design some methods in protocol in Swift as optional?
- Add before protocol and method
@objc
, and then add it before the methodoptional
Keyword, change mode is actually the protocol into OC mode
@objc protocol someProtocol {
@objc optional func test()
}
Copy the code
- 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
13. What is the difference between 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 protocol in Swift and OC?
- Protocol in Swift and OC have the same point in that both can be used as agents.
- 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.
15. 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 or not, in the following 2 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
16. What is function overloading? Does Swift support function overloading?
- Function overloading is when the function name is the same, the number of arguments of the function is different, or the parameter type is different, or the parameter label is different, and the return value type is independent of the function overloading
- Swift supports function overloading
17. Enumerations in Swift, the distinction between associated values and primitive 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
18. What does a closure look like in Swift?
{(parameter list) -> Return value type in function body code}Copy the code
19. What is a trailing closure?
- Take a long closure expression as the last argument to the function
- The readability of functions can be enhanced by using trailing closures
- A trailing closure is a closure expression written outside (after) the function call parentheses
Func exec(v1: Int, v2: Int, fn: (Int, Int) -> Int) {print(fn(v1, v2))} 20) {$0 + $1}Copy the code
20. What is an escape closure?
When a closure is passed as an actual argument to a function or variable, we say that the closure escapes. To clarify that escaping is allowed, we write @escaping before the formal argument.
- Non-escape closures, escape closures, are generally passed to functions as arguments
- Non-escaping closures: Closure calls occur before the end of a function, and the closure calls are in function scope
- Escaping closure: It is possible for a closure to be called after a function ends. Closure calls that escape the scope of a function are required with the @escaping declaration
// Define an array to store the closure type var completionHandlers: [() - > Void] = [] / / closures as actual parameters in the method, the storage to the external variable func someFunctionWithEscapingClosure (completionHandler: @escaping () -> Void) { completionHandlers.append(completionHandler) }Copy the code
If you do not mark the function with the formal argument @escaping, you will experience a compile-time error.
21. What is an automatic closure?
An automatic closure is a closure that is automatically created to package expressions passed to functions as actual arguments. It takes no actual arguments, and when it is called, it returns the value of the internally packaged expression. The nice thing about this syntax is that it lets you omit the parentheses surrounding functional formal arguments by writing plain expressions instead of explicit closures.
func getFirstPositive(_ v1: Int, _ v2: @autoclosure () -> Int) -> Int? {
return v1 > 0 ? v1 : v2()
}
getFirstPositive(10, 20)
Copy the code
- To avoid conflicts with expectations, it is best to make it clear where @Autoclosure is used that this value will be deferred
- @autoClosure will automatically wrap 20 into a closure {20}
- @Autoclosure only supports arguments in () -> T format
- @Autoclosure does not support only the last parameter
- @autoclosure and no @Autoclosure constitute function overloading
If you want automatic closures to allow escape, use both the @autoclosure and @escaping flags.
22. What is the difference between stored attributes and calculated attributes in SWIFT?
The attributes associated with instance objects in Swift fall into two broad categories
Stored Property
- Similar to the concept of a member variable
- Stored in the memory of the instance object
- Structures and classes can define storage properties
- Enumerations cannot define storage properties
Computed Properties (Computed Property)
- The essence is the method (function)
- Does not occupy the memory of the instance object
- Enumerations, structures, and classes can all define computed properties
Struct diameter: struct diameter: struct diameter: Double { set { radius = newValue / 2 } get { return radius * 2 } } }Copy the code
23. What is a Lazy Stored Property?
Using lazy you can define a lazy storage property that is initialized on the first use of the property (similar to lazy loading in OC)
-
The lazy attribute must be a var, not a let
- The let must have the value before the initialization method of the instance object completes
-
If multiple threads access the lazy property for the first time
- There is no guarantee that the property will be initialized only once
Class PhotoView {// Lazy var image: image = {let URL = "https://.. x.png" let data = Data(url: url) return Image(data: data) }() }Copy the code
24. What is a property viewer?
You can set property observers for non-lazy VAR storage properties to listen for property changes through the keywords willSet and didSet
struct Circle { var radius: Double { willSet { print("willSet", newValue) } didSet { print("didSet", oldValue, Radius)}} init() {self.radius = 1.0 print("Circle init! )}}Copy the code
25. What Type Property is in SWIFT?
Strictly speaking, attributes can be divided into
Instance Property: Can only be accessed from Instance objects
- Stored Instance Property: Stored in the memory of Instance objects. Each Instance object has one copy
- Computed Instance Property
Type Property: Can only be accessed by Type
- Stored Type Property: During the entire run of the program, only one portion of memory is Stored (similar to global variables).
- Computed Type Properties (Computed Type Property)
You can define the type attribute p as static or use the class keyword if it’s a class
struct Car {
static var count: Int = 0
init() {
Car.count += 1
}
}
Copy the code
Unlike store instance properties, you must set initial values for store type properties
- Because types don’t have an init initializer to initialize storage properties like instance objects do
The storage type attribute is lazy by default and is initialized the first time it is used
- It is guaranteed to be initialized only once, even if accessed by multiple threads at the same time
- The storage type attribute can be let
Enumerated types can also define type properties (storage type properties, computed type properties)
26. How to use singleton pattern in SWIFT?
Singletons can be written using the type attribute +let+private; The code is as follows:
public class FileManager { public static let shared = { // .... / /... return FileManager() }() private init() { } }Copy the code
27. What is the subscript in swift?
- Subscript can be used to add subscripts to any type (enumeration, struct, class)
- Subscript syntax is similar to instance methods, computed properties, and is essentially methods (functions)
Use as follows:
Class Point {var x = 0.0, y = 0.0 subscript(index: Int) -> Double { set { if index == 0 { x = newValue } else if index == 1 { y = newValue } } get { if index == 0 { return X} else if index == 1 {return y} return 0}} var p = Point() // 11.1 print(p.y) // 22.2Copy the code
27. Brief description of initializers in Swift?
- Classes, structs, and enumerations can all define initializers
- Class has two types of initializers:
Designated Initializer
,Convenience Initializer
// Init (parameters) {statements} // Easy init(parameters) {statements}Copy the code
Rules:
- Each class has at least one designated initializer, which is the primary initializer of the class
- The default initializer is always the designated initializer for the class
- Classes tend to have a small number of designated initializers, and a class usually has only one
Rules for calling each other to initializers
- The specified initializer must be called from its immediate parent
- The convenience initializer must call another initializer from the same class
- The convenience initializer must eventually call a designated initializer
28. What is the optional chain?
An optional chain is a procedure that calls and queries optional properties, methods, and subscripts, which may be nil. If the option contains a value, the attribute, method, or subscript was called successfully; If the optional is nil, calls to properties, methods, or subscripts return nil. Multiple queries can be linked together, and if any node in the chain is nil, the whole chain fails gracefully.
- More than one? You can link them together
- If any node in the chain is nil, then the whole chain will fail the call
29. What is Operator Overload?
Classes, structs, and enumerations can provide custom implementations of existing operators. This operation is called operator overloading
Struct Point {var x: Int var y: Int static func + (p1: Point, p2: Point) -> Point {return Point(x: Point) p1.x + p2.x, y: p1.y + p2.y) } } var p1 = Point(x: 10, y: 10) var p2 = Point(x: 20, y: 20) var p3 = p1 + p2Copy the code
The statement
The answer to the interview questions in this article is based on the collection of various gods, the answer is not necessarily the most comprehensive, the most appropriate, if there is a question, welcome to actively discuss.
Reference article:
www.jianshu.com/p/ca1ff3749…
Github.com/ReginaVicky…