A Swift.

defer

Before leaving the current scope, execute the code in defer. If there are more than one defer, proceed from the bottom up and from the outside in.

func test {
	defer {
            print("second")
            defer {
                print("third")}}defer {
            print("first")}}Copy the code

@testable

Testable. Change the level of access to files. For example, unit tests can use @testable Import Module to access internal code from the Pods Project.

@testable import FooModule
Copy the code

@convention

Modify closures to meet the needs of different scenarios:

@convention(swift) , @convention(block),@convention(c)

let methond = class_getInstanceMethod(Animal.self, #selector(Animal.eat(food:)))
let imp = method_getImplementation(methond!)
// Use @convention(c) to declare a C-compatible closure
typealias Imp  = @convention(c) (Animal.Selector.String) - >Void
// force the function pointer to a pointer with the corresponding argument
let castImp = unsafeBitCast(imp, to: Imp.self)
Copy the code

class

Decorates a protocol that can only be observed by a class.

protocol Renderable: class {}
Copy the code

associatedtype

Association types, similar to class and struct reflection, are used semantically because we do not adhere to both A protocol\ and A protocol\.

protocol Renderable: class {
    associatedtype Shape
    func draw(with shape: Shape)
}
Copy the code

fallthrough

For switch, different case through effect. That is, after the above case is executed, if there is a fallthrough decoration, the next case is executed.

var age = 5
switch age {
case 0.5:
	print("baby")
	fallthrough
case 5..<18:
	print("teenager")
case 18.100:
	print("adult")
default:
	break
}
// log
// baby
// teenager
Copy the code

where

Generic constraint

func eat<T>(food: T) where T: Eatable {}
Copy the code

Self

Used in a protocol to refer to classes that comply with the protocol. As in a protocol extension, use self. Self to print the class name.

protocol Eatable {
    var name: String { get}}extension Eatable {
    var name: String {
        return String(describing: Self.self)}}Copy the code

Type

Class type: The type of the parameter used as the parameter or attribute of the method declaration.

func test(type: UIView.Type) {}

var test: UIView.Type = UIView.self
Copy the code

throw, throws

Throws an exception that can be caught using do-try-catch.

func sendMessage(_ message: String, to phone: Int) throws -> Void {
	guard message.count > 0 else {
		throw NSError(domain: "Illegal Message", code: 0, userInfo: nil)}// ...
}
Copy the code

rethrows

Throws an exception in the passed closure, that is, the passed closure throws an exception, and the function rethrows the exception one level up.

func help(_ action: ((String, Int) throws -> Void)) rethrows -> Void {
	try action("".110)}do {
	try help(self.sendMessage(_:to:))
	}
catch {
	// An exception by sendMessage -> help re> is received
	print(error)
}
Copy the code

operator

Custom operators

prefix operator ++
Copy the code

prefix

Declarations for custom pre-operator declarations, or pre-operator methods. The document

prefix operator~ +prefix func~ +(good: String) -> String {
    return good + Copyright © 2017 ABC
}
Copy the code

infix

Custom middle operator

infix operatorTo:AdditionPrecedence
func ~ (left: String, right: String) -> String {
    return left + ":" + right
}
Copy the code

postfix

Custom postfix operators

postfix operator~ -postfix func~ -(content: String) -> String {
    guard content.count > 2 else { return content }
    return content.substring(from: String.Index(encodedOffset: 2))}Copy the code

asociativity, precedence

The previous version is used for the associative declaration of user-defined operators, but the current version is invalid. Use precedence group.

infix operatorTo:AdditionPrecedence
func ~ (left: String, right: String) -> String {
    return left + "" + right
}
Copy the code

left

The previous version was used to customize the binding direction of the operator

right

The previous version was used to customize the binding direction of the operator

convenience

The convenience constructor, which encapsulates its own specified constructor, must call its own specified constructor within the implementation.

convenience init() {
    self.init(frame: CGRect.zero)
}
// Specify the constructor
override init(frame: CGRect) {
    super.init(frame: frame)
}
Copy the code

dynamic

Runtime modifier. More care is needed in practical use.

  • In objective-C source projects, Swift classes that inherit objective-C will all register with the Runtime, meaning that setters and getters are generated for all properties by default, and custom methods appear in the Runtime.
  • In the Swift source project, since the compiler prefers to optimize all Swift classes for function table distribution (analogous to C++ vtable), if you want to access a property or method in objective-C code, you must add it before the Swift property or methoddynamicModifier, registered to runtime (only by@objcModified methods may be optimized by the compiler for distribution into a function table.
/// Objective-C source project class SomeClass {var name: String = "Scy" func test() {}} Class SomeClass {@objc dynamic var name: String = "Scy" @objc dynamic func test() {}}Copy the code

indirect

A recursive reference in an enumeration that uses its own enumeration type in an enumeration.

indirect enum Animal {
    case Human(eat: Animal)
    case bird(eat: Worm)}struct Worm {
    var food = ["bugA"."bugB"]}Copy the code

mutating

Modifier method used to change its value in Struct, Enum, or Protocol. Note the use in the protocol:

If the protocol is implemented by a structure (enumeration) and the structure needs to change its value, it must be added before the protocol methodmutating

protocol Renameable {
    var name: String { set get }
    mutating func rename(a)
}

struct Dog: Renameable {
    var name: String
	func rename(a) {
        name = "happy" + name
    }
}
Copy the code

nonmutating

Modifier method used to disallow methods in Struct, Enum, Protocol from changing their values.

protocol Renameable {
    var name: String { set get }
    nonmutating func rename(a)
}
Copy the code

#available

Modifies a class or method for conditional compilation.

#colorLiteral

When encoding, use this keyword to directly play the custom color picker.

#imageLiteral

When encoding, use this keyword to pop up the gallery selector within assets directly.

#column

Same as the objective-C macro __column__, which outputs the current number of columns.

#file

Same as the objective-C macro __file__, which prints the current file name.

#function

Same as the objective-C macro __function__, which prints the name of the current method.

#line

Same as the objective-C macro __line__, which prints the current number of lines.

#sourceLocation

Used to modify the values of #file and #line for debugging purposes.

#sourceLocation(file: "DebugInfo", line: 100)
#file = "DebugInfo", #line = 100
#sourceLocation()
// Restore normal output
Copy the code

Objective – C

__packed

Can cause variables or structure members to use minimal alignment, is more common in C language structure.

struct Person {
  int age;
} __attribute__ ((__packed__));

struct __packed Person;
Copy the code

goto

Has been abandoned by history, but Swift partially implements this functionality with the break, continue jump statement.

loop: if (n<200) { n++; &emsp; &emsp; goto loop; }Copy the code

Nil

Used to indicate that a class object is empty, the same as nil, just a semantic distinction.

// Nil = nil = ((void *)0)
Class FooClass = Nil;
Copy the code

voletile

Direct access to raw memory addresses, ignoring compiler optimizations. Prevent in multithreading, read register cache, resulting in data synchronization errors.

void cFunction(volatile int *ptr) {}

@interface FooClass : NSObject
{
    volatile int *_ptr;
}
@property (nonatomic) volatile int pointee;
@end
Copy the code

assign/strong, readwrite, nonable, atomic

The default modifier when no modifier is added.

@property NSString *name;
Copy the code

atomic

The default implementation of the setter and getter with @Synthesized (self) is relatively thread-safe, because thread races still occur through direct access to instance variables. Properties in Swift are introduced in Objective-C and default to nonatomic.

@interface FooClass() @property (atomic) NSString *property; @end // adds a lock to the setter and getter. But the @impletation FooClass @synthesize property = _property; - (void)setProperty:(NSString *)property { @synchronized(self) { if (_property ! = property) { [_property release]; _property = [property retain]; } } } - (NSString *)property { @synchronized(self) { return _property; } } @endCopy the code

nonable, nonnull

Property, used at Objective-C compile time to check if a pointer can be null and throw a warning. The mixing corresponds to optional and non-optional values in Swift.

In fact, these null-related modifiers are primarily used to bridge to Swift, which in Objective-C is more of a constraint on the coder.

@property (nullable) NSString *firstName;
@property (nonnull) NSString *lastName;
Copy the code

_Nullable, _Nonnull, __nonnull, __nullable

Decorates parameters and return values, used in Objective-C to constrain parameter passing and throw a warning if an error occurs. The mixing corresponds to optional and non-optional values in Swift.

- (NSString *_Nullable)hello;
- (NSString *_Nonnull)hi;
Copy the code

null_resetable

At sign property, the value can never be null, but set can be null, that is, [obj setProperty:nil] is legal, but you need to override setter methods to handle null cases.

@interface FooClass : NSObject
@property (null_resettable) NSString *name;
@end
  
@impletation FooClass
- (void)setName:(NSString *)name {
	if (name == nil) {
        // ....
    }
}
@end
Copy the code

null_unspecified

Decorates @property to alert the coder that the property may be null. When the null_Unspecified attribute is used in Swift, it is an optional value in Swift.

@property (null_unspecified) NSString *name;
Copy the code

@synthesize

Used to synthesize member variables, setters and getters.

@implementation FooClass
@synthesize property = _property;
@end
Copy the code

@dynamic

Does not automatically generate member variables, setters, and getters at compile time. Ns-managed object in CoreData, for example, creates setters and getters dynamically at run time, which is called dynamic binding.

@implementation FooClass
@dynamic property;
@end
Copy the code

@available

Compile instructions, generally used for version constraints.

if (@available(iOS 9, *)) {
	// code for iOS 9
}
Copy the code

@encode

Given a type, output one or more bits of code, often used in method signatures.

@encode(type)
Copy the code

@package

Access modifier, in three cases.

@public in 32bit Compiler

In 64bit, @public in the same framework

Under 64bit, different frameworks are @private

@interface NSURLResponse : NSObject <NSSecureCoding, NSCopying>
{
    @package
    NSURLResponseInternal *_internal;
}
Copy the code