Structure 구조체

Lena·2021년 12월 30일
0
post-thumbnail
  • Defining the Structure

    struct MyStruct { }

    let name = "Lenaland"
    var citizens = ["Lena", "Jack"]
    var resources = ["Grain": 100, "Ore": 42, "Wool":75]
    // Properties : 이게 무엇인가!
    
    func fortify(){
        print("Defences increased!")
    }
    // Method : 뭘 할 수 있는가!
  • Initializing the Structure

    MyStruct()

    var myTown = Town()

    print(myTown.citizens)
    print("\(myTown.name) has \(myTown.resources["Grain"]!) bag of grain.")

    // 마을에서 새로운 시민이 생긴다면
    myTown.citizens.append("Selena")
    print(myTown.citizens.count)

    myTown.fortify()

["Lena", "Jack"]
Lenaland has 100 bag of grain.
3
Defences increased!


  • 문제풀이
func exercise() {

    // Define the User struct here
    
    struct User{
        let name: String
        let email: String?
        var followers: Int
        var isActive: Bool
        
       

        // Initialise a User struct here
        init(name: String, email: String?, followers: Int, isActive: Bool){
            self.name = name
            self.email = email
            self.followers = followers
            self.isActive = isActive
        }
        
         func logStatus(){
             if isActive == true{
                print("\(name) is working hard")
             } else{
                 print("\(name) has left earth")
             }
         }
    }
        
    let user = User(name: "Richard", email: " ", followers: 0, isActive: false)
    user.logStatus()


    print("\nDiagnostic code (i.e., Challenge Hint):")
    var musk = User(name: "Elon", email: "elon@tesla.com", followers: 2001, isActive: true)
    musk.logStatus()
    print("Contacting \(musk.name) on \(musk.email!) ...")
    print("\(musk.name) has \(musk.followers) followers")
    // sometime later
    musk.isActive = false
    musk.logStatus()
}

0개의 댓글