码迷,mamicode.com
首页 > 编程语言 > 详细

swift构造器_009-swift构造器

时间:2016-06-08 10:45:22      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

//: Playground - noun: a place where people can play

import UIKit

//----构造器-------
//构造器的作用:用于给类、结构体、枚举的实例进行初始化
//如果没有显式的定义构造器,则系统会自动生成一个
//结构体:生成一个逐一成员构造器
//类:生成一个无参的构造器,按照每个属性的初始值进行初始化

//1.类和结构体的默认构造器
struct Weather {
    
    
    var temp : Double

    init() {
        
        temp = 23
        
    }
    
    
}

var weather1 = Weather()
print(weather1.temp)

class Dog {
    let color:String = "White"
    var name:String = "旺财"
    var age:Int = 1
    
    
    
}

let dog = Dog()
print(dog.color)
print(dog.name)
print(dog.age)

//2.自定义构造器
struct City {
    
    var name : String?
    var location : String?
    var weather : Weather?
    
    init(name : String, location: String, weather : Weather) {
        
        self.name = name
        self.weather = weather
        self.location = location
    }
    
    //带外部参数名的init方法
    init(cityName name : String, _ location : String, wea weather : Weather) {
        
        self.name = name
        self.location = location
        self.weather = weather
    }
    
    
}

var city = City(cityName: "杭州", "Middle", wea: Weather())
print(city)

 

swift构造器_009-swift构造器

标签:

原文地址:http://www.cnblogs.com/foreveriOS/p/5569172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!