Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 10/10)

Swift

  • define struct
  • computed property
  • getter and setter
  • property observer: willSet, didSet
  • customize init function
importCocoa// ## Define structstructEmployee{letname:StringvarvacationRemaining:IntmutatingfunctakeVacation(days:Int){ifvacationRemaining>days{vacationRemaining-=daysprint("I'm going on vacation!")print("Days remaining:\(vacationRemaining)")}else{print("Oops! There aren't enough days remaining.")}}}// ## Computed Properties with getter and setterstructEmployee2{letname:StringvarvacationAllocated=14varvacationTaken=0varvacationRemaining:Int{// getterget{vacationAllocated-vacationTaken}// setter -> even we have a setter here, no `mutating` needs to be addedset{vacationAllocated=vacationTaken+newValue}}}// ## Property observers// willSet and didSetstructApp{varcontacts=[String](){// newValue and oldValue are built-in variable in observerswillSet{print("Current value is:\(contacts)")print("New value will be:\(newValue)")}didSet{print("There are now\(contacts.count) contacts.")print("Old value was\(oldValue)")}}}// ## custom initializers// explicitly define `init` function - no `func` needed, and you can use `self.`structPlayer{letname:Stringletnumber:Intinit(name:String){self.name=namenumber=Int.random(in:1...99)}}
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Coder, Learner
  • Location
    New York
  • Joined

More fromBC

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp