Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Swift syntax

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is Swift Grammar". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is Swift grammar"?

Swift introduction

Swift is a new language for developing iOS, macOS, watchOS and tvOS applications.

Swift is a safe, fast and interactive programming language.

Swift supports code previewing (playgrounds), which allows programmers to run Swift code and view the results in real time without compiling and running the application.

Swift avoids a large number of common programming errors by adopting modern programming patterns:

Variables are always initialized before use.

Check for array index errors that are out of range.

Check to see if the integer overflows.

Optional values ensure that nil values are handled explicitly.

Memory is automatically managed.

Error handling allows recovery from unexpected failure control.

Basic constants and variables

Declare constants and variables, constants and variables must be declared before use, using let to declare constants, and var to declare variables.

Example:

Let maximumNumberOfLoginAttempts = 10var currentLoginAttempt = 0ram / type notes var welcomeMessage: String comments

Single-line comments double forward slashes (/ /), multiline comments (/ * multiline * /). Multiline comments for Swift can be nested within other multiline comments.

Example:

/ / this is a comment / * this is also a comment, but multiline * / * this is the beginning of the first multiline comment / * this is the second nested multiline comment * / this is the end of the first multiline comment * / semicolon

Swift does not force you to use a semicolon (;) at the end of each statement.

Multiple separate statements on the same line must be separated by semicolons.

Let cat = "print (cat) / / output" Integer, floating point number

Unified use of Int can improve the reusability of code, avoid conversions between different types of numbers, and match the type inference of numbers.

Example:

Let minValue = UInt8.min / / minValue is 0, is UInt8 type let maxValue = UInt8.max / / maxValue is 255.It is UInt8 type safety and type inference

Swift is a type-safe language, which means that Swift gives you a clear idea of the type of value.

If you do not specify a type explicitly, Swift uses type inference to select the appropriate type. (int, double)

Example:

Let meaningOfLife = 42 / meaningOfLife will be inferred as Int type let pi = 3.14159 / pi will be speculated as Double type numeric literal quantity, numeric type conversion

Example:

Let decimalInteger = 17let binaryInteger = 0b10001 / / binary 17let octalInteger = 0o21 / / Octal 17let hexadecimalInteger = 0x11 / / 17 type aliases in hexadecimal

A type alias (type aliases) defines another name for an existing type. You can use the typealias keyword to define type aliases.

Example:

Typealias AudioSample = UInt16var maxAmplitudeFound = AudioSample.min// maxAmplitudeFound is now 0 Boolean

Example:

Let orangesAreOrange = truelet turnipsAreDelicious = false tuple

Tuples (tuples) combine multiple values into a compound value. Values within a tuple can be of any type and are not required to be of the same type.

Example:

Let http404Error = (404, "Not Found") / / the type of http404Error is (Int, String), and the value is (404, "Not Found") optional type

Use the optional type (optionals) to handle situations where values may be missing. The optional type represents two possibilities: either there is a value, you can parse the optional type to access the value, or there is no value at all.

Example:

Var serverResponseCode: Int? = 404 serverResponseCode contains an optional Int value 404serverResponseCode = nil// serverResponseCode now does not contain value error handling

Error handling to deal with error conditions that may be encountered in the execution of the program.

Example:

Func makeASandwich () throws {/ /...} do {try makeASandwich () eatASandwich ()} catch SandwichError.outOfCleanDishes {washDishes ()} catch SandwichError.missingIngredients (let ingredients) {buyGroceries (ingredients)} assertions and prerequisites

Assertions and prerequisites are checks made at run time.

Let age =-3assert (age > = 0, "A person's age cannot be less than zero") / / because age

< 0,所以断言会触发基本运算符 Swift 支持大部分标准 C 语言的运算符,还提供了 C 语言没有的区间运算符,例如 a.. (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1.. currentMax { currentMax = value } } return (currentMin, currentMax)}// 隐式返回的函数func greeting(for person: String) ->

