Swift Learning Notes-1. Basic section

Source: Internet
Author: User

Numeric type conversionsFloating-point type: If no explicitly specified type is float,swift, it is inferred as Double Integer ConversionsLet twothousand:uint16 = 2_000
Let One:uint8 = 1
Let twothousandandone:uint16 = Twothousand + UInt16 (one)conversion Format: A type (variable) is the default method that invokes the Swift constructor and passes in an initial value. There is a constructor in UInt16 that can accept a value of type UInt8, so the constructor can create a new UInt16 with the existing UInt8. Note that the value of any type can be passed in, and only the value of the corresponding constructor inside the UInt16 is entered. However, you can extend an existing type to allow it to accept other types of values, including custom types.   integer and floating-point conversionThe conversion of integers and floating-point numbers must explicitly specify the type: let three = 3
Let Pointonefouronefivenine = 0.14159
Let pi = Double (three) + PointonefouronefivenineThe reverse conversion is also possible, Let Integerpi = Int (PI)
type aliasesA type alias is one that defines another name for an existing type. You can use the Typealias keyword to define type aliases Typealias Audiosampe = UInt16

var maxamtlitudefound = Audiosampe.min Boolean valueBoolean type bool, True and False if you use a non-Boolean value where you want to use the Bool type, Swift will error let i = 1
If I {
Will error
}Correct usageLet i = 1
if i = = 1 {
Legal
}
Meta-grouptuples (tuples) synthesize multiple values into a composite value. Values within tuples can be any type and do not require the same typeLet Http404error = (404, "not Found")
You can combine any sequence of types into a tuple, tuples can contain all types, you can create a type (int, int, int) or (String, Bool) or other tuple you want. How to use(1) You can break down the contents of a tuple into separate constants and variables let (StatusCode, statusmessage) = Http404error (2) If you want only a subset of the tuple values, you can use the underline (_) to mark the Allow section to be omitted when decomposing ( Justthestatscode, _) = Http404error (3) You can also use subscripts to access individual elements in a tuple, with subscripts starting at 0 println (http404error.0)
println (Http404error.1)(4) You can name a single element when you define a tupleLet Http200status = (statuscode:200, description: "OK")(5) After naming the elements in a tuple, you can get the values of those elements by nameprintln (Http200status.statuscode)
println (http200status.description)
Tuples are useful when you return a value as a functionNote:tuples are useful when organizing values temporarily, but they are not suitable for wearing complex data structures. If you are not using it temporarily, use the class or struct body.     Optional TypeUse an optional type (optionals) to handle situations where the value may be missing. Optional type is expressed as: has a value, equals X or has no value Let Possiblenumber = "123"
Let Convertednumber = Possiblenumber.toint ()
The ToInt method returns an int of an optional type, and an optional int is written int? Rather than Int If statements and forced parsingYou can use the IF statement to determine whether an optional value is included. After you have determined that an optional type contains a value, you can add an exclamation point (!) after the optional name. ) to get the value. This is called forced parsing of optional values. if (convertednumber! = nil) {
println ("\ (possiblenumber) have an integer value fo \ (convertednumber!)")
} else {
println ("\ (Possiblenumber) could not being converted to an integer")
} NOTE: Use! To obtain an optional value that does not exist causes a run-time error. Use! To force a value to be resolved, make sure that the optional package contains a non-nil value Optional BindingsUse an optional binding to determine whether an optional type contains a value, or assign the value to a temporary constant or variable if it is included. An optional binding can be used in an if or while statement to determine the value of an optional type and assign a value to a constant or variable. If let Constantname = someoptional {
Statements
The above example can be written as: if let Actualnumber = Possiblenumber.toint () {
println ("\ (possiblenumber) have an integer value of \ (Actualnumber)")
} else {
println ("\ (Possiblenumber) could not being converted to an integer")
}you can use constants and variables in optional bindings. If you manipulate the value of Actualnumber in the first branch of the IF statement, you can change to if Var actualnumber so that the optional type contains values that are assigned to a variable rather than a variable. NilYou can assign a value of nil to an optional variable to indicate that it has no value: var serverresponsecode:int? = 404
Serverresponsecode = Nil Note: Nil cannot be used for non-optional constants and variables. If there are constants or variables that need to handle the actual value, declare them as the corresponding optional type. If you declare an optional constant or variable but are not assigned, will they automatically be set to Nil:var surveranswer:string? Nil in Swift and OC Nil are not the same. In OC, nil a pointer to an object that does not exist. In Swift, nil is not a pointer, he is a definite value used to denote a missing value. Any type can be set to nil, not just the object type. implicitly selectable typesAn optional type implies that a constant or variable can have no value. Optionally, the IF statement can be used to determine if there is a value, and if a value is available, the value can be resolved by an optional binding.at some point, after the first assignment, you can determine that an optional type always has a value. In this case, each judgment and resolution is very inefficient because it always has a value. This type of optional state is defined as an implicitly resolved optional type, (type!) For example: (string!)implicit parsing of optional types is useful when the above occurs. Primarily used in the construction of swift classes (referencing a cyclic strong reference between class instances) An implicit parsing optional type is actually a normal optional type, but can be used as a non-optional type, and does not require parsing to get an optional value each time.  the difference between an optional type and an implicitly resolved optional type: Let possiblestring:string? = "An optional string"
println (possiblestring!)

Let assumedstring:string! = "An implicity unwrapped optional string"
println (assumedstring)you can think of the implicit parsing optional type as an optional type that can be automatically parsed, all you have to do is put! At the end of the type, not at the end of the optional name at which each value is taken. Note:If you try to take a value when you implicitly parse an optional type without a value, a run-time error is triggered. And after the normal optional type with no value Added! is the same.   you can still determine whether an implicit parsing optional type is a normal optional type to see if it contains:if (assumedstring! = nil) {
println (assumedstring)
}
 You can also use an implicit optional type in an optional binding to examine and resolve its valueIf let definitestring = assumedstring {
println (definitestring)
}
 Note:If a variable may become nil after that, do not use implicit optional type, if you need to determine whether it is nil in the life cycle of the variable, use the normal pass optional type  AssertionAn optional type allows you to determine if a value exists, and you can handle the absence of a value in your code. However, in some cases, if the value is missing or the value does not meet a specific condition, your code may not need to proceed. At this point, you can trigger an assertion (assertion) in your code to end the code cloud and debug to find out why the value is missing.  using assertions for debuggingThe assertion determines whether a logical condition is true at run time. Use assertions to ensure that some important conditions have been met before running other code. If true, continue running, otherwise stop.  If your code triggers an assertion, you can clearly see where the illegal state occurs and check the status of your app when the assertion is started. Additionally, assertions allow you to attach a debug message.  you can write an assertion using the global assert function. An expression with a result of true or false is passed to the Assert function, and a message is displayed when false: Let Age =-3
ASSERT (age >= 0, "A person ' s cannot is less than zero") When age < 0 o'clock, the assertion is triggered to end the application  proper use of assertionsuse assertions when the condition may be false, but ultimately make sure that the condition is true so that your code can continue to run. usage Scenarios for assertions:
    • The subordinate script index of an integer is passed into a custom satellite script implementation, but the subscript index value may be too small or too large.
    • You need to pass in a value to the function, but an illegal value may cause the function to not work correctly.
    • An optional value is now nil, but a non-nil value is required for the subsequent code to run.
Note: Assertions can cause your app to stop running, so you should design your code carefully so that illegal conditions do not appear. However, there are times when illegal conditions may occur before your app is released, and using assertions can quickly identify problems.

Swift Learning Notes-1. Basic section

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.