Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct BookStruct {
- var title:String
- var author:String
- }// end dfine struct BookStruct
- class BookClass {
- var title:String
- var author:String
- init(title:String, author:String) {
- self.title = title
- self.author = author
- }// end init
- }// end class BookClass
- func createBook(titlle:String, author:String) {
- var book1 = BookStruct(title: titlle, author: author)
- book1.title = "def" // OK
- let book1b = BookStruct(title: titlle, author: author)
- book1b.title = "def" // letで宣言したのに内容を変更しようとしているため、NG
- modifyTitle(book: book1, newTitle: "abc") // コメントbookStruct1のmofifyTitleが呼ばれる
- modifyTitle(book: &book1, newTitle: "abc") // コメントbookStruct2のmodifyTitleが呼ばれる
- let book2 = BookClass(title: titlle, author: author)
- book2.title = "def" // OK
- modifyTitle(book: book2, newTitle: "def") // コメントbookClassのmodifyTitleが呼ばれる
- }
- // bookStruct 1
- func modifyTitle(book: BookStruct, newTitle:String) {
- book.title = newTitle // bookは、letでコピーされた値が渡されるので、変更しようとすると、NG
- }
- // bookStruct 2
- func modifyTitle(book: inout BookStruct, newTitle:String) {
- book.title = newTitle // bookを受け取るときに inout宣言で値の参照を受け取っているので、 OK
- }
- // bookClass
- func modifyTitle(book: BookClass, newTitle:String) {
- book.title = newTitle // book自体は値渡しだが、クラスのインスタンスなので、プロパティの変更は OK
- book = BookClass(title: "cde", author: "aaa") // book自体を書き替えようとするのは NG
- }
Add Comment
Please, Sign In to add comment