Swift struct struct

Source: Internet
Author: User

Objective
    • A struct is a value type and is assigned only if it is given a variable or constant, or is called by a function.
1, the creation of the structure body
    • Structure BASIC structure

      struct 结构体名 {    var 或 let 字段名 = 初始化值    var 或 let 字段名: 类型}
      struct Student {    var age = 0}var stu = Student()/// struct      结构体关键字/// Student     结构体名称/// student()   创建一个结构体变量
1.1 Standard Definition
    • Definition of the structure body

      • When you define a struct field, you can define a field name directly and assign an initial value to the field name. Or simply define a field name, do not assign an initial value, but a field that does not assign an initial value must be assigned an initial value when creating a struct variable.

        struct Student {                                  var name: String                           // 只定义一个字段名,不赋初始值    var age = 0                                // 定义一个字段名,并且给字段名赋初始值}
    • Use of the structure body

      • When you create a struct variable, the fields of the struct must all have an initial value, or an error will be made.

        let s = Student(name: "appple", age: 8)        // 创建结构体变量时初始化结构体的字段print("\(s.name), \(s.age)")                   // 结构体类型变量值的调用
1.2 Basic Definitions
    • Definition of the structure body

      • Each field name is assigned an initial value.

        struct BookInfo {                                   var ID: Int = 0                            // 每个字段名都赋初始值    var Name: String = "Default"    var Author: String = "Default"    var RootType: String = "Default"}
    • Use of the structure body

      • When you create a struct variable, the fields of the struct must all have an initial value, or an error will be made.

        let book = BookInfo()                          // 创建结构体变量时不再需要初始化结构体的字段print("\(book.ID), \(book.Name), \(book.Author), \(book.RootType)")     // 结构体类型变量值的调用

Swift struct struct

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.