Swift学习日记003

类、方法、数组

类(Class)

 
  
class Person  {
 
  var firstName = ""
  var lastName = ""
  var age = 0
 
}

方法 (func)

func input() -> String {
  let keyboard = NSFileHandle.fileHandleWithStandardInput()
  let inputData = keyboard.availableData
  let rawString = NSString(data: inputData, encoding:NSUTF8StringEncoding)
  if let string = rawString {
    return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  } else {
    return "Invalid input"
  }
}

数组

// 这里people是Person类的对象

var people: [Person] = []

结合起来创建一个简单的个人信息输入输出工程,代码如下:

所需要的helper文件可以在上篇文章看到链接

首先创建一个swift对象(cmd+n\iOS\Source\Swift File),命名为Person

import Foundation

class Person  {
    
    //类的属性
    var firstName = ""
    var lastName = ""
    var age = 0
    
    //类方法 输入
    func input() -> String {
        let keyboard = NSFileHandle.fileHandleWithStandardInput()
        let inputData = keyboard.availableData
        let rawString = NSString(data: inputData, encoding:NSUTF8StringEncoding)
        if let string = rawString {
            return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        } else {
            return "Invalid input"
        }
    }

    //类方法 
    func changeFirstName(newFirstName:String) {
        firstName = newFirstName
    }

    //类方法
    func enterInfo()  {
        print("What is the first name?")
        firstName = input()
        print("What is \(firstName)'s last name?")
        lastName = input()
        print("How old is \(firstName) \(lastName)")
        let userInput = Int(input())
        if let number = userInput {
            age = number
        }
    }
    
//类方法
    func printInfo()  {
        print("First Name: \(firstName)")
        print("Last Name: \(lastName)")
        print("\(firstName) \(lastName) is \(age) years old")
    }
    
}



然后在main文件里面写主体代码:

import Foundation
//Repeat While Loop
var response: String

// 声明一个people数组并赋予空数组初值
var people:[Person] = []

//repeat...while 相当于之前的do..while,循环体会先执行一次
repeat {
    var newPerson = Person()
    newPerson.enterInfo()
    
    people.append(newPerson)
    
    newPerson.printInfo()
    
    print("Do you want to enter another name? (y/n)")
    response = input()
    
} while (response == "y")
//这个循环用于给数组添加Person对象,直到输入不是y为止

//数组个数
print("Number of people in db: \(people.count)")

//循环输出数组里面person对象信息
for onePerson in people{
    onePerson.printInfo()
}




你可能感兴趣的:(iOS学习,Swift)