Object-oriented general overview:
Swift is not only capable of process-oriented programming, but also object-oriented programming (OOP). Object-oriented is actually "taking the object as the core", thinking that our objective world is composed of one object, object-oriented programming provides properties and methods for the object, the property is to describe some state of the object, and the method is to tell you what the object should do. Object-oriented and core are "classes" and "Objects"! When I first touch programming, in fact I also very easy to confuse this thing, you want to also just touch programming, can help you, I think instead of time. You must be a bit difficult to understand, do not go to the dead, maybe tomorrow because of something you will suddenly realize. Super Like that feeling!
The three main features of object-oriented: Inheritance polymorphic encapsulation (encapsulation and inheritance good understanding, polymorphism I mentioned in the previous blog, do not understand can be turned to look at the front).
Swift object-oriented programming has five units: enum struct class extension protocol
From a functional perspective of the whole, Swift's enumeration, structure, and class are all of equal status. (We will make a distinction between these three) in other object-oriented programming languages, cavities provide a unit of class, and Swift has three, and you think, Oc,java and other languages are object-oriented programming, Swift is object-oriented and process can, Swift is a new language, It's only been available for two years, and OC is almost 30 years old. So Swift is not easy, and if Swift had just come out when someone wrote a println ("Hello World")(before 2.0) it was simple, you were really wrong. Swift is not simple, you say simply because you are only studying print ("Hello world")!
In swift, enumerations and struct-bodies are value types, and classes are reference types. The difference between a value type and a reference type, we say later, is to know this first.
In Swift's classes, structs, enumerations can be defined (attributes, methods, subscripts, constructs, nested types), below we have a small understanding of them, I will give you some I see a very good blog links, convenient for everyone to better grasp, understand swift!
One: Enumeration
Swift enumeration is used to manage a set of values, and of course it is limited. For example, you can use the enumeration to manage all year round, write a season enumeration, the value is (Spring and autumn), as well as gender (male and female), and then to our projects such as often see in the Instant Messenger message type (text, pictures, voice, system messages) and so on. For example, the following:
We are going to show you how we define enumerations in OC, and we compare them to understand:
/** sent message type */enum zxmessagetype:int {case messagetypeunknown = 0 //unknown case Messagetypesystem // System Case Messagetypetext //Text case messagetypeimage //Picture case Messagetypevoice //Voice Case Messagetypevideo// video case messagetypefile //File case messagetypelocation //Location Case Messagetypeshake //Jitter }
OC Enumeration
/** * Message type */typedef ns_enum (Nsinteger, Tlmessagetype) { messagetypeunknown, //Unknown Messagetypesystem ,// system Messagetypetext, //Text messagetypeimage, //Picture Messagetypevoice, //Voice Messagetypevideo,// video messagetypefile, //File messagetypelocation, //Location Messagetypeshake, //jitter};
By the way, the above two ways, is my own habit, in fact, according to the way we first learned to define no problem, but in the official definition, OC and Swift are the above examples of the way to write enumerations, so write is also good, have peer analysis, link here.
The difference between Swift enumeration and C,OC enumeration: Swift's enumeration member is not assigned a default integer value, and its enumeration name itself is a relationship between an enumerated instance and an integer value.
Swift's knowledge points are: The enumeration value and the switch statement original value correlation value and so on several aspects, but I did not say, said also does not have the predecessor summarizes the detail, I put the knowledge point to everybody, inside content enough grasps Swift's enumeration!
The enumeration in Swift, you should know something
Advanced usage and practice of enumeration in Swift
II: Classes and structures
Put these two together, purely because the two are so similar, we first listed the differences, the rest of the two are the same.
1: A struct is a value type, and a class is a reference type.
2: Structs do not support inheritance, type conversions are not supported. (Value type reason)
3: The struct does not support defining the destructor. (When the destructor is later said)
Insert says a question: the problem with instances and objects, in the previous OC, the object is an instance, and an instance is an object. But in Swift, when you remember to read a book, there are instances of classes that can be called objects, and instances of structs and enumerations can only be called instances, not objects. I think it should be related to the type of them, the main difference between them is actually around the value type and the reference type.
Look at the definition of the class:
Class Name:super Class { //code //constructor //attribute //method //Subscript }
Note the point:
1: When we do not provide a constructor for a struct/class, the system generates two constructors for the struct, one for the parameterless constructor, and one for the constructor that initializes all the stored properties. If you want the user-defined constructor to exist at the same time as the system-provided constructor, you cannot define the constructor directly in the class, and the extension can be used to add it.
The properties of 2:swift are divided into two categories, storing properties and computed properties, and storing properties similar to instance variables in OC, which are used to hold the state data of the type itself or the instance variable. The computed property is equivalent to the property attribute of the setter and getter synthesized in OC, and it does not necessarily save the data.
Three: Storing and Computing properties
(i) Storage properties
Swift defines the method of storing the property and defines its variable constants in the same way that we are not burdensome.
Storage properties can be divided into instance store attribute type store attribute two classes. This can be referred to OC instance methods and type methods, instance variables and type variables for the same reason to understand.
Note the point:
1: Enumerations cannot define instance store properties, classes and struct bodies can.
2:swift requires that all storage properties have an explicit initial value, either you specify the initial value when you define it, or you specify the initial value in the constructor.
3: If the type of the stored property is declared as an optional type, the system can set the initial value of these properties to nil (it must be noted that Swift's nil and OC Nil are completely different, Swift's nil is a definite value, called the missing value, And OC's nil is a pointer that does not point to any type.
For example, a model defined;
Class Zxuser:nsobject { var username:string = "" var userid:string = "" var nikename:string = "" var Avat arurl:string = " var motto:string =" " var phonenumber:string =" " var pinyin:string =" " var initial:st Ring = ""}
in the storage properties, we should note that this, the deferred storage attribute, the deferred storage attribute is the property of the initial value that is evaluated at the first call, and the lazy modifier is required to declare the deferred storage property.
The lazy loading that we use in OC is the delayed storage property, and we see a concrete example of this: like we lazy load this an array of type Zxmessagemodel, as follows:
Lazy var dataarray:array<zxmessagemodel> = { //weak reference prevents circular reference notation //[weak self] in //[unowned Self] in __weak typeof (self) wself = self let Dataarray:array = array<zxmessagemodel> () return dataarray< c9/>} ()
As for lazy loading why write like this, what are the benefits of looking at the links below!
The difference between Swift lazy loading (lazy) and objective-c lazy loading
(ii) Calculated attributes
The computed attribute can only be defined as a variable, and it can only be modified with Var.
the computed attribute is the same as our OC and Java properties (property properties) that are synthesized by setter and getter.
We often use a property attribute in OC, declare this attribute in. h, in. m we write its set or Get method, and then do something in their set or get method, see this example:
Return different values according to different criteria var cellheight:cgfloat{ get{ Switch self.messagetype! {Case Zxmessagetype (rawvalue:2)!: return self.messageSize.height + > self.messageSize.height + 40:60 Case Zxmessagetype (rawvalue:3)!: return self.messageSize.height +; Default: break } return 0 } }
Set different cellindentify var based on different message types messagetype:zxmessagetype?{ get{ return Self.messagetype } set { switch messagetype! {Case Zxmessagetype (rawvalue:2)!: self.cellindentify = "Textmessagecell"; Case Zxmessagetype (rawvalue:3)!: self.cellindentify = "Imagemessagecell"; Case Zxmessagetype (rawvalue:4)!: self.cellindentify = "Voicemessagecell"; Case Zxmessagetype (rawvalue:5)!: self.cellindentify = "Systemmessagecell"; Default: break } } }
Learning Links:
Swift Properties
Property attributes in Swift and OBJECTIVE-C
FOUR: Attribute Observer
Willset (NewValue): The method is called automatically before the property being observed is about to be assigned a value.
Didset (OldValue): The method is called automatically after the property being evaluated is completed.
The formal parameter names above are provided by Swift implicitly for them, and you can call them directly in the method, and deduct the words above to understand their definition and use;
var namestring = "" { willset{
Print ("Set value") } didset{
Print ("Did set Value") } }
Five: Methods
method Here we say a little, this feeling is very basic, the function method, said more also no meaning.
A method that uses static or class adornments belongs to a class method of that type, which can be invoked using the type itself. Class is typically decorated in classes, and static is typically used in structs and enumerations.
Six: Subscript
all Swift types (structs, enumerations, classes) support the definition of subscripts, which can be used as a simplified way to access objects, collections, or sequences.
Swift uses the Subscript keyword to define subscripts.
See the following example to see how it works:
struct Timestable {let multiplier:int subscript (index:int)->int { return multiplier * Index } } In another method such invocation, see output result let threetimestable = timestable (multiplier:3) print ("Sixtimes three is \ ( THREETIMESTABLE[6]) //Prints "six times three is 18"
Seven: Optional chain
all types of Swit cannot accept nil values by default, and if the program wants a data type to be able to accept nil values, the data type is packaged as an optional type:
1: Add after the original type? , this optional type must be forced to parse to get the wrapped value.
2: Add after the original type! , this optional type can have Swift's implicit parsing of the wrapped value.
In fact, you master the optional type of use, the optional chain is no difficulty, the following specific use of the following link is very clear:
Swift Optional Chain
VIII: Constructors
The constructor is used to complete the construction of the instance, which includes the initial values in the Society for each storage attribute in the instance and the necessary preparation and initialization tasks, unlike the OC constructor, where Swift's constructor does not have to explicitly declare the type of the return value, nor does it need to explicitly return an instance using return. The instance constructed by Swift's constructor is returned implicitly by the system. The essence of it is actually one or more functions called init.
concrete usage and the pit of the constructor here are
Nine: constructors that might fail
Sometimes, enumerations, structs, and classes may not be able to successfully return instances of that type, such as when you pass in a constructor parameter data that is invalid, and so on, you define a "constructor that might fail."
Could a failed constructor use init? or init!. To define, in this construct my execution body returns using return nil to represent a construction failure, and the constructor returns a nil (missing value).
Swift does not allow the definition of two constructors with the same form category, even if one is a constructor that might fail, and one is a normal constructor.
After the end of the case of object-oriented not finished, but also in the manufacturing, there is a wrong place to welcome correct, also can add my QQ. Discuss learning together
Swift Object-oriented parsing (i)