Swift面向对象之枚举

前端之家收集整理的这篇文章主要介绍了Swift面向对象之枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
//  main.swift
//  Swift面向对象之枚举
//
//  Created by Goddog on 15/7/17.
//  Copyright © 2015年 Goddog. All rights reserved.
//

import Foundation

print("Swift不仅是面向过程还是面向对象的,Swift可以定义枚举、结构体、类3种面向对象的类型,用枚举、结构体定义的变量属于值类型,用类定义的变量属于引用类型,3种面向对象都支持定义存储属性、计算属性方法、下标、构造器和嵌套类型")

print("Swift5种面向对象的程序单元:类、结构体、枚举、扩展、协议")

print("定义类型的步骤:1.声明变量;2.创建实例;3.访问属性;4.调用方法;5.派生子类(枚举和结构体不支持继承)")

//MARK: - 定义枚举
enum Season
{
    case Spring
    case Summer
    case Fall
    case Winter
}
//或
enum Weekday
{
    case Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}
//使用枚举声明变量
var day: Weekday
//使用已有枚举赋值
day = Weekday.Saturday
print("结果是:\(day)")

//MARK: - 枚举值和switch语句
var chooseDay = Weekday.Monday
switch chooseDay
{
    case .Monday:
        print("周一")
    case .Tuesday:
        print("周二")
    case .Wednesday:
        print("周三")
    case .Thursday:
        print("周四")
    case .Friday:
        print("周五")
    case .Saturday:
        print("周六")
    default:
        print("周日")
}

//MARK: - 原始值
//定义枚举,指定原始值为Int
enum Weekdays: Int
{
    case Monday,Tuesday = 1,Wednessday = 5,Sunnday
}
var days = Weekdays.Monday
print("Monday is : \(days.rawValue)")   //0是根据Tuesday=1自动判断的
days = .Friday
print("Friday is : \(days.rawValue)")   //7是根据Wednessday=5自动判断的

enum Seasons: Character
{
    //为每个枚举指定原始值
    case Spring = "s"
    case Summer = "u"
    case Fall = "f"
    case Winter = "w"
}

//根据原始值获取枚举
var getSeason = Seasons(rawValue: "s")
if getSeason != nil
{
    switch (getSeason!)
    {
    case .Spring:
        print("春")
    case .Summer:
        print("夏")
    case .Fall:
        print("秋")
    default:
        print("冬")
    }
}


//MARK: - 关联值
enum Planet
{
    //不同枚举可以携带数量不等,类型不等的关联值
    case Mercury(weight: Double,density: Double,name: String)
    case Venus(Double,Double)
    case Earth(Double,String)
    case Mars(density: Double,name:String)
    case Jupiter
    case Saturn
    case Uranus
    case Nepturn
}

var p1 = Planet.Mercury(weight: 0.05,density: 5.43,name: "水星")
var p2 = Planet.Venus(0.815,5.25)
var p3 = Planet.Earth(1.0,"地球")
var p4 = Planet.Mars(density: 3.95,name: "火星")

switch(p3)
{
    case Planet.Earth(var weight,var name):
        print("\(name),\(weight)")
    default:
        break
}

switch (p1)
{
    case let .Venus(weight,density):
        print("\(weight),\(density)")
    case let .Mercury(weight: w,density: d,name: n):
        print("\(w),\(d),\(n)")
    default:
        break
}









Swift不仅是面向过程还是面向对象的,Swift可以定义枚举、结构体、类3种面向对象的类型,用枚举、结构体定义的变量属于值类型,用类定义的变量属于引用类型,3种面向对象都支持定义存储属性、计算属性方法、下标、构造器和嵌套类型
Swift5种面向对象的程序单元:类、结构体、枚举、扩展、协议
定义类型的步骤:1.声明变量;2.创建实例;3.访问属性;4.调用方法;5.派生子类(枚举和结构体不支持继承)
结果是:Swift面向对象之一.Weekday.Saturday
周一
Monday is : 0
Friday is : 7
春
地球,1.0
0.05,5.43,水星
Program ended with exit code: 0
原文链接:https://www.f2er.com/swift/326581.html

猜你在找的Swift相关文章