Guest User

Untitled

a guest
Jun 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. struct BookStruct {
  2. var title:String
  3. var author:String
  4. }// end dfine struct BookStruct
  5.  
  6. class BookClass {
  7. var title:String
  8. var author:String
  9.  
  10. init(title:String, author:String) {
  11. self.title = title
  12. self.author = author
  13. }// end init
  14. }// end class BookClass
  15.  
  16. func createBook(titlle:String, author:String) {
  17. var book1 = BookStruct(title: titlle, author: author)
  18. book1.title = "def" // OK
  19. let book1b = BookStruct(title: titlle, author: author)
  20. book1b.title = "def" // letで宣言したのに内容を変更しようとしているため、NG
  21. modifyTitle(book: book1, newTitle: "abc") // コメントbookStruct1のmofifyTitleが呼ばれる
  22. modifyTitle(book: &book1, newTitle: "abc") // コメントbookStruct2のmodifyTitleが呼ばれる
  23.  
  24. let book2 = BookClass(title: titlle, author: author)
  25. book2.title = "def" // OK
  26. modifyTitle(book: book2, newTitle: "def") // コメントbookClassのmodifyTitleが呼ばれる
  27.  
  28. }
  29.  
  30. // bookStruct 1
  31. func modifyTitle(book: BookStruct, newTitle:String) {
  32. book.title = newTitle // bookは、letでコピーされた値が渡されるので、変更しようとすると、NG
  33. }
  34.  
  35. // bookStruct 2
  36. func modifyTitle(book: inout BookStruct, newTitle:String) {
  37. book.title = newTitle // bookを受け取るときに inout宣言で値の参照を受け取っているので、 OK
  38. }
  39.  
  40. // bookClass
  41. func modifyTitle(book: BookClass, newTitle:String) {
  42. book.title = newTitle // book自体は値渡しだが、クラスのインスタンスなので、プロパティの変更は OK
  43. book = BookClass(title: "cde", author: "aaa") // book自体を書き替えようとするのは NG
  44. }
Add Comment
Please, Sign In to add comment