如何在swift上阅读这三种类型的数据我想将这三个变量分配给标签。我该怎么做? [这是第一次,用swift编写,我是学习者,我是IOS移动开发的初学者]
student.swift
class Student{
let nubmers: [phone_number]?
let bday: DOB?
let gender: Gender?
init(numbers:[phone_number],bday:DOB, gender:Gender){
self.nubmers = []
self.bday = bday
self.gender = gender
}
}
enum Gender{
case Male
case Female
case Unspecific
}
phone_number.swift
import Foundation
struct phone_number {
var number:String!
}
DOB.dart
import Foundation
struct DOB {
let year:Int!
let month:Int!
let day:Int!
}
插入这样的数据?这是对的吗?
let student1 = Student(
numbers: [phone_number(number: "0773024962")],
bday: DOB(year:1996,month:01,day:13),
gender: Gender.Male)
我想读这样的//错误
func setStudent(student: Student){
label.text = numbers.number
label.text = student.bday
label.text = student.gender
}
如果您想参考第一个电话号码,那么您需要
label.text = student.numbers.first?.number
我可以建议其他一些改进:
Date
出生日期?PhoneNumber
Student
的类 - 你正在使用let
属性,所以你已经具有不变性。结构为您提供自动初始化生成struct Student {
let numbers: [String]
let bday: Date
let gender: Gender
}
enum Gender {
case male
case female
case unspecified
}
var dc = DateComponents()
dc.setValue(13, for: .day)
dc.setValue(1, for: .month)
dc.setValue(1996, for: .year)
dc.timeZone = TimeZone(secondsFromGMT: 0)
let dob = Calendar.autoupdatingCurrent.date(from: dc)!
// You could also use a DateFormatter to parse DOB from a string
let student1 = Student(numbers:["0773024962"], DOB:dob, gender:.male)