Swift4 基礎(chǔ)部分: Nested Types(嵌套類型)

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點(diǎn)。

系列文章:

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 允許你定義嵌套類型,可以在支持的類型中定義嵌套的枚舉、類和結(jié)構(gòu)體。

個(gè)人覺得枚舉中嵌套類與結(jié)構(gòu)體會(huì)讓整個(gè)邏輯看上去很奇怪,相反結(jié)構(gòu)體,類中嵌套其他類型的數(shù)據(jù)我覺得是合理的。下面舉一個(gè)例子:

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);

執(zhí)行結(jié)果:

xz is a 18, profession is engineer(High), address is 
hubei-wuhan zhongshan road.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容