Swift4 基础部分: Nested Types(嵌套类型)

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

  • Swift4 基础部分:The Basics
  • Swift4 基础部分:Basic Operators
  • Swift4 基础部分:Strings and Characters
  • Swift4 基础部分:Collection Types
  • Swift4 基础部分:Control Flow
  • Swift4 基础部分:Functions
  • Swift4 基础部分:Closures
  • Swift4 基础部分: Enumerations
  • Swift4 基础部分: Classes and Structures
  • Swift4 基础部分: Properties
  • Swift4 基础部分: Methods
  • Swift4 基础部分: Subscripts
  • Swift4 基础部分: Inheritance
  • Swift4 基础部分: Initialization
  • Swift4 基础部分: Deinitialization
  • Swift4 基础部分: Automatic Reference Counting(自动引用计数)
  • Swift4 基础部分: Optional Chaining(可选链)
  • Swift4 基础部分: Error Handling(错误处理)
  • Swift4 基础部分: Type Casting(类型转换)
Enumerations are often created to support a specific class 
or structure’s functionality. Similarly, it can be 
convenient to define utility classes and structures purely 
for use within the context of a more complex type. To 
accomplish this, Swift enables you to define nested types, 
whereby you nest supporting enumerations, classes, and 
structures within the definition of the type they 
support.
  • Swift 允许你定义嵌套类型,可以在支持的类型中定义嵌套的枚举、类和结构体。

个人觉得枚举中嵌套类与结构体会让整个逻辑看上去很奇怪,相反结构体,类中嵌套其他类型的数据我觉得是合理的。下面举一个例子:

class Person {
    let name:String;
    let age:Int;
    let sex:Sex;
    let profession:Profession;
    let address:Address;
    
    enum Sex {
        case male,female
    }
    
    init(_ profession:Profession,_ address:Address,_ name:String, _ age:Int, _ sex:Sex) {
        self.profession = profession;
        self.address = address;
        self.name = name;
        self.age = age;
        self.sex = sex;
    }
    
    struct Profession {
        let professionName:String;
        let level:ProfessionLevel;
        
        enum ProfessionLevel {
            case High,Middle,Low
        }
        
        init(_ professionName:String,_ level:ProfessionLevel) {
            self.professionName = professionName;
            self.level = level;
        }
    }
    
    struct Address {
        let city:String;
        let street:String;
    }
    
    var description: String {
        var output = "\(self.name) is a \(self.age),";
        output += " profession is \(self.profession.professionName)(\(self.profession.level)),";
        output += " address is \(self.address.city) \(self.address.street)";
        return output
    }
}

var profession:Person.Profession = Person.Profession("engineer",Person.Profession.ProfessionLevel.High);
var address:Person.Address = Person.Address(city:"hubei-wuhan",street:"zhongshan road.");
var person:Person = Person(profession,address,"xz",18,Person.Sex.male);
print(person.description);

执行结果:

xz is a 18, profession is engineer(High), address is 
hubei-wuhan zhongshan road.

你可能感兴趣的:(Swift4 基础部分: Nested Types(嵌套类型))