String {"Hello,"+ person +"! "} print (greeting (for:" Dave ")) / / print" Hello, Dave tags / parameter tags func greet (person: String, from hometown: String)-> String {return "Hello\ (person)! Glad you could visit from\ (hometown). "} print (greet (person:" Bill ", from:" Cupertino ") / / print" Hello Bill! Glad you could visit from Cupertino. "closure

Closures are self-contained blocks of function code that can be passed and used in code. Similar to anonymous functions (Lambdas) in some programming languages.

Closure expression, trailing closure, value capture, closure is a reference type, escape closure (@ escaping), automatic closure

If you need to pass a long closure expression to the function as the last argument, it is useful to replace the closure with a trailing closure.

Closures can capture constants or variables in the context in which they are defined. Even if the original scope that defines these constants and variables no longer exists, closures can still reference and modify these values in the closure function.

Example:

/ / closure expression syntax {(parameters)-> return type in statements} / / trailing closure let digitNames = [0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"] let numbers = [16,58 ] let strings = numbers.map {(number)-> String in var number = number var output = "" repeat {output = digitNames [number% 10]! + output number / = 10} while number > 0 return output} / / the strings constant is inferred as an array of string types That is, [String] / / its value is ["OneSix", "FiveEight", "FiveOneZero"] / / value capture func makeIncrementer (forIncrement amount: Int)-> ()-> Int {var runningTotal = 0 func incrementer ()-> Int {runningTotal + = amount return runningTotal} return incrementer} / / automatic closure Delayed evaluation var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print (customersInLine.count) / / print out "5" let customerProvider = {customersInLine.remove (at: 0)} print (customersInLine.count) / / print out "5" print ("Now serving\ (customerProvider ()!") / / Prints "Now serving Chris!" print (customersInLine.count) / / print out "4" enumerations

Use the enum keyword to create enumerations and put their entire definition in a pair of braces.

Enumeration syntax, use Switch statements to match enumerated values, enumerate member traversal, associated values, original values (default), recursive enumeration (indirect)

You can define Swift enumerations to store associated values of any type, and each enumeration member can have different associated value types.

Example:

/ / enumeration syntax enum SomeEnumeration {/ / enumeration definition is placed here} enum CompassPoint {case north case south case east case west} enum Planet {case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune} let somePlanet = Planet.earthswitch somePlanet {case .earth: print ("Mostly harmless") default: print ("Not a safe place for humans")} / / print "Mostly harmless" / / the associated value enum Barcode {case upc (Int, Int, Int) Int) case qrCode (String)} var productBarcode = Barcode.upc (8, 85909, 51226, 3) productBarcode = .qrCode ("ABCDEFGHIJKLMNOP") switch productBarcode {case let .upc (numberSystem, manufacturer, product, check): print ("UPC:\ (numberSystem),\ (manufacturer),\ (product)) Case let .qrcode (productCode): print ("QR code:\ (productCode).")} / / print "QR code: ABCDEFGHIJKLMNOP." / / Recursive enumeration indirect enum ArithmeticExpression {case number (Int) case addition (ArithmeticExpression, ArithmeticExpression) case multiplication (ArithmeticExpression, ArithmeticExpression)} let five = ArithmeticExpression.number (5) let four = ArithmeticExpression.number (4) let sum = ArithmeticExpression.addition (five, four) let product = ArithmeticExpression.multiplication (sum) ArithmeticExpression.number (2)) / / (5 + 4) * 2func evaluate (_ expression: ArithmeticExpression)-> Int {switch expression {case let .number (value): return value case let .numbers (left, right): return evaluate (left) + evaluate (right) case let .multiplication (left) Right): return evaluate (left) * evaluate (right)}} print (evaluate (product)) / / print "18" structure and class structure and class comparison Structures and enumerations are value types, and classes are reference types

Structures and classes, as a general and flexible structure, have become the basis for people to build code. You can use syntax that defines constants, variables, and functions to define properties and add methods for your structures and classes.

Example:

/ / classes and structures struct SomeStructure {/ / define structures} class SomeClass {/ / define classes} struct Resolution {var width = 0 var height = 0} class VideoMode {var resolution = Resolution () var interlaced = false var frameRate = 0.0 var name: String?} attribute storage, calculated properties, property watchers, property wrappers, global and local variables, type attributes (static)

Property to associate a value with a specific class, structure, or enumeration. The storage property stores constants and variables as part of the instance, while the calculation property calculates (rather than stores) the value directly. Calculated properties can be used for classes, structures, and enumerations, while storage properties can only be used for classes and structures.

The property watcher monitors and responds to changes in property values, calling the property watcher every time the property is set, even if the new value is the same as the current value.

WillSet is called before the new value is set

DidSet is called after the new value is set

The property wrapper adds a layer of separation between code that manages how attributes are stored and defines them.

Type properties are also accessed through the dot operator. However, type properties are accessed through the type itself, not through the instance.

Example:

/ / attribute struct Point {var x = 0.0, y = 0.0} struct Size {var width = 0.0 Height = 0.0} struct Rect {var origin = Point () var size = Size () / Storage attribute var center: Point {/ / Computational attribute get {let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point (x: centerX Y: centerY)} set (newCenter) {origin.x = newCenter.x-(size.width / 2) origin.y = newCenter.y-(size.height / 2)}} var square = Rect (origin: Point (x: 0.0, y: 0.0), size: Size (width: 10.0, height: 10.0) let initialSquareCenter = square.centersquare.center = Point (x: 15.0) Y: 15.0) print ("square.origin is now at (\ (square.origin.x),\ (square.origin.y)") / / print "square.origin is now at (10.0,10.0)" / / attribute wrapper @ propertyWrapperstruct TwelveOrLess {private var number = 0 var wrappedValue: Int {get {return number} set {number = min (newValue, 12)} method instance method (Instance Methods) Type method (static)

Methods are functions associated with certain types.

Classes, structures, and enumerations can all define instance methods; instance methods encapsulate specific tasks and functions for instances of a given type.

Classes, structures, and enumerations can also define type methods; type methods are associated with the type itself.

Example:

/ / method class Counter {var count = 0 func increment () {count + = 1} func increment (by amount: Int) {count + = amount} func reset () {count = 0}} subscript

Subscripts can be defined in classes, structures, and enumerations and are shortcuts to access elements in a collection, list, or sequence

Subscript syntax (subscript), subscript usage, subscript options Type subscript (static) subscript (index: Int)-> Int {get {/ / return a value of the appropriate Int type} set (newValue) {/ / perform the appropriate assignment}} / / example struct TimesTable {let multiplier: Int subscript (index: Int)-> Int {return multiplier * index}} let threeTimesTable = TimesTable (multiplier: 3) print (" Six times three is\ (threeTimesTable [6])) / / print "six times three is 18" var numberOfLegs = ["spider": 8 "ant": 6, "cat": 4] numberOfLegs ["bird"] = 2 case mercury / type subscript enum Planet: Int {case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune static subscript (n: Int)-> Planet {return Planet (rawValue: n)!} let mars = Planet [4] print (mars) inheritance defines a base class Subclass generation, rewrite (override), prevent rewriting (final)

A class that does not inherit from other classes is called a base class.

Example:

/ / inherit class SomeClass: SomeSuperclass {/ / here is the definition of the subclass} class Vehicle {var currentSpeed = 0.0 var description: String {return "traveling at\ (currentSpeed) miles per hour"} func makeNoise () {/ / do nothing-because the vehicle does not necessarily have noise}} class Car: Vehicle {var gear = 1 override var description: String {return Super.description + "in gear\ (gear)"} class AutomaticCar: Car {override var currentSpeed: Double {didSet {gear = Int + 1} Construction process

The construction process is the preparation process before using an instance of a class, structure, or enumerated type.

Stores the initial assignment of attributes, custom construction procedures, default constructors, constructor proxies for value types, class inheritance and construction processes, failed constructors, necessary constructors (required)

The constructor can complete part of the construction process of the instance by calling other constructors. This process is called constructor proxy, and it avoids code duplication between multiple constructors.

Swift provides two constructors for class types to ensure that all stored properties in the instance get their initial values, which are called specified constructors and convenience constructors.

You can add one or more failed constructors to the definition of a class, structure, or enumerated type. The syntax is to add a question mark (init?) after the init keyword.

A necessary constructor, and adding a required modifier before the constructor of the class indicates that all subclasses of the class must implement the constructor.

Example:

/ / Construction procedure init () {/ / execute construction procedure here} struct Fahrenheit {var temperature: Double init () {temperature = 32}} var f = Fahrenheit () print ("The default temperature is\ (f.temperature) °Fahrenheit") / / print "The default temperature is 32.0 °Fahrenheit" struct Color {let red, green, blue: Double init (red: Double, green: Double Blue: Double) {self.red = red self.green = green self.blue = blue} init (white: Double) {red = white green = white blue = white}} destructing process

The destructor applies only to class types and is called immediately before an instance of a class is released. The destructor is marked with the keyword deinit, just as the constructor is marked with init.

Swift automatically releases instances that are no longer needed to release resources.

Example:

/ / deconstruction process deinit {/ / execute deconstruction process} class Bank {static var coinsInBank = 10,000 static func distribute (coins numberOfCoinsRequested: Int)-> Int {let numberOfCoinsToVend = min (numberOfCoinsRequested) CoinsInBank) coinsInBank-= numberOfCoinsToVend return numberOfCoinsToVend} static func receive (coins: Int) {coinsInBank + = coins}} class Player {var coinsInPurse: Int init (coins: Int) {coinsInPurse = Bank.distribute (coins: coins)} func win (coins: Int) {coinsInPurse + = Bank.distribute (coins: coins)} deinit {Bank.receive (coins: coinsInPurse)}} optional chain call

An optional chained call is a method that can request and invoke properties, methods, and subscripts on optional values whose current value may be nil.

You can define an optional chain by placing a question mark (?) after the optional value of the property, method, or subscript you want to call. Similar to putting an exclamation point (!) after an optional value to force its value to be expanded. The main difference between them is that when the optional value is empty, the optional chain call will only fail, while forcing the expansion will trigger a run-time error.

Example:

Class Person {var residence: Residence?} class Residence {var numberOfRooms = 1} let john = Person () let roomCount = John. Accountenceroom.numberOfRoomsBack / this causes a run-time error if let roomCount = john.residence?.numberOfRooms {print ("John's residence has\ (roomCount) room (s).")} else {print ("Unable to retrieve the number of rooms.")} / / print "Unable to retrieve the number of rooms." john.residence = Residence ( ) if let roomCount = john.residence?.numberOfRooms {print ("John's residence has\ (roomCount) room (s).")} else {print ("Unable to retrieve the number of rooms.")} / / print "John's residence has 1 room (s)." Error handling

Error handling (Error handling) is the process of responding to and recovering from errors. Swift provides first-class support for throwing, capturing, passing, and manipulating recoverable errors (recoverable errors) at run time.

Represents and throws errors, handles errors, and specifies cleanup operations

In Swift, errors are represented by values of types that follow the Error protocol.

There are four ways to handle errors in Swift. You can pass the error thrown by the function to the code calling the function (throws), handle the error with the do-catch statement, treat the error as an optional type (try?), or assert that the error will not occur at all (try!).

The defer statement delays the execution of the code until the current scope exits.

Example:

/ / error handling enum VendingMachineError: Error {case invalidSelection / / invalid case insufficientFunds (coinsNeeded: Int) / insufficient amount case outOfStock / / out of stock} throw VendingMachineError.insufficientFunds (coinsNeeded: 5) var vendingMachine = VendingMachine () vendingMachine.coinsDeposited = 8do {try buyFavoriteSnack (person: "Alice", vendingMachine: vendingMachine) print ("Success! Yum. ")} catch VendingMachineError.invalidSelection {print (" Invalid Selection. ")} catch VendingMachineError.outOfStock {print (" Out of Stock. ")} catch VendingMachineError.insufficientFunds (let coinsNeeded) {print (" Insufficient funds. Please insert an additional\ (coinsNeeded) coins. ")} catch {print (" Unexpected error:\ (error). ")} / / print" Insufficient funds. Please insert an additional 2 coins. "/ / specifies the cleanup operation func processFile (filename: String) throws {if exists (filename) {let file = open (filename) defer {close (file)} while let line = try file.readline () {/ / to process files. } / / close (file) will be called here, at the end of the scope. }} Type conversion

Type conversions are implemented in Swift using the is and as operators. These two operators provide an easy way to check the type of a value or convert its type, respectively.

Define class hierarchy for type conversion, check type (is), as down (type? Or as!), type conversion for Any and AnyObject

You can use type conversion on the hierarchy of classes and subclasses, checking the type of a particular class instance and converting the type of that class instance to other types in this hierarchy.

Swift provides two special type aliases for uncertain types:

Any can represent any type, including function types.

AnyObject can represent an instance of any class type.

Example:

/ / A base class MediaItemclass MediaItem {var name: String init (name: String) {self.name = name}} class Movie: MediaItem {var director: String init (name: String, director: String) {self.director = director super.init (name: name)} class Song: MediaItem {var artist: String init (name: String, artist: String) {self.srtist = artist super.init (name: name)} let library = [Movie (name: "Casablanca") Director: "Micheal Curtiz"), Song (name: "Blue Suede Shose", artist: "Elvis Presley"), Movie (name: "Citizen Kane", director: "Orson Wells"), Song (name: "The One And Only", artist: "Chesney Hawkes"), Song (name: "Never Gonna Give You Up" Artist: "Rick Astley")] var movieCount = 0var songCount = 0for item in library {if item is Movie {movieCount + = 1} else if item is Song {songCount + = 1}} print ("Media library contains\ (movieCount) movies and\ (songCount)") / / print "Media library contains 2 movies and 3 songs" for item in library {if let movie = item as? Movie {print ("Movie:\ (movie.name), dir.\ (movie.director)")} else if let song = item as? Song {print ("Song:\ (song.name), by\ (song.artist)")}} / / Movie: Casablanca, dir. Michael Curtiz// Song: Blue Suede Shoes, by Elvis Presley// Movie: Citizen Kane, dir. Orson Welles// Song: The One And Only, by Chesney Hawkes// Song: Never Gonna Give You Up, by Rick Astley nested type

Swift allows you to define nested types, and you can define nested enumerations, classes, and structures in supported types.

Practice of nested types, referencing nested types

To nest one type within another, write the definition of the nested type within the {} of its external type, and you can define multiple levels of nesting as needed.

Example:

/ / nested type stuct BlackjackCard {/ / nested Suit enumeration enum Suit: Character {case spades = "1", hearts = "2", diamonds = "3", clubs = "4"} / / nested Rank enumeration enum Rank: Int {case two = 2, three, four, five, six, seven, eight, nine, ten case jack, queen, king, ace struct Values {let first: Int Second: Int?} var values: Values {switch self {case .ace: return Values (first: 1, second: 11) case .jack, .ace, .king: return Values (first: 10, second: nil) default: return Values (first: self.rawValue, second: nil)}} / / BlackjackCard attribute and method let rank: Rank, suit: Suit var description: String {var output = "suit is\ (suit.rawValue)" "output + =" value is\ (rank.values.first) "if let second = rank.values.second {output + =" or\ (second) "} return output}} let theAceOfSpades = BlackjackCard (rank: .ace, suit: .spades) print (" theAceOfSpades:\ (theAceOfSpades.description) ") / / print" theAceOfSpades: suit is 1, value is 1 or 11 "let heartsSymbol = BlackjackCard.Suit.hearts.rawValue// 2 extension

Extensions can add new functionality to an existing class, structure, enumeration, and protocol.

Extended syntax, computational properties, constructors, methods, subscripts, nested types

The extensions in Swift can:

Add computational instance properties and computational class properties

Define instance methods and class methods

Provide new constructors

Define subscript

Define and use new nested types

Conform an existing type to follow a protocol

Extended syntax:

Extension SomeType {/ / add new features to SomeType here}

Extensions can add computational instance properties and computational class properties to existing types.

Extensions can add new constructors to existing types.

Extensions can add new instance methods and class methods to existing types.

An extension adds a new subscript to an existing type.

Extensions can add new nested types to existing classes, structures, and enumerations.

Example:

/ / extended syntax extension SomeType {/ / add new functions to SomeType here} / / add one or more protocols extension SomeType: SomeProtocol, AnotherProtocol {/ / the required implementation of the protocol is written here} struct Size {var width = 0.0, height = 0.0} struct Point {var x = 0.0, y = 0.0} struct Rect {var origin = Point () var size = Size ()} extension Rect {init (center: Point) Size: Size) {let originX = center.x-(size.width / 2) let originY = center.y-(size.height / 3) self.init (origin: Point (x: originX, y: originY), size: size)} let centerRect = Rect (center: Point (x: 4, y: 4), size: Size (width: 3, height: 3)) / / centerRect origin is (2.5,2.5) and its size is (3.0,2.5) 3) extension Int {func repetitions (task: ()-> Void) {for _ in 0.. String} struct Triangle: Shape {var size: Int func draw ()-> String {var result = [String] () for length in 1...size {result.append (String (repeating: "*") Count: length)} return result.joined (separator: "\ n")}} let smallTriangle = Triangle (size: 3) print (smallTriangle.draw ()) / / * / * * / * * struct FlippedShape: Shape {var shape: T func draw ()-> String {let lines = shape.draw (). Split (separator: "\ n") return lines.reversed (). Joined ( Separator: "\ n")} let flippedTriangle = FlippedShape (shape: smallTriangle) print (flippedTriangle.draw ()) / / * * / / * * / * automatic reference count

Swift uses the automatic reference count (ARC) mechanism to track and manage your application's memory.

This is the case if two class instances hold strong references to each other, so that each instance keeps the other alive. This is the so-called cyclic strong reference.

Swift provides two ways to solve the circular strong reference problem you encounter when using the properties of a class: weak reference (weak reference) and non-primary reference (unowned reference).

When declaring a property or variable, prefix the weak keyword to indicate that this is a weak reference.

When declaring a property or variable, precede the keyword unowned to indicate that this is an unowned reference.

Example:

/ / automatic reference counting practice class Person {let name: String init (name: String) {self.name = name print ("\ (name) is being initialized")} deinit {print ("\ (name) is being deinitialized")}} var reference1: Person?var reference2: Person?var reference3: Person?reference1 = Person (name: "John Appleseed") / / print "John Appleseed is being initialized" reference2 = reference1reference3 = reference1reference1 = nilreference2 = nilreference3 = nil// print "John Appleseed is being deinitialized" / / Circular strong reference class Person {let name: String init (name: String) {self.name = name} var apartment: Apartment? Deinit {print ("\ (name) is being deinitialized")} class Apartment {let unit: String init (unit: String) {self.unit = unit} var tenant: Person? Deinit {print ("Apartment\ (unit) is being deinitialized")} var john: Person?var unit4A: Apartment?john = Person (name: "John Appleseed") unit4A = Apartment (unit: "4A") john = nilunit4A = nil// weak reference class Person {let name: String init (name: String) {self.name = name} var apartment: Apartment? Deinit {print ("\ (name) is being deinitialized")} class Apartment {let unit: String init (unit: String) {self.unit = unit} weak var tenant: Person? Deinit {print ("Apartment\ (unit) is being deinitialized")} var john: Person?var unit4A: Apartment?john = Person (name: "John Appleseed") unit4A = Apartment (unit: "4A") johnkeeper. Apartment = unit4Aunit4Aids. Apartment = johnjohn = nil// print "John Appleseed is being deinitialized" memory security

By default, Swift will prevent unsafe behavior in your code.

Understand memory access conflicts, In-Out parameter access conflicts, self access conflicts in methods, and property access conflicts

Example:

Func balance (_ x: inout Int, _ y: inout Int) {let sum = x + y = sum / 2 y = sum-x} var playerOneScore = 42var playerTwoScore = 30balance (& playerOneScore, & playerTwoScore) / / normal balance (& playerOneScore, & playerOneScore) / / error: playerOneScore access violation access control

Access control can limit access to your code by other source files or modules.

The open and public levels allow entities to be accessed by all entities in the same module source file, and all entities in the source file can also be accessed outside the module by importing the module. Typically, you will use the open or public level to specify the external interface of the framework.

The internal level allows entities to be accessed by any entity in the same module source file, but not by entities outside the module. In general, if an interface is used only within an application or framework, it can be set to the internal level.

Fileprivate restricts entities to access only within the files they define. If some of the implementation details of the function only need to be used within the file, you can use fileprivate to hide it.

Private restricts entity access only in its defined scope, as well as extension access within the same file. If some of the details of the function only need to be used in the current scope, you can use private to hide it.

Open is the highest access level (least restricted) and private is the lowest access level (most restricted).

Open can only act on classes and members of classes. The main difference between open and public is that classes and members qualified by open can be inherited and rewritten outside the module.

Example:

Public class SomePublicClass {} internal class SomeInternalClass {} fileprivate class SomeFilePrivateClass {} private class SomePrivateClass {} class SomeInternalClass {} / implicit internalvar someInternalConstant = 0 / / implicit internalpublic class SomePublicClass {/ / explicit public class public var somePublicProperty = 0 / / explicit public class member var someInternalProperty = 0 / / implicit internal class member fileprivate func someFilePrivateMethod () {} / / explicit Type fileprivate class member private func somePrivateMethod () {} / explicit private class member} class SomeInternalClass {/ / implicit internal class var someInternalProperty = 0 / / implicit internal class member fileprivate func someFilePrivateMethod () {} / / explicit fileprivate class member private func somePrivateMethod () {} / / explicit private class member} Fileprivate class SomeFilePrivateClass {/ / explicit fileprivate class func someFilePrivateMethod () {} / / implicit fileprivate class member private func somePrivateMethod () {} / / explicit private class member} private class SomePrivateClass {/ / explicit private class func somePrivateMethod () {} / / implicit private class member} advanced operator

Swift also provides several advanced operators that can perform complex operations on numeric values. They contain bit operators and shift operators.

Bit operators, overflow operators, precedence and associativity, operator functions, custom operators

Example:

The value of let initialBits: UInt8 = 0b00001111let invertedBits = ~ initialBits / / equals 0b11110000var potentialOverflow = Int16.max// potentialOverflow is 32767 This is the maximum integer that Int16 can hold: potentialOverflow + = 1 return Vector2D / struct Vector2D {var x = 0.0, y = 0.0} extension Vector2D {static func + (left: Vector2D, right: Vector2D)-> Vector2D {return Vector2D (x: left.x + right.x, y: left.y + right.y)} let vector = Vector2D (x: 3.0,1.0) let anotherVector = Vector2D (x: 2.0) Y: 4) let combinedVector = vector + anotherVector// combinedVector is a new Vector2D instance The value is (5.0,5.0) so far, I believe you have a deeper understanding of "what is Swift syntax", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report