{"appState":{"pageLoadApiCallsStatus":true},"categoryState":{"relatedCategories":{"headers":{"timestamp":"2025-04-17T16:01:06+00:00"},"categoryId":33594,"data":{"title":"App Development","slug":"app-development","image":{"src":null,"width":0,"height":0},"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"parentCategory":{"categoryId":33592,"title":"Programming & Web Design","slug":"programming-web-design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"}},"childCategories":[],"description":"Facebooks and Instas and Tiktoks, oh my. Check out our articles on how ideas become world-famous apps.","relatedArticles":{"self":"https://dummies-api.dummies.com/v2/articles?category=33594&offset=0&size=5"},"hasArticle":true,"hasBook":true,"articleCount":85,"bookCount":6},"_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"relatedCategoriesLoadedStatus":"success"},"listState":{"list":{"count":10,"total":85,"items":[{"headers":{"creationTime":"2020-10-28T17:58:33+00:00","modifiedTime":"2022-08-10T16:49:12+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"9 SwiftUI Tips and Tricks","strippedTitle":"9 swiftui tips and tricks","slug":"9-swiftui-tips-and-tricks","canonicalUrl":"","seo":{"metaDescription":"Want to improve your SwiftUI skills? We've got you covered! Give these nine tips and tricks a try to level up your developing.","noIndex":0,"noFollow":0},"content":"<a href=\"https://www.dummies.com/programming/macintosh/a-brief-primer-on-swift-programming-basic-syntax/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a> makes creating your iOS applications easy and efficient. However, there are neat tricks that are not so obvious. Here, you learn some of these tips and tricks so that you can become a better SwiftUI developer.\r\n<h2 id=\"tab1\" ><a name=\"_Toc37583247\"></a>Resume SwiftUI’s live preview</h2>\r\nMy number-one pet peeve about SwiftUI is that the live preview feature in <a href=\"https://www.dummies.com/web-design-development/mobile-apps/using-xcode-to-develop-an-app/\" target=\"_blank\" rel=\"noopener\">Xcode</a> doesn’t always work. Very often, changes made to your code will cause the automatic previewing feature to pause. Even though your code is perfectly correct and there is no error, the live preview just can’t seem to update automatically.\r\n\r\nOf course, you could click the Resume button to update the preview, but you waste precious time moving your mouse to click the button.\r\n<p class=\"article-tips tip\">A better way is to press ⌘+Option+P. This causes the live preview to resume and update itself. Now that you know this trick, there is no reason to click the Resume button anymore!</p>\r\nYou may also want to check out the <a href=\"https://developer.apple.com/library/archive/documentation/IDEs/Conceptual/xcode_help-command_shortcuts/MenuCommands/MenuCommands014.html.\" target=\"_blank\" rel=\"noopener\">list of shortcuts for working in Xcode</a>.\r\n<h2 id=\"tab2\" ><a name=\"_Toc37583249\"></a>Combine text views in SwiftUI</h2>\r\nHere is a neat little trick that you should know if you want to display the various words in a sentence in different colors and sizes. Instead of using the <code>HStack</code> view to group various <code>Text</code> views together, you can simply use the plus (<strong>+</strong>) operator to add different <code>Text</code> views together, like this:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Text(\"Red \")\r\n .foregroundColor(.red)\r\n .font(.largeTitle)\r\n +\r\n Text(\"Green \")\r\n .foregroundColor(.green)\r\n .font(.body)\r\n +\r\n Text(\"Blue\")\r\n .foregroundColor(.blue)\r\n .font(.title)\r\n }\r\n}</pre>\r\nHow cool is that? Here’s the output.\r\n\r\n[caption id=\"attachment_274193\" align=\"aligncenter\" width=\"125\"]<img class=\"wp-image-274193 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-text-views-125x255.jpg\" alt=\"SwiftUI Text views\" width=\"125\" height=\"255\" /> Concatenating different Text views together.[/caption]\r\n\r\n \r\n\r\nIf you want all the texts to be of the same font size, group them together using a <code>Group</code> view and apply the <code>font()</code> modifier on the <code>Group</code> view:\r\n<pre class=\"code\">struct ContentView: View {\r\n \r\n var body: some View {\r\n Group {\r\n Text(\"Red \")\r\n .foregroundColor(.red)\r\n +\r\n Text(\"Green \")\r\n .foregroundColor(.green)\r\n +\r\n Text(\"Blue\")\r\n .foregroundColor(.blue)\r\n }\r\n .font(.largeTitle)\r\n }\r\n}</pre>\r\n<h2 id=\"tab3\" ><a name=\"_Toc37583250\"></a>Create custom modifiers in SwiftUI</h2>\r\nSwift modifiers allow you to change the behaviors of views. Consider the following example:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2)\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2) \r\n }\r\n }\r\n}</pre>\r\nHere, you apply the same set of modifiers to the two <code>Text</code> views. You often do that when you want to ensure consistencies in your UI (for example, applying the same set of UI styles when displaying certain information in your application). Instead of repeating the same set of modifiers again and again, wouldn’t it be easier if you could just encapsulate all the modifiers into yet another modifier?\r\n\r\nWhat you can do it is create another struct that conforms to the <code>ViewModifier</code> protocol. This protocol requires you to implement a <code>body() </code>method that has a <code>Content </code>parameter. You then apply whatever modifiers you want to this <code>Content</code> argument and return it:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct Title: ViewModifier {\r\n func body(content: Content) -&gt; some View {\r\n content\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2)\r\n }\r\n}</pre>\r\nTo use the newly created <code>Title</code> struct on the <code>Text</code> view, apply the<code> modifier() </code>modifier and pass in the <code>Title</code> struct, like this:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .modifier(Title())\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .modifier(Title())\r\n }\r\n }\r\n}</pre>\r\nTo make the <code>Title</code> struct look more like a true modifier, create an extension to the <code>View</code> protocol and give it a name — say,<code> titleStyle</code>:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nextension View {\r\n func titleStyle() -&gt; some View {\r\n self.modifier(Title())\r\n }\r\n}</pre>\r\nYou can now apply the <code>titleStyle()</code> modifier to the two<code> Text</code> views:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .titleStyle()\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .titleStyle()\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc37583251\"></a>Display multiple alerts in SwiftUI</h2>\r\nUsually, in SwiftUI you apply a single <code>alert()</code> modifier to a single view. For example, when the user taps a button, you can display an alert by using the <code>alert()</code> modifier to the button. If you have multiple buttons, you can attach an <code>alert()</code> modifier to each button.\r\n\r\nHowever, there are times when you need to display multiple different alerts for a single view. Applying multiple <code>alert()</code> modifiers to a single view will not work correctly, because the last modifier will override the earlier ones. To solve this problem, you can use a single<code> alert()</code> modifier, and use a<code> switch </code>statement within the modifier to decide which alert to display.\r\n\r\nThe following example shows a button that, when it’s clicked, generates a random number of either 1 or 2 and uses it to decide which alert to display:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var displayAlert = false\r\n @State private var alertToDisplay = 0\r\n \r\n var body: some View {\r\n Button(action: {\r\n self.alertToDisplay = Int.random(in: 1..&lt;3)\r\n self.displayAlert = true\r\n }) {\r\n Text(\"Display Alert\")\r\n }\r\n .alert(isPresented: $displayAlert) {\r\n switch alertToDisplay {\r\n case 1:\r\n return Alert(title: Text(\"Alert 1\"),\r\n message: Text(\"This is Alert 1\"))\r\n default:\r\n return Alert(title: Text(\"Alert 2\"),\r\n message: Text(\"This is Alert 2\"))\r\n }\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab5\" ><a name=\"_Toc37583252\"></a>Enable debug preview in SwiftUI</h2>\r\nBy default, the preview canvas doesn’t display outputs printed using the <code>print()</code> function. This isn’t useful, however, because often you want to use the<code> print()</code> function as a quick debugging option. The good news is, you can easily fix this.\r\n\r\nIn the preview canvas, right-click the Play button and select Debug Preview.\r\n\r\n[caption id=\"attachment_274194\" align=\"aligncenter\" width=\"181\"]<img class=\"wp-image-274194 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-debug-preview-181x255.jpg\" alt=\"SwiftUI debug preview\" width=\"181\" height=\"255\" /> Enabling the Debug Preview feature in the preview canvas.[/caption]\r\n\r\n \r\n\r\nNow if you tap the button, your code will print the output in the Output window:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Button (\"Tap Me\") {\r\n print(\"Button was tapped...\")\r\n }\r\n }\r\n}</pre>\r\nIf the Output window is not shown in Xcode, press ⌘+Shift+C and it should appear.\r\n<h2 id=\"tab6\" ><a name=\"_Toc37583253\"></a>Preview your SwiftUI app using different devices</h2>\r\nYou’re familiar with using the preview canvas to preview your app. By default, Xcode automatically picks an appropriate device based on your target.\r\n\r\n[caption id=\"attachment_274195\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274195 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-target-set.jpg\" alt=\"SwiftUI target set\" width=\"556\" height=\"67\" /> The target set for your project (iPhone 11 Pro Max, in this example).[/caption]\r\n\r\n \r\n\r\nYou can preview your app on different modes — light mode and dark mode — using the <code>environment() </code>modifier:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n Group {\r\n ContentView()\r\n .environment(\\.colorScheme, .light)\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n }\r\n}</pre>\r\nIn addition to previewing in different modes, you can alter the size of the preview window, allowing you to have a glimpse of how your UI will look under different screen dimensions. You can do so using the<code> previewLayout() </code>modifier:\r\n<pre class=\"code\">static var previews: some View {\r\n Group {\r\n ContentView()\r\n .environment(\\.colorScheme, .light)\r\n .previewLayout((.fixed(width: 400, \r\n height: 600)))\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n }</pre>\r\nThe image below shows the top preview displaying your UI in a dimension of 400 x 600 pixels. Note that clicking the Live Preview button will revert the preview back to the default size.\r\n\r\n[caption id=\"attachment_274196\" align=\"aligncenter\" width=\"197\"]<img class=\"wp-image-274196 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-preview-app-197x586.jpg\" alt=\"SwiftUI app preview\" width=\"197\" height=\"586\" /> Previewing your app in the specified dimensions.[/caption]\r\n\r\n \r\n\r\nIf you want to preview your UI on multiple devices, you can use a <code>ForEach</code> loop, supply a list of device names, and then use the<code> previewDevice()</code> modifier on the<code> ContentView</code>, like this:\r\n<pre class=\"code\"> static var previews: some View {\r\n ForEach([\"iPhone 11\", \"iPhone SE\"], \r\n id: \\.self) { deviceName in\r\n ContentView()\r\n .environment(\\.colorScheme, \r\n .light)\r\n .previewDevice(PreviewDevice(\r\n rawValue: deviceName))\r\n .previewDisplayName(deviceName)\r\n }\r\n }</pre>\r\nThe following image shows the preview on the iPhone 11 and the iPhone SE. Notice that you can display the name of the device using the <code>previewDisplayName()</code> modifier.\r\n\r\n[caption id=\"attachment_274197\" align=\"aligncenter\" width=\"174\"]<img class=\"wp-image-274197 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-preview-174x586.jpg\" alt=\"preview app in SwiftUI\" width=\"174\" height=\"586\" /> Previewing the app on an iPhone 11 and an iPhone SE.[/caption]\r\n\r\n \r\n\r\nCheck out the <a href=\"https://developer.apple.com/documentation/swiftui/list/3270295-previewdevice\" target=\"_blank\" rel=\"noopener\">full list of devices that you can preview</a>.\r\n<h2 id=\"tab7\" ><a name=\"_Toc37583254\"></a>Dark mode only works on NavigationView</h2>\r\nAs stated, you can use the environment() modifier to set the preview to dark mode so that you can see how your UI will look like in dark mode.\r\n\r\nHowever, it seems like the dark preview mode only works for the <code>NavigationView</code>. For example, consider the following example where you have two <code>Text</code> views contained within a <code>VStack </code>view:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n Text(\"Vincent van Gogh\")\r\n }\r\n }\r\n}</pre>\r\nSuppose you use the <code>environment()</code> modifier to set the preview mode to<code> dark</code>, like this:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n}</pre>\r\nThe words in the <code>Text</code> views automatically change to white, but the background remains white (running on the simulator or an actual device doesn’t have this issue), as shown below. So, essentially, you get a white screen.\r\n\r\n[caption id=\"attachment_274198\" align=\"aligncenter\" width=\"137\"]<img class=\"wp-image-274198 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-dark-mode-137x255.jpg\" alt=\"SwiftUI dark mode\" width=\"137\" height=\"255\" /> Previewing in dark mode but the background of the app is still white.[/caption]\r\n\r\n \r\n\r\nTo fix this problem, wrap the <code>ContentView</code> view using a <code>ZStack</code> and set its background to black, like this:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n ZStack {\r\n Color(.black)\r\n ContentView()\r\n }\r\n .edgesIgnoringSafeArea(.all)\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n}</pre>\r\nThe image below shows the text showing up on a black background.\r\n\r\n[caption id=\"attachment_274199\" align=\"aligncenter\" width=\"138\"]<img class=\"wp-image-274199 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-dark-mode-138x255.jpg\" alt=\"SwiftUI dark mode\" width=\"138\" height=\"255\" /> You can now preview the dark mode correctly.[/caption]\r\n\r\n \r\n<h2 id=\"tab8\" ><a name=\"_Toc37583256\"></a>Extract subviews in SwiftUI</h2>\r\nYour UI may contain quite a large number of views. This is very common if you have a complicated UI. However, you can simplify your UI by extracting some of the views as subviews. Consider the following example:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n Image(\"weimenglee\")\r\n .resizable()\r\n .frame(width: CGFloat(120),\r\n height: CGFloat(120))\r\n .cornerRadius(CGFloat(15),\r\n antialiased: true)\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n }\r\n}</pre>\r\nTo break down the UI into smaller subviews so that your UI is more modular and manageable, follow these steps:\r\n<ol>\r\n \t<li>In the preview canvas, select the <code>Image</code> view and press the ⌘ key.\r\n\r\n[caption id=\"attachment_274200\" align=\"aligncenter\" width=\"247\"]<img class=\"wp-image-274200 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-subviews-247x255.jpg\" alt=\"SwiftUI subviews\" width=\"247\" height=\"255\" /> Extracting views as subviews in the preview canvas.[/caption]</li>\r\n \t<li>Select Extract Subview.</li>\r\n \t<li>Name the new view PhotoView.</li>\r\n</ol>\r\n[caption id=\"attachment_274201\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274201 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-name-subview.jpg\" alt=\"name subview SwiftUI\" width=\"556\" height=\"373\" /> Naming the newly extracted subview.[/caption]\r\n\r\n \r\n\r\nThe<code> Image</code> view will now be extracted as a new struct named PhotoView:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n PhotoView()\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n }\r\n}\r\n\r\nstruct PhotoView: View {\r\n var body: some View {\r\n Image(\"weimenglee\")\r\n .resizable()\r\n .frame(width: CGFloat(120),\r\n height: CGFloat(120))\r\n .cornerRadius(CGFloat(15),\r\n antialiased: true)\r\n }\r\n}</pre>\r\nYou can now also extract the<code> VStack</code> and save it as another struct named <code>DetailsView</code>. Now your UI looks like the following, which is more maintainable:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n PhotoView()\r\n DetailsView()\r\n }\r\n }\r\n}\r\n\r\nstruct PhotoView: View {\r\n...\r\n}\r\n\r\nstruct DetailsView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab9\" ><a name=\"_Toc37583257\"></a>Display a context menu in SwiftUI</h2>\r\nOne of the innovative features of iPhone is the support for Haptic Touch (which replaces the 3D Touch on older iPhones). Using Haptic Touch, you can long-press an item on your iPhone and a context-sensitive menu appears (if the app you’re using supports it). You can support this feature in SwiftUI as well.\r\n\r\nTo attach a context menu to a view, use the<code> contextMenu()</code> modifier:\r\n\r\nTo attach a context menu to a view, use the contextMenu() modifier:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Image(\"Mac Pro\")\r\n .resizable()\r\n .frame(width: 300, height: 280)\r\n .contextMenu {\r\n Button(action: {\r\n print(\"Save Image button tapped...\")\r\n }) {\r\n Text(\"Save Image\")\r\n Image(systemName: \r\n \"tray.and.arrow.down\")\r\n }\r\n Button(action: {\r\n print(\"Add to Cart button tapped...\")\r\n }) {\r\n Text(\"Add to Cart\")\r\n Image(systemName: \"plus\")\r\n }\r\n }\r\n }\r\n}</pre>\r\nTo create a context menu, you provide a list of<code> Button</code> views, and the content of each button is automatically wrapped using an <code>HStack</code> view. Now when you long-press the <code>Image</code> view, a context menu appears.\r\n\r\n[caption id=\"attachment_274202\" align=\"aligncenter\" width=\"244\"]<img class=\"wp-image-274202 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-image-view-244x255.jpg\" alt=\"SwiftUI Image view\" width=\"244\" height=\"255\" /> Implementing a context menu on an Image view.[/caption]\r\n\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwifUI Cheat Sheet</a>.","description":"<a href=\"https://www.dummies.com/programming/macintosh/a-brief-primer-on-swift-programming-basic-syntax/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a> makes creating your iOS applications easy and efficient. However, there are neat tricks that are not so obvious. Here, you learn some of these tips and tricks so that you can become a better SwiftUI developer.\r\n<h2 id=\"tab1\" ><a name=\"_Toc37583247\"></a>Resume SwiftUI’s live preview</h2>\r\nMy number-one pet peeve about SwiftUI is that the live preview feature in <a href=\"https://www.dummies.com/web-design-development/mobile-apps/using-xcode-to-develop-an-app/\" target=\"_blank\" rel=\"noopener\">Xcode</a> doesn’t always work. Very often, changes made to your code will cause the automatic previewing feature to pause. Even though your code is perfectly correct and there is no error, the live preview just can’t seem to update automatically.\r\n\r\nOf course, you could click the Resume button to update the preview, but you waste precious time moving your mouse to click the button.\r\n<p class=\"article-tips tip\">A better way is to press ⌘+Option+P. This causes the live preview to resume and update itself. Now that you know this trick, there is no reason to click the Resume button anymore!</p>\r\nYou may also want to check out the <a href=\"https://developer.apple.com/library/archive/documentation/IDEs/Conceptual/xcode_help-command_shortcuts/MenuCommands/MenuCommands014.html.\" target=\"_blank\" rel=\"noopener\">list of shortcuts for working in Xcode</a>.\r\n<h2 id=\"tab2\" ><a name=\"_Toc37583249\"></a>Combine text views in SwiftUI</h2>\r\nHere is a neat little trick that you should know if you want to display the various words in a sentence in different colors and sizes. Instead of using the <code>HStack</code> view to group various <code>Text</code> views together, you can simply use the plus (<strong>+</strong>) operator to add different <code>Text</code> views together, like this:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Text(\"Red \")\r\n .foregroundColor(.red)\r\n .font(.largeTitle)\r\n +\r\n Text(\"Green \")\r\n .foregroundColor(.green)\r\n .font(.body)\r\n +\r\n Text(\"Blue\")\r\n .foregroundColor(.blue)\r\n .font(.title)\r\n }\r\n}</pre>\r\nHow cool is that? Here’s the output.\r\n\r\n[caption id=\"attachment_274193\" align=\"aligncenter\" width=\"125\"]<img class=\"wp-image-274193 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-text-views-125x255.jpg\" alt=\"SwiftUI Text views\" width=\"125\" height=\"255\" /> Concatenating different Text views together.[/caption]\r\n\r\n \r\n\r\nIf you want all the texts to be of the same font size, group them together using a <code>Group</code> view and apply the <code>font()</code> modifier on the <code>Group</code> view:\r\n<pre class=\"code\">struct ContentView: View {\r\n \r\n var body: some View {\r\n Group {\r\n Text(\"Red \")\r\n .foregroundColor(.red)\r\n +\r\n Text(\"Green \")\r\n .foregroundColor(.green)\r\n +\r\n Text(\"Blue\")\r\n .foregroundColor(.blue)\r\n }\r\n .font(.largeTitle)\r\n }\r\n}</pre>\r\n<h2 id=\"tab3\" ><a name=\"_Toc37583250\"></a>Create custom modifiers in SwiftUI</h2>\r\nSwift modifiers allow you to change the behaviors of views. Consider the following example:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2)\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2) \r\n }\r\n }\r\n}</pre>\r\nHere, you apply the same set of modifiers to the two <code>Text</code> views. You often do that when you want to ensure consistencies in your UI (for example, applying the same set of UI styles when displaying certain information in your application). Instead of repeating the same set of modifiers again and again, wouldn’t it be easier if you could just encapsulate all the modifiers into yet another modifier?\r\n\r\nWhat you can do it is create another struct that conforms to the <code>ViewModifier</code> protocol. This protocol requires you to implement a <code>body() </code>method that has a <code>Content </code>parameter. You then apply whatever modifiers you want to this <code>Content</code> argument and return it:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct Title: ViewModifier {\r\n func body(content: Content) -&gt; some View {\r\n content\r\n .font(.largeTitle)\r\n .foregroundColor(.blue)\r\n .shadow(radius: 2)\r\n }\r\n}</pre>\r\nTo use the newly created <code>Title</code> struct on the <code>Text</code> view, apply the<code> modifier() </code>modifier and pass in the <code>Title</code> struct, like this:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .modifier(Title())\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .modifier(Title())\r\n }\r\n }\r\n}</pre>\r\nTo make the <code>Title</code> struct look more like a true modifier, create an extension to the <code>View</code> protocol and give it a name — say,<code> titleStyle</code>:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nextension View {\r\n func titleStyle() -&gt; some View {\r\n self.modifier(Title())\r\n }\r\n}</pre>\r\nYou can now apply the <code>titleStyle()</code> modifier to the two<code> Text</code> views:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n .bold()\r\n .titleStyle()\r\n \r\n Text(\"Vincent van Gogh\")\r\n .bold()\r\n .titleStyle()\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc37583251\"></a>Display multiple alerts in SwiftUI</h2>\r\nUsually, in SwiftUI you apply a single <code>alert()</code> modifier to a single view. For example, when the user taps a button, you can display an alert by using the <code>alert()</code> modifier to the button. If you have multiple buttons, you can attach an <code>alert()</code> modifier to each button.\r\n\r\nHowever, there are times when you need to display multiple different alerts for a single view. Applying multiple <code>alert()</code> modifiers to a single view will not work correctly, because the last modifier will override the earlier ones. To solve this problem, you can use a single<code> alert()</code> modifier, and use a<code> switch </code>statement within the modifier to decide which alert to display.\r\n\r\nThe following example shows a button that, when it’s clicked, generates a random number of either 1 or 2 and uses it to decide which alert to display:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var displayAlert = false\r\n @State private var alertToDisplay = 0\r\n \r\n var body: some View {\r\n Button(action: {\r\n self.alertToDisplay = Int.random(in: 1..&lt;3)\r\n self.displayAlert = true\r\n }) {\r\n Text(\"Display Alert\")\r\n }\r\n .alert(isPresented: $displayAlert) {\r\n switch alertToDisplay {\r\n case 1:\r\n return Alert(title: Text(\"Alert 1\"),\r\n message: Text(\"This is Alert 1\"))\r\n default:\r\n return Alert(title: Text(\"Alert 2\"),\r\n message: Text(\"This is Alert 2\"))\r\n }\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab5\" ><a name=\"_Toc37583252\"></a>Enable debug preview in SwiftUI</h2>\r\nBy default, the preview canvas doesn’t display outputs printed using the <code>print()</code> function. This isn’t useful, however, because often you want to use the<code> print()</code> function as a quick debugging option. The good news is, you can easily fix this.\r\n\r\nIn the preview canvas, right-click the Play button and select Debug Preview.\r\n\r\n[caption id=\"attachment_274194\" align=\"aligncenter\" width=\"181\"]<img class=\"wp-image-274194 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-debug-preview-181x255.jpg\" alt=\"SwiftUI debug preview\" width=\"181\" height=\"255\" /> Enabling the Debug Preview feature in the preview canvas.[/caption]\r\n\r\n \r\n\r\nNow if you tap the button, your code will print the output in the Output window:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Button (\"Tap Me\") {\r\n print(\"Button was tapped...\")\r\n }\r\n }\r\n}</pre>\r\nIf the Output window is not shown in Xcode, press ⌘+Shift+C and it should appear.\r\n<h2 id=\"tab6\" ><a name=\"_Toc37583253\"></a>Preview your SwiftUI app using different devices</h2>\r\nYou’re familiar with using the preview canvas to preview your app. By default, Xcode automatically picks an appropriate device based on your target.\r\n\r\n[caption id=\"attachment_274195\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274195 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-target-set.jpg\" alt=\"SwiftUI target set\" width=\"556\" height=\"67\" /> The target set for your project (iPhone 11 Pro Max, in this example).[/caption]\r\n\r\n \r\n\r\nYou can preview your app on different modes — light mode and dark mode — using the <code>environment() </code>modifier:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n Group {\r\n ContentView()\r\n .environment(\\.colorScheme, .light)\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n }\r\n}</pre>\r\nIn addition to previewing in different modes, you can alter the size of the preview window, allowing you to have a glimpse of how your UI will look under different screen dimensions. You can do so using the<code> previewLayout() </code>modifier:\r\n<pre class=\"code\">static var previews: some View {\r\n Group {\r\n ContentView()\r\n .environment(\\.colorScheme, .light)\r\n .previewLayout((.fixed(width: 400, \r\n height: 600)))\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n }</pre>\r\nThe image below shows the top preview displaying your UI in a dimension of 400 x 600 pixels. Note that clicking the Live Preview button will revert the preview back to the default size.\r\n\r\n[caption id=\"attachment_274196\" align=\"aligncenter\" width=\"197\"]<img class=\"wp-image-274196 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-preview-app-197x586.jpg\" alt=\"SwiftUI app preview\" width=\"197\" height=\"586\" /> Previewing your app in the specified dimensions.[/caption]\r\n\r\n \r\n\r\nIf you want to preview your UI on multiple devices, you can use a <code>ForEach</code> loop, supply a list of device names, and then use the<code> previewDevice()</code> modifier on the<code> ContentView</code>, like this:\r\n<pre class=\"code\"> static var previews: some View {\r\n ForEach([\"iPhone 11\", \"iPhone SE\"], \r\n id: \\.self) { deviceName in\r\n ContentView()\r\n .environment(\\.colorScheme, \r\n .light)\r\n .previewDevice(PreviewDevice(\r\n rawValue: deviceName))\r\n .previewDisplayName(deviceName)\r\n }\r\n }</pre>\r\nThe following image shows the preview on the iPhone 11 and the iPhone SE. Notice that you can display the name of the device using the <code>previewDisplayName()</code> modifier.\r\n\r\n[caption id=\"attachment_274197\" align=\"aligncenter\" width=\"174\"]<img class=\"wp-image-274197 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-preview-174x586.jpg\" alt=\"preview app in SwiftUI\" width=\"174\" height=\"586\" /> Previewing the app on an iPhone 11 and an iPhone SE.[/caption]\r\n\r\n \r\n\r\nCheck out the <a href=\"https://developer.apple.com/documentation/swiftui/list/3270295-previewdevice\" target=\"_blank\" rel=\"noopener\">full list of devices that you can preview</a>.\r\n<h2 id=\"tab7\" ><a name=\"_Toc37583254\"></a>Dark mode only works on NavigationView</h2>\r\nAs stated, you can use the environment() modifier to set the preview to dark mode so that you can see how your UI will look like in dark mode.\r\n\r\nHowever, it seems like the dark preview mode only works for the <code>NavigationView</code>. For example, consider the following example where you have two <code>Text</code> views contained within a <code>VStack </code>view:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Leonardo da Vinci\")\r\n Text(\"Vincent van Gogh\")\r\n }\r\n }\r\n}</pre>\r\nSuppose you use the <code>environment()</code> modifier to set the preview mode to<code> dark</code>, like this:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n ContentView()\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n}</pre>\r\nThe words in the <code>Text</code> views automatically change to white, but the background remains white (running on the simulator or an actual device doesn’t have this issue), as shown below. So, essentially, you get a white screen.\r\n\r\n[caption id=\"attachment_274198\" align=\"aligncenter\" width=\"137\"]<img class=\"wp-image-274198 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-dark-mode-137x255.jpg\" alt=\"SwiftUI dark mode\" width=\"137\" height=\"255\" /> Previewing in dark mode but the background of the app is still white.[/caption]\r\n\r\n \r\n\r\nTo fix this problem, wrap the <code>ContentView</code> view using a <code>ZStack</code> and set its background to black, like this:\r\n<pre class=\"code\">struct ContentView_Previews: PreviewProvider {\r\n static var previews: some View {\r\n ZStack {\r\n Color(.black)\r\n ContentView()\r\n }\r\n .edgesIgnoringSafeArea(.all)\r\n .environment(\\.colorScheme, .dark)\r\n }\r\n}</pre>\r\nThe image below shows the text showing up on a black background.\r\n\r\n[caption id=\"attachment_274199\" align=\"aligncenter\" width=\"138\"]<img class=\"wp-image-274199 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-dark-mode-138x255.jpg\" alt=\"SwiftUI dark mode\" width=\"138\" height=\"255\" /> You can now preview the dark mode correctly.[/caption]\r\n\r\n \r\n<h2 id=\"tab8\" ><a name=\"_Toc37583256\"></a>Extract subviews in SwiftUI</h2>\r\nYour UI may contain quite a large number of views. This is very common if you have a complicated UI. However, you can simplify your UI by extracting some of the views as subviews. Consider the following example:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n Image(\"weimenglee\")\r\n .resizable()\r\n .frame(width: CGFloat(120),\r\n height: CGFloat(120))\r\n .cornerRadius(CGFloat(15),\r\n antialiased: true)\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n }\r\n}</pre>\r\nTo break down the UI into smaller subviews so that your UI is more modular and manageable, follow these steps:\r\n<ol>\r\n \t<li>In the preview canvas, select the <code>Image</code> view and press the ⌘ key.\r\n\r\n[caption id=\"attachment_274200\" align=\"aligncenter\" width=\"247\"]<img class=\"wp-image-274200 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-subviews-247x255.jpg\" alt=\"SwiftUI subviews\" width=\"247\" height=\"255\" /> Extracting views as subviews in the preview canvas.[/caption]</li>\r\n \t<li>Select Extract Subview.</li>\r\n \t<li>Name the new view PhotoView.</li>\r\n</ol>\r\n[caption id=\"attachment_274201\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274201 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-name-subview.jpg\" alt=\"name subview SwiftUI\" width=\"556\" height=\"373\" /> Naming the newly extracted subview.[/caption]\r\n\r\n \r\n\r\nThe<code> Image</code> view will now be extracted as a new struct named PhotoView:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n PhotoView()\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n }\r\n}\r\n\r\nstruct PhotoView: View {\r\n var body: some View {\r\n Image(\"weimenglee\")\r\n .resizable()\r\n .frame(width: CGFloat(120),\r\n height: CGFloat(120))\r\n .cornerRadius(CGFloat(15),\r\n antialiased: true)\r\n }\r\n}</pre>\r\nYou can now also extract the<code> VStack</code> and save it as another struct named <code>DetailsView</code>. Now your UI looks like the following, which is more maintainable:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n HStack {\r\n PhotoView()\r\n DetailsView()\r\n }\r\n }\r\n}\r\n\r\nstruct PhotoView: View {\r\n...\r\n}\r\n\r\nstruct DetailsView: View {\r\n var body: some View {\r\n VStack {\r\n Text(\"Wei-Meng Lee\")\r\n .font(.largeTitle)\r\n .bold()\r\n Text(\"Founder\")\r\n Text(\"Developer Learning Solutions\")\r\n .italic()\r\n Text(\"http://calendar.learn2develop.net\")\r\n Text(\"@weimenglee\")\r\n }\r\n }\r\n}</pre>\r\n<h2 id=\"tab9\" ><a name=\"_Toc37583257\"></a>Display a context menu in SwiftUI</h2>\r\nOne of the innovative features of iPhone is the support for Haptic Touch (which replaces the 3D Touch on older iPhones). Using Haptic Touch, you can long-press an item on your iPhone and a context-sensitive menu appears (if the app you’re using supports it). You can support this feature in SwiftUI as well.\r\n\r\nTo attach a context menu to a view, use the<code> contextMenu()</code> modifier:\r\n\r\nTo attach a context menu to a view, use the contextMenu() modifier:\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n Image(\"Mac Pro\")\r\n .resizable()\r\n .frame(width: 300, height: 280)\r\n .contextMenu {\r\n Button(action: {\r\n print(\"Save Image button tapped...\")\r\n }) {\r\n Text(\"Save Image\")\r\n Image(systemName: \r\n \"tray.and.arrow.down\")\r\n }\r\n Button(action: {\r\n print(\"Add to Cart button tapped...\")\r\n }) {\r\n Text(\"Add to Cart\")\r\n Image(systemName: \"plus\")\r\n }\r\n }\r\n }\r\n}</pre>\r\nTo create a context menu, you provide a list of<code> Button</code> views, and the content of each button is automatically wrapped using an <code>HStack</code> view. Now when you long-press the <code>Image</code> view, a context menu appears.\r\n\r\n[caption id=\"attachment_274202\" align=\"aligncenter\" width=\"244\"]<img class=\"wp-image-274202 size-medium\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-image-view-244x255.jpg\" alt=\"SwiftUI Image view\" width=\"244\" height=\"255\" /> Implementing a context menu on an Image view.[/caption]\r\n\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwifUI Cheat Sheet</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Resume SwiftUI’s live preview","target":"#tab1"},{"label":"Combine text views in SwiftUI","target":"#tab2"},{"label":"Create custom modifiers in SwiftUI","target":"#tab3"},{"label":"Display multiple alerts in SwiftUI","target":"#tab4"},{"label":"Enable debug preview in SwiftUI","target":"#tab5"},{"label":"Preview your SwiftUI app using different devices","target":"#tab6"},{"label":"Dark mode only works on NavigationView","target":"#tab7"},{"label":"Extract subviews in SwiftUI","target":"#tab8"},{"label":"Display a context menu in SwiftUI","target":"#tab9"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48f1a23\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48f231d\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274192},{"headers":{"creationTime":"2020-10-06T19:16:21+00:00","modifiedTime":"2022-08-10T16:46:26+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"What Is Swift Programming? Understanding What SwiftUI Is","strippedTitle":"what is swift programming? understanding what swiftui is","slug":"what-is-swift-programming-understanding-what-swiftui-is","canonicalUrl":"","seo":{"metaDescription":"SwiftUI is a framework for developing apps for Apple products. Swift is the new programming language to help fill the gaps of UIKit. Find out more.","noIndex":0,"noFollow":0},"content":"SwiftUI is a declarative programming framework for developing UIs for <a href=\"https://www.dummies.com/web-design-development/ios/why-you-should-develop-ios-apps/\" target=\"_blank\" rel=\"noopener\">iOS</a>, iPadOS, watchOS, tvOS, and macOS applications. In fact, SwiftUI was invented by the watchOS group at Apple.\r\n\r\nBefore SwiftUI was introduced, most developers use UIKit and Storyboard (which is still supported by Apple in the current version of Xcode to design a UI. Using UIKit and Storyboard, developers drag and drop View controls onto View Controllers and connect them to outlets and actions on the View Controller classes. This model of building UIs is known as <em>Model View Controller</em> (MVC), which creates a clean separation between UI and business logic.\r\n\r\nThe following shows a simple implementation in UIKit and Storyboard. Here, a <code>Button</code> and <code>Label</code> view have been added to the View Controller in Storyboard; two outlets and an action have been created to connect to them:\r\n<pre class=\"code\">class ViewController: UIViewController {\r\n\r\n &lt;strong&gt; @IBOutlet weak var lbl: UILabel!\r\n @IBOutlet weak var button: UIButton!\r\n @IBAction func btnClicked(_ sender: Any) {\r\n lbl.text = \"Button tapped\"\r\n }&lt;/strong&gt;</pre>\r\nFor laying out the views, you use auto-layout to position the button and label in the middle of the screen (both horizontally and vertically).\r\n\r\nTo customize the look and feel of the button, you can code it in the <code>loadView()</code> method, like this:\r\n<pre class=\"code\"> override func loadView() {\r\n super.loadView()\r\n\r\n &lt;strong&gt;// background color\r\n button.backgroundColor = UIColor.yellow\r\n\r\n // button text and color\r\n button.setTitle(\"Submit\", for: .normal)\r\n button.setTitleColor(.black, for: .normal)\r\n\r\n // padding\r\n button.contentEdgeInsets = UIEdgeInsets(\r\n top: 10, left: 10, bottom: 10, right: 10)\r\n\r\n // border\r\n button.layer.borderColor =\r\n UIColor.darkGray.cgColor\r\n button.layer.borderWidth = 3.0\r\n\r\n // text font\r\n button.titleLabel!.font =\r\n UIFont.systemFont(ofSize: 26, weight:\r\n UIFont.Weight.regular)\r\n\r\n // rounder corners\r\n button.layer.cornerRadius = 10\r\n\r\n // auto adjust button size\r\n button.sizeToFit()\r\n &lt;/strong&gt; }</pre>\r\nThe following image shows the button that has customized. UIKit is an <em>event-driven</em> framework, where you can reference each view in your view controller, update its appearance, or handle an event through <em>delegates</em> when some events occurred.\r\n\r\n[caption id=\"attachment_273770\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-273770 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-uikit.jpg\" alt=\"UIKit\" width=\"556\" height=\"563\" /> UIKit is event driven, and it uses delegates to handle events.[/caption]\r\n\r\n \r\n\r\nIn contrast, SwiftUI is a <em>state-driven, </em>declarative framework. In SwiftUI, you can implement all the above with the following statements:\r\n<pre class=\"code\">struct ContentView: View {\r\n &lt;strong&gt; @State private var label = \"label\"&lt;/strong&gt;\r\n\r\n var body: some View {\r\n &lt;strong&gt;VStack {\r\n Button(action: {\r\n self.label = \"Button tapped\"\r\n }) {\r\n Text(\"Submit\")\r\n .padding(EdgeInsets(\r\n top: 10, leading: 10,\r\n bottom: 10, trailing: 10))\r\n .background(Color.yellow)\r\n .foregroundColor(Color.black)\r\n .border(Color.gray, width: 3)\r\n .font(Font.system(size: 26.0))\r\n .overlay(\r\n RoundedRectangle(cornerRadius: 10)\r\n .stroke(Color.gray,\r\n lineWidth: 5)\r\n &lt;/strong&gt; &lt;strong&gt; )\r\n }\r\n Text(label)\r\n .padding()\r\n }&lt;/strong&gt;\r\n }\r\n}</pre>\r\nNotice that all the views are now created declaratively using code — no more drag-and-drop in Storyboard. Layouts are now also specified declaratively using code (the <code>VStack</code> in this example stacks all the views vertically). Delegates are now replaced with closures.\r\n\r\nMore important, views are now a function of state (and not a sequence of events) — the text displayed by the <code>Text</code> view is now bound to the state variable <code>label</code>. When the button is tapped, you change the value of the<code> label</code> state variable, which automatically updates the text displayed in the <code>Text</code> view. This programming paradigm is known as <em>reactive programming</em><em>.</em>\r\n\r\nThe image below shows the various views in action.\r\n\r\n[caption id=\"attachment_273771\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-273771 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui.jpg\" alt=\"SwiftUI\" width=\"556\" height=\"561\" /> SwiftUI is a state-driven declarative framework.[/caption]\r\n\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","description":"SwiftUI is a declarative programming framework for developing UIs for <a href=\"https://www.dummies.com/web-design-development/ios/why-you-should-develop-ios-apps/\" target=\"_blank\" rel=\"noopener\">iOS</a>, iPadOS, watchOS, tvOS, and macOS applications. In fact, SwiftUI was invented by the watchOS group at Apple.\r\n\r\nBefore SwiftUI was introduced, most developers use UIKit and Storyboard (which is still supported by Apple in the current version of Xcode to design a UI. Using UIKit and Storyboard, developers drag and drop View controls onto View Controllers and connect them to outlets and actions on the View Controller classes. This model of building UIs is known as <em>Model View Controller</em> (MVC), which creates a clean separation between UI and business logic.\r\n\r\nThe following shows a simple implementation in UIKit and Storyboard. Here, a <code>Button</code> and <code>Label</code> view have been added to the View Controller in Storyboard; two outlets and an action have been created to connect to them:\r\n<pre class=\"code\">class ViewController: UIViewController {\r\n\r\n &lt;strong&gt; @IBOutlet weak var lbl: UILabel!\r\n @IBOutlet weak var button: UIButton!\r\n @IBAction func btnClicked(_ sender: Any) {\r\n lbl.text = \"Button tapped\"\r\n }&lt;/strong&gt;</pre>\r\nFor laying out the views, you use auto-layout to position the button and label in the middle of the screen (both horizontally and vertically).\r\n\r\nTo customize the look and feel of the button, you can code it in the <code>loadView()</code> method, like this:\r\n<pre class=\"code\"> override func loadView() {\r\n super.loadView()\r\n\r\n &lt;strong&gt;// background color\r\n button.backgroundColor = UIColor.yellow\r\n\r\n // button text and color\r\n button.setTitle(\"Submit\", for: .normal)\r\n button.setTitleColor(.black, for: .normal)\r\n\r\n // padding\r\n button.contentEdgeInsets = UIEdgeInsets(\r\n top: 10, left: 10, bottom: 10, right: 10)\r\n\r\n // border\r\n button.layer.borderColor =\r\n UIColor.darkGray.cgColor\r\n button.layer.borderWidth = 3.0\r\n\r\n // text font\r\n button.titleLabel!.font =\r\n UIFont.systemFont(ofSize: 26, weight:\r\n UIFont.Weight.regular)\r\n\r\n // rounder corners\r\n button.layer.cornerRadius = 10\r\n\r\n // auto adjust button size\r\n button.sizeToFit()\r\n &lt;/strong&gt; }</pre>\r\nThe following image shows the button that has customized. UIKit is an <em>event-driven</em> framework, where you can reference each view in your view controller, update its appearance, or handle an event through <em>delegates</em> when some events occurred.\r\n\r\n[caption id=\"attachment_273770\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-273770 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-uikit.jpg\" alt=\"UIKit\" width=\"556\" height=\"563\" /> UIKit is event driven, and it uses delegates to handle events.[/caption]\r\n\r\n \r\n\r\nIn contrast, SwiftUI is a <em>state-driven, </em>declarative framework. In SwiftUI, you can implement all the above with the following statements:\r\n<pre class=\"code\">struct ContentView: View {\r\n &lt;strong&gt; @State private var label = \"label\"&lt;/strong&gt;\r\n\r\n var body: some View {\r\n &lt;strong&gt;VStack {\r\n Button(action: {\r\n self.label = \"Button tapped\"\r\n }) {\r\n Text(\"Submit\")\r\n .padding(EdgeInsets(\r\n top: 10, leading: 10,\r\n bottom: 10, trailing: 10))\r\n .background(Color.yellow)\r\n .foregroundColor(Color.black)\r\n .border(Color.gray, width: 3)\r\n .font(Font.system(size: 26.0))\r\n .overlay(\r\n RoundedRectangle(cornerRadius: 10)\r\n .stroke(Color.gray,\r\n lineWidth: 5)\r\n &lt;/strong&gt; &lt;strong&gt; )\r\n }\r\n Text(label)\r\n .padding()\r\n }&lt;/strong&gt;\r\n }\r\n}</pre>\r\nNotice that all the views are now created declaratively using code — no more drag-and-drop in Storyboard. Layouts are now also specified declaratively using code (the <code>VStack</code> in this example stacks all the views vertically). Delegates are now replaced with closures.\r\n\r\nMore important, views are now a function of state (and not a sequence of events) — the text displayed by the <code>Text</code> view is now bound to the state variable <code>label</code>. When the button is tapped, you change the value of the<code> label</code> state variable, which automatically updates the text displayed in the <code>Text</code> view. This programming paradigm is known as <em>reactive programming</em><em>.</em>\r\n\r\nThe image below shows the various views in action.\r\n\r\n[caption id=\"attachment_273771\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-273771 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui.jpg\" alt=\"SwiftUI\" width=\"556\" height=\"561\" /> SwiftUI is a state-driven declarative framework.[/caption]\r\n\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48e6eca\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48e79cf\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":273769},{"headers":{"creationTime":"2020-10-28T20:51:06+00:00","modifiedTime":"2022-08-10T16:44:34+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"A Quick Intro to Swift Functions","strippedTitle":"a quick intro to swift functions","slug":"a-quick-intro-to-swift-functions","canonicalUrl":"","seo":{"metaDescription":"Want to know how to program great iOS apps? SwiftUI is a great tool for exactly that purpose. But first, let's learn about Swift functions.","noIndex":0,"noFollow":0},"content":"Are you ready to <a href=\"https://www.dummies.com/web-design-development/ios/what-makes-a-great-ios-app/\" target=\"_blank\" rel=\"noopener\">build iOS apps</a> using an innovative and intuitive user interface? Then, SwiftUI is for you! But before you dive in, you’ll need to know about Swift functions. Here’s a quick intro.\r\n\r\n[caption id=\"attachment_274212\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274212 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-developer.jpg\" alt=\"SwiftUI app development\" width=\"556\" height=\"370\" /> ©Shutterstock/baranq[/caption]\r\n\r\nIn Swift, a function is defined using the <code>func</code> keyword, like this:\r\n<pre class=\"code\">func doSomething() {\r\n print(\"doSomething\")\r\n}</pre>\r\nThe preceding code snippet defines a function called <code>doSomething</code>. It does not take in any inputs (known as <em>parameters</em>) and does not return a value (technically, it does return a <code>Void</code> value).\r\n\r\nTo call the function, simply call its name followed by a pair of empty parentheses:\r\n<pre class=\"code\">doSomething()</pre>\r\n<h2 id=\"tab1\" ><a name=\"_Toc273568048\"></a><a name=\"_Toc39248487\"></a>Understanding input parameters</h2>\r\nA function can also optionally define one or more named typed inputs. The following function takes in one single typed input parameter:\r\n<pre class=\"code\">func doSomething(num: Int) {\r\n print(num)\r\n}</pre>\r\nTo call this function, call its name and pass in an integer value (known as an <em>argument</em>) with the parameter name, like this:\r\n<pre class=\"code\">doSomething(num: 5)</pre>\r\nThe following function takes in two input parameters, both of type Int:\r\n<pre class=\"code\">func doSomething(num1: Int, num2: Int) {\r\n print(num1, num2)\r\n}</pre>\r\nTo call this function, pass it two integer values as the argument:\r\n<pre class=\"code\">doSomething(num1: 5, num2: 6)</pre>\r\n<h2 id=\"tab2\" ><a name=\"_Toc39248488\"></a><a name=\"_Toc273568049\"></a>Returning a value</h2>\r\nFunctions are not required to return a value. However, if you want the function to return a value, use the -> operator after the function declaration. The following function returns an integer value:\r\n<pre class=\"code\">func doSomething(num1: Int, num2: Int, num3: Int) -&gt; Int {\r\n return num1 + num2 + num3\r\n}</pre>\r\nYou use the <code>return</code> keyword to return a value from a function and then exit it. When the function returns a value, you can assign it to a variable or constant, like this:\r\n<pre class=\"code\">var sum = doSomething(num1:5, num2:6, num3: 7)</pre>\r\n<p class=\"article-tips tip\">Functions are not limited to returning a single value. In some cases, it’s important for functions to return multiple values (or even functions). In Swift, you can use a tuple type in a function to return multiple values.</p>\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/\" target=\"_blank\" rel=\"noopener\">SwiftUI tips and tricks</a>.","description":"Are you ready to <a href=\"https://www.dummies.com/web-design-development/ios/what-makes-a-great-ios-app/\" target=\"_blank\" rel=\"noopener\">build iOS apps</a> using an innovative and intuitive user interface? Then, SwiftUI is for you! But before you dive in, you’ll need to know about Swift functions. Here’s a quick intro.\r\n\r\n[caption id=\"attachment_274212\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274212 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-app-developer.jpg\" alt=\"SwiftUI app development\" width=\"556\" height=\"370\" /> ©Shutterstock/baranq[/caption]\r\n\r\nIn Swift, a function is defined using the <code>func</code> keyword, like this:\r\n<pre class=\"code\">func doSomething() {\r\n print(\"doSomething\")\r\n}</pre>\r\nThe preceding code snippet defines a function called <code>doSomething</code>. It does not take in any inputs (known as <em>parameters</em>) and does not return a value (technically, it does return a <code>Void</code> value).\r\n\r\nTo call the function, simply call its name followed by a pair of empty parentheses:\r\n<pre class=\"code\">doSomething()</pre>\r\n<h2 id=\"tab1\" ><a name=\"_Toc273568048\"></a><a name=\"_Toc39248487\"></a>Understanding input parameters</h2>\r\nA function can also optionally define one or more named typed inputs. The following function takes in one single typed input parameter:\r\n<pre class=\"code\">func doSomething(num: Int) {\r\n print(num)\r\n}</pre>\r\nTo call this function, call its name and pass in an integer value (known as an <em>argument</em>) with the parameter name, like this:\r\n<pre class=\"code\">doSomething(num: 5)</pre>\r\nThe following function takes in two input parameters, both of type Int:\r\n<pre class=\"code\">func doSomething(num1: Int, num2: Int) {\r\n print(num1, num2)\r\n}</pre>\r\nTo call this function, pass it two integer values as the argument:\r\n<pre class=\"code\">doSomething(num1: 5, num2: 6)</pre>\r\n<h2 id=\"tab2\" ><a name=\"_Toc39248488\"></a><a name=\"_Toc273568049\"></a>Returning a value</h2>\r\nFunctions are not required to return a value. However, if you want the function to return a value, use the -> operator after the function declaration. The following function returns an integer value:\r\n<pre class=\"code\">func doSomething(num1: Int, num2: Int, num3: Int) -&gt; Int {\r\n return num1 + num2 + num3\r\n}</pre>\r\nYou use the <code>return</code> keyword to return a value from a function and then exit it. When the function returns a value, you can assign it to a variable or constant, like this:\r\n<pre class=\"code\">var sum = doSomething(num1:5, num2:6, num3: 7)</pre>\r\n<p class=\"article-tips tip\">Functions are not limited to returning a single value. In some cases, it’s important for functions to return multiple values (or even functions). In Swift, you can use a tuple type in a function to return multiple values.</p>\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/\" target=\"_blank\" rel=\"noopener\">SwiftUI tips and tricks</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Understanding input parameters","target":"#tab1"},{"label":"Returning a value","target":"#tab2"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48ddcb4\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48de798\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274211},{"headers":{"creationTime":"2020-10-27T19:54:57+00:00","modifiedTime":"2022-08-10T16:37:56+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"A Brief Primer on Swift Programming: Basic Syntax","strippedTitle":"a brief primer on swift programming: basic syntax","slug":"a-brief-primer-on-swift-programming-basic-syntax","canonicalUrl":"","seo":{"metaDescription":"Want to learn the basics of Swift programming? This brief primer teaches you how the basics of Swift syntax, from Dummies.com.","noIndex":0,"noFollow":0},"content":"Swift is a <em>type-safe language,</em> which means that the programming language makes it clear to you the types of values your code is working with. The following article discusses how to declare constants and variables and how to work with strings and comments when programming with Swift.\r\n<h2 id=\"tab1\" ><a name=\"_Toc273410879\"></a><a name=\"_Toc39248462\"></a>Swift constants</h2>\r\nIn Swift, you create a constant using the let keyword:\r\n<pre class=\"code\">let radius = 3.45 // Double\r\nlet numOfColumns = 5 // Int\r\nlet myName = \"Wei-Meng Lee\" // String</pre>\r\nNotice that there is no need to specify the data type — the data types are inferred automatically.\r\n\r\nIf you want to declare the type of constant, you can do so using the colon operator (:) followed by the data type, as shown here:\r\n<pre class=\"code\">let diameter&lt;strong&gt;:Double&lt;/strong&gt; = 8</pre>\r\n<p class=\"article-tips remember\">After a constant is created, you can no longer change its value. Always use a let when you need to store values that do not change.</p>\r\n\r\n<h2 id=\"tab2\" ><a name=\"_Toc273410880\"></a><a name=\"_Toc39248463\"></a>Swift variables</h2>\r\nTo declare a variable, you use the var keyword:\r\n<pre class=\"code\">var myAge = 25\r\nvar circumference = 2 * 3.14 * radius</pre>\r\nAfter a variable is created, you can change its value. In Swift, values are never implicitly converted to another type. For example, suppose you’re trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() function to convert the value of myAge to a string value before concatenating it with another string:\r\n<pre class=\"code\">var strMyAge = \"My age is \" + String(myAge)</pre>\r\n<p class=\"article-tips remember\">To get the text representation of a value (constant or variable), you can also use the description property, like this: myAge.description.</p>\r\n\r\n<h2 id=\"tab3\" ><a name=\"_Toc273410881\"></a><a name=\"_Toc39248464\"></a>Swift strings</h2>\r\nOne of the common tasks in programming is inserting values of variables into a string. In Swift, you use <em>string interpolation</em> and it has the following format:\r\n<pre class=\"code\">\"Your string literal &lt;strong&gt;\\(&lt;/strong&gt;&lt;em&gt;variable_name&lt;/em&gt;&lt;strong&gt;)&lt;/strong&gt;\"</pre>\r\nThe following statement shows an example:\r\n<pre class=\"code\">let firstName = \"Wei-Meng\"\r\nlet lastName = \"Lee\"\r\nvar strName = \"My name is \\(firstName) \\(lastName)\"</pre>\r\nYou can also use this method to include a Double value in your string (or even perform mathematical operations or function calls):\r\n<pre class=\"code\">var strResult = \"The circumference is \\(circumference)\"</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc273410884\"></a><a name=\"_Toc39248465\"></a>Swift comments</h2>\r\nIn Swift, as in most <a href=\"https://www.dummies.com/programming/the-types-of-programming-languages/\" target=\"_blank\" rel=\"noopener\">programming languages</a>, you insert comments into your code using two forward slashes (//):\r\n<pre class=\"code\">// this is another comment</pre>\r\nIf you have several lines of comments, it’s better to use the /* and */ combination to denote a block of statements as comments:\r\n<pre class=\"code\">/*\r\n this is a comment\r\n this is another comment\r\n*/</pre>\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","description":"Swift is a <em>type-safe language,</em> which means that the programming language makes it clear to you the types of values your code is working with. The following article discusses how to declare constants and variables and how to work with strings and comments when programming with Swift.\r\n<h2 id=\"tab1\" ><a name=\"_Toc273410879\"></a><a name=\"_Toc39248462\"></a>Swift constants</h2>\r\nIn Swift, you create a constant using the let keyword:\r\n<pre class=\"code\">let radius = 3.45 // Double\r\nlet numOfColumns = 5 // Int\r\nlet myName = \"Wei-Meng Lee\" // String</pre>\r\nNotice that there is no need to specify the data type — the data types are inferred automatically.\r\n\r\nIf you want to declare the type of constant, you can do so using the colon operator (:) followed by the data type, as shown here:\r\n<pre class=\"code\">let diameter&lt;strong&gt;:Double&lt;/strong&gt; = 8</pre>\r\n<p class=\"article-tips remember\">After a constant is created, you can no longer change its value. Always use a let when you need to store values that do not change.</p>\r\n\r\n<h2 id=\"tab2\" ><a name=\"_Toc273410880\"></a><a name=\"_Toc39248463\"></a>Swift variables</h2>\r\nTo declare a variable, you use the var keyword:\r\n<pre class=\"code\">var myAge = 25\r\nvar circumference = 2 * 3.14 * radius</pre>\r\nAfter a variable is created, you can change its value. In Swift, values are never implicitly converted to another type. For example, suppose you’re trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() function to convert the value of myAge to a string value before concatenating it with another string:\r\n<pre class=\"code\">var strMyAge = \"My age is \" + String(myAge)</pre>\r\n<p class=\"article-tips remember\">To get the text representation of a value (constant or variable), you can also use the description property, like this: myAge.description.</p>\r\n\r\n<h2 id=\"tab3\" ><a name=\"_Toc273410881\"></a><a name=\"_Toc39248464\"></a>Swift strings</h2>\r\nOne of the common tasks in programming is inserting values of variables into a string. In Swift, you use <em>string interpolation</em> and it has the following format:\r\n<pre class=\"code\">\"Your string literal &lt;strong&gt;\\(&lt;/strong&gt;&lt;em&gt;variable_name&lt;/em&gt;&lt;strong&gt;)&lt;/strong&gt;\"</pre>\r\nThe following statement shows an example:\r\n<pre class=\"code\">let firstName = \"Wei-Meng\"\r\nlet lastName = \"Lee\"\r\nvar strName = \"My name is \\(firstName) \\(lastName)\"</pre>\r\nYou can also use this method to include a Double value in your string (or even perform mathematical operations or function calls):\r\n<pre class=\"code\">var strResult = \"The circumference is \\(circumference)\"</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc273410884\"></a><a name=\"_Toc39248465\"></a>Swift comments</h2>\r\nIn Swift, as in most <a href=\"https://www.dummies.com/programming/the-types-of-programming-languages/\" target=\"_blank\" rel=\"noopener\">programming languages</a>, you insert comments into your code using two forward slashes (//):\r\n<pre class=\"code\">// this is another comment</pre>\r\nIf you have several lines of comments, it’s better to use the /* and */ combination to denote a block of statements as comments:\r\n<pre class=\"code\">/*\r\n this is a comment\r\n this is another comment\r\n*/</pre>\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Swift constants","target":"#tab1"},{"label":"Swift variables","target":"#tab2"},{"label":"Swift strings","target":"#tab3"},{"label":"Swift comments","target":"#tab4"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48cc85a\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48cd370\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274150},{"headers":{"creationTime":"2020-10-28T21:22:20+00:00","modifiedTime":"2022-08-10T16:35:01+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"Swift Closures","strippedTitle":"swift closures","slug":"swift-closures","canonicalUrl":"","seo":{"metaDescription":"Want to make better iOS apps?You're in luck! Discover Swift closures and level up your Swift programming game, from Dummies.com.","noIndex":0,"noFollow":0},"content":"One important feature in <a href=\"https://www.dummies.com/programming/macintosh/swift/what-is-swift-programming-understanding-what-swiftui-is/\" target=\"_blank\" rel=\"noopener\">Swift</a> is <em>closure</em><em>.</em> Closures are self-contained blocks of code that can be passed to functions to be executed as independent code units. Think of a closure as a function without a name. In fact, functions are actually special cases of closures.\r\n\r\n[caption id=\"attachment_274218\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274218 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-developing-apps.jpg\" alt=\"SwiftUI app development \" width=\"556\" height=\"370\" /> ©Shutterstock/NDAB Creativity[/caption]\r\n\r\nSwift offers various ways to optimize closures so that they’re brief and succinct. The various optimizations include the following:\r\n<ul>\r\n \t<li>Inferring parameter types and return types</li>\r\n \t<li>Implicit returns from single-statement closures</li>\r\n \t<li>Shorthand argument names</li>\r\n \t<li>Trailing closure syntax</li>\r\n \t<li>Operator closure</li>\r\n</ul>\r\n<h2 id=\"tab1\" ><a name=\"_Toc39248510\"></a><a name=\"_Toc270097018\"></a>Understanding Swift closures</h2>\r\nThe best way to understand Swift closures is to use an example. Suppose you have the following array of integers:\r\n<pre class=\"code\">let numbers = [5,2,8,7,9,4,3,1]</pre>\r\nAssume you want to sort this array in ascending order. You could write your own function to perform the sorting, or you could use the <code>sorted()</code> function available in Swift. The<code> sorted()</code> function takes two arguments:\r\n<ul>\r\n \t<li>An array to be sorted</li>\r\n \t<li>A closure that takes two arguments of the same type as the array and returns a true if the first value appears before the second value</li>\r\n</ul>\r\n<h2 id=\"tab2\" ><a name=\"_Toc39248511\"></a><a name=\"_Toc270097019\"></a>Using Swift functions as closures</h2>\r\nIn Swift, functions are special types of closures. As mentioned, the<code> sorted() </code>function needs a closure that takes two arguments of the same type as the array, returning a <code>true</code> if the first value appears before the second value. The following <a href=\"https://www.dummies.com/programming/macintosh/a-quick-intro-to-swift-functions/\" target=\"_blank\" rel=\"noopener\">Swift function</a> fulfils that requirement:\r\n<pre class=\"code\">func ascending(num1:Int, num2:Int) -&gt; Bool {\r\n return num1</pre>\r\nThe <code>ascending()</code> function takes two arguments of type <code>Int</code> and returns a <code>Bool </code>value. If num1 is less than <code>num2</code>, it returns true. You can now pass this function to the <code>sorted()</code> function, as shown here:\r\n<pre class=\"code\">var sortedNumbers = numbers.sorted(by: ascending)</pre>\r\nThe <code>sorted()</code> function now returns the array that is sorted in ascending order.\r\n\r\nThe <code>sorted()</code> function does not modify the original array. It returns the sorted array as a new array.\r\n<h2 id=\"tab3\" ><a name=\"_Toc39248512\"></a><a name=\"_Toc270097020\"></a>Assigning Swift closures to variables</h2>\r\nAs mentioned earlier, functions are special types of closures. In fact, a closure is a function without a name. However, you can assign a closure to a variable — for example, the<code> ascending()</code> function discussed earlier can be written as a closure assigned to a variable:\r\n<pre class=\"code\">var compareClosure : (Int, Int)-&gt;Bool =\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &lt; num2\r\n }</pre>\r\nTo use the <code>compareClosure</code> closure with the <code>sorted()</code> function, pass in the compareClosure variable:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by: &lt;strong&gt;compareClosure&lt;/strong&gt;)</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc270097021\"></a><a name=\"_Toc39248513\"></a>Writing Swift closures inline</h2>\r\nYou can pass a function into the <code>sorted()</code> function as a closure function, but a better way is to write the closure inline, which obviates the need to define a function explicitly or assign it to a variable.\r\n\r\nRewriting the earlier example would yield the following:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by:\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &lt; num2\r\n }\r\n)</pre>\r\nAs you can see, the<code> ascending()</code> function name is now gone; all you’ve supplied is the parameter list and the content of the function.\r\n\r\nIf you want to sort the array in descending order, you can simply change the comparison operator:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by:\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &gt; num2\r\n }\r\n)</pre>\r\n<h2 id=\"tab5\" ><a name=\"_Toc270097022\"></a><a name=\"_Toc39248514\"></a>Understanding type inference</h2>\r\nBecause the type of the first argument of the closure function must be the same as the type of array you’re sorting, it’s actually redundant to specify the type in the closure, because the compiler can infer that from the type of array you’re using:\r\n<pre class=\"code\">var fruits = [\"orange\", \"apple\", \"durian\",\r\n \"rambutan\", \"pineapple\"]\r\nprint(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nIf your closure has only a single statement, you can even omit the<code> return </code>keyword:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n fruit1</pre>\r\n<h2 id=\"tab6\" ><a name=\"_Toc270097023\"></a><a name=\"_Toc39248515\"></a>Using shorthand argument names</h2>\r\nAbove, names were given to arguments within a closure. In fact, this is also optional, because Swift automatically provides shorthand names to the parameters, which you can refer to as <code>$0</code>, <code>$1</code>, and so on.\r\n\r\nThe previous code snippet could be rewritten as follows without using named parameters:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n $0&lt;$1\r\n })\r\n)</pre>\r\nTo make the closure really terse, you can write everything on one line:\r\n\r\nprint(fruits.sorted(by:<strong>{ $0<$1 }</strong>))\r\n<h2 id=\"tab7\" ><a name=\"_Toc270097024\"></a><a name=\"_Toc39248516\"></a>Working with Swift’s operator function</h2>\r\nYou saw that the closure for the sorted() function was reduced to the following:\r\n<pre class=\"code\">print(fruits.sorted(by:{ $0&lt;$1 }))</pre>\r\nOne of the implementations of the lesser than (<code>&lt;</code>) operator is actually a function that works with two operands of type <code>String</code>. Because of this, you can actually simply specify the <code>&lt;</code> operator in place of the closure, and the compiler will automatically infer that you want to use the particular implementation of the<code> </code><<code> operator. The preceding statement can be reduced to the following:</code>\r\n<pre class=\"code\">print(fruits.sorted(by:&lt;strong&gt;&lt;&lt;/strong&gt;))</pre>\r\nIf you want to sort the array in descending order, simply use the greater than (>) operator:\r\n<pre class=\"code\">print(fruits.sorted(by:&lt;strong&gt;&gt;&lt;/strong&gt;))</pre>\r\n<h2 id=\"tab8\" ><a name=\"_Toc39248517\"></a><a name=\"_Toc270097025\"></a>Using trailing closures in Swift</h2>\r\nConsider the closure that you saw earlier:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nNotice that the closure is passed in as a second argument of the <code>sorted()</code> function. For long closures, this syntax may be a little messy. If the closure is the final argument of a function, you can rewrite this closure as a trailing closure. A trailing closure is written outside of the parentheses of the function call. The preceding code snippet, when rewritten using the trailing closure, looks like this:\r\n<pre class=\"code\">print(fruits.sorted()\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nUsing the shorthand argument name, the closure can be shortened to the following:\r\n<pre class=\"code\">print(fruits.sorted()&lt;strong&gt;{$0&lt;$1}&lt;/strong&gt;)</pre>\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","description":"One important feature in <a href=\"https://www.dummies.com/programming/macintosh/swift/what-is-swift-programming-understanding-what-swiftui-is/\" target=\"_blank\" rel=\"noopener\">Swift</a> is <em>closure</em><em>.</em> Closures are self-contained blocks of code that can be passed to functions to be executed as independent code units. Think of a closure as a function without a name. In fact, functions are actually special cases of closures.\r\n\r\n[caption id=\"attachment_274218\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274218 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-developing-apps.jpg\" alt=\"SwiftUI app development \" width=\"556\" height=\"370\" /> ©Shutterstock/NDAB Creativity[/caption]\r\n\r\nSwift offers various ways to optimize closures so that they’re brief and succinct. The various optimizations include the following:\r\n<ul>\r\n \t<li>Inferring parameter types and return types</li>\r\n \t<li>Implicit returns from single-statement closures</li>\r\n \t<li>Shorthand argument names</li>\r\n \t<li>Trailing closure syntax</li>\r\n \t<li>Operator closure</li>\r\n</ul>\r\n<h2 id=\"tab1\" ><a name=\"_Toc39248510\"></a><a name=\"_Toc270097018\"></a>Understanding Swift closures</h2>\r\nThe best way to understand Swift closures is to use an example. Suppose you have the following array of integers:\r\n<pre class=\"code\">let numbers = [5,2,8,7,9,4,3,1]</pre>\r\nAssume you want to sort this array in ascending order. You could write your own function to perform the sorting, or you could use the <code>sorted()</code> function available in Swift. The<code> sorted()</code> function takes two arguments:\r\n<ul>\r\n \t<li>An array to be sorted</li>\r\n \t<li>A closure that takes two arguments of the same type as the array and returns a true if the first value appears before the second value</li>\r\n</ul>\r\n<h2 id=\"tab2\" ><a name=\"_Toc39248511\"></a><a name=\"_Toc270097019\"></a>Using Swift functions as closures</h2>\r\nIn Swift, functions are special types of closures. As mentioned, the<code> sorted() </code>function needs a closure that takes two arguments of the same type as the array, returning a <code>true</code> if the first value appears before the second value. The following <a href=\"https://www.dummies.com/programming/macintosh/a-quick-intro-to-swift-functions/\" target=\"_blank\" rel=\"noopener\">Swift function</a> fulfils that requirement:\r\n<pre class=\"code\">func ascending(num1:Int, num2:Int) -&gt; Bool {\r\n return num1</pre>\r\nThe <code>ascending()</code> function takes two arguments of type <code>Int</code> and returns a <code>Bool </code>value. If num1 is less than <code>num2</code>, it returns true. You can now pass this function to the <code>sorted()</code> function, as shown here:\r\n<pre class=\"code\">var sortedNumbers = numbers.sorted(by: ascending)</pre>\r\nThe <code>sorted()</code> function now returns the array that is sorted in ascending order.\r\n\r\nThe <code>sorted()</code> function does not modify the original array. It returns the sorted array as a new array.\r\n<h2 id=\"tab3\" ><a name=\"_Toc39248512\"></a><a name=\"_Toc270097020\"></a>Assigning Swift closures to variables</h2>\r\nAs mentioned earlier, functions are special types of closures. In fact, a closure is a function without a name. However, you can assign a closure to a variable — for example, the<code> ascending()</code> function discussed earlier can be written as a closure assigned to a variable:\r\n<pre class=\"code\">var compareClosure : (Int, Int)-&gt;Bool =\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &lt; num2\r\n }</pre>\r\nTo use the <code>compareClosure</code> closure with the <code>sorted()</code> function, pass in the compareClosure variable:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by: &lt;strong&gt;compareClosure&lt;/strong&gt;)</pre>\r\n<h2 id=\"tab4\" ><a name=\"_Toc270097021\"></a><a name=\"_Toc39248513\"></a>Writing Swift closures inline</h2>\r\nYou can pass a function into the <code>sorted()</code> function as a closure function, but a better way is to write the closure inline, which obviates the need to define a function explicitly or assign it to a variable.\r\n\r\nRewriting the earlier example would yield the following:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by:\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &lt; num2\r\n }\r\n)</pre>\r\nAs you can see, the<code> ascending()</code> function name is now gone; all you’ve supplied is the parameter list and the content of the function.\r\n\r\nIf you want to sort the array in descending order, you can simply change the comparison operator:\r\n<pre class=\"code\">sortedNumbers = numbers.sorted(by:\r\n {\r\n (num1:Int, num2:Int) -&gt; Bool in\r\n return num1 &gt; num2\r\n }\r\n)</pre>\r\n<h2 id=\"tab5\" ><a name=\"_Toc270097022\"></a><a name=\"_Toc39248514\"></a>Understanding type inference</h2>\r\nBecause the type of the first argument of the closure function must be the same as the type of array you’re sorting, it’s actually redundant to specify the type in the closure, because the compiler can infer that from the type of array you’re using:\r\n<pre class=\"code\">var fruits = [\"orange\", \"apple\", \"durian\",\r\n \"rambutan\", \"pineapple\"]\r\nprint(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nIf your closure has only a single statement, you can even omit the<code> return </code>keyword:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n fruit1</pre>\r\n<h2 id=\"tab6\" ><a name=\"_Toc270097023\"></a><a name=\"_Toc39248515\"></a>Using shorthand argument names</h2>\r\nAbove, names were given to arguments within a closure. In fact, this is also optional, because Swift automatically provides shorthand names to the parameters, which you can refer to as <code>$0</code>, <code>$1</code>, and so on.\r\n\r\nThe previous code snippet could be rewritten as follows without using named parameters:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n $0&lt;$1\r\n })\r\n)</pre>\r\nTo make the closure really terse, you can write everything on one line:\r\n\r\nprint(fruits.sorted(by:<strong>{ $0<$1 }</strong>))\r\n<h2 id=\"tab7\" ><a name=\"_Toc270097024\"></a><a name=\"_Toc39248516\"></a>Working with Swift’s operator function</h2>\r\nYou saw that the closure for the sorted() function was reduced to the following:\r\n<pre class=\"code\">print(fruits.sorted(by:{ $0&lt;$1 }))</pre>\r\nOne of the implementations of the lesser than (<code>&lt;</code>) operator is actually a function that works with two operands of type <code>String</code>. Because of this, you can actually simply specify the <code>&lt;</code> operator in place of the closure, and the compiler will automatically infer that you want to use the particular implementation of the<code> </code><<code> operator. The preceding statement can be reduced to the following:</code>\r\n<pre class=\"code\">print(fruits.sorted(by:&lt;strong&gt;&lt;&lt;/strong&gt;))</pre>\r\nIf you want to sort the array in descending order, simply use the greater than (>) operator:\r\n<pre class=\"code\">print(fruits.sorted(by:&lt;strong&gt;&gt;&lt;/strong&gt;))</pre>\r\n<h2 id=\"tab8\" ><a name=\"_Toc39248517\"></a><a name=\"_Toc270097025\"></a>Using trailing closures in Swift</h2>\r\nConsider the closure that you saw earlier:\r\n<pre class=\"code\">print(fruits.sorted(by:\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nNotice that the closure is passed in as a second argument of the <code>sorted()</code> function. For long closures, this syntax may be a little messy. If the closure is the final argument of a function, you can rewrite this closure as a trailing closure. A trailing closure is written outside of the parentheses of the function call. The preceding code snippet, when rewritten using the trailing closure, looks like this:\r\n<pre class=\"code\">print(fruits.sorted()\r\n {\r\n (fruit1, fruit2) in\r\n return fruit1</pre>\r\nUsing the shorthand argument name, the closure can be shortened to the following:\r\n<pre class=\"code\">print(fruits.sorted()&lt;strong&gt;{$0&lt;$1}&lt;/strong&gt;)</pre>\r\n \r\n\r\nWant to learn more? Check out our <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI Cheat Sheet</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Understanding Swift closures","target":"#tab1"},{"label":"Using Swift functions as closures","target":"#tab2"},{"label":"Assigning Swift closures to variables","target":"#tab3"},{"label":"Writing Swift closures inline","target":"#tab4"},{"label":"Understanding type inference","target":"#tab5"},{"label":"Using shorthand argument names","target":"#tab6"},{"label":"Working with Swift’s operator function","target":"#tab7"},{"label":"Using trailing closures in Swift","target":"#tab8"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48c31b4\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48c3acd\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274217},{"headers":{"creationTime":"2020-10-30T14:56:33+00:00","modifiedTime":"2022-08-10T16:33:19+00:00","timestamp":"2022-09-14T18:19:52+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"Understanding How to Animate in SwiftUI","strippedTitle":"understanding how to animate in swiftui","slug":"understanding-how-to-animate-in-swiftui","canonicalUrl":"","seo":{"metaDescription":"SwiftUI makes easy work of animation. Use this brief guide to learn the basics of animating in SwiftUI, from Dummies.com.","noIndex":0,"noFollow":0},"content":"To animate a view in <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a>, apply the <code>animation()</code> modifier on it. SwiftUI animates any changes made to animatable properties of a view. For example, the various properties of a view in SwiftUI — such as its color, opacity, rotation, size, and other properties — are all animatable. As usual, the best way to understand this concept is to use an example.\r\n\r\nFirst, create a rounded button that shows the Confirm caption:\r\n<pre class=\"code\">struct ContentView: View {\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n }\r\n}</pre>\r\n[caption id=\"attachment_274232\" align=\"aligncenter\" width=\"294\"]<img class=\"wp-image-274232 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-button-view-294x586.jpg\" alt=\"SwiftUI button view\" width=\"294\" height=\"586\" /> Displaying the rounded Button view in SwiftUI.[/caption]\r\n\r\n \r\n\r\nApply some scaling (zooming) to the button using the <code>scaleEffect()</code> modifier:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var scaleFactor: CGFloat = 1\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .onAppear(perform: {\r\n self.scaleFactor = 2.5\r\n })\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n .scaleEffect(scaleFactor)\r\n }\r\n}</pre>\r\nWhat you want to do here is zoom the button to two and a half times its original size. The scaling will be performed as soon as the <code>Button</code> view is shown in <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a>. The following image shows the button zoomed in to two and a half times its original size when it first appears.\r\n\r\n[caption id=\"attachment_274233\" align=\"aligncenter\" width=\"292\"]<img class=\"wp-image-274233 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-zoom-button-292x586.jpg\" alt=\"SwiftUI zoom button\" width=\"292\" height=\"586\" /> Zooming the Button view two and a half times in SwiftUI.[/caption]\r\n\r\n \r\n\r\nWhat you really want is to slow down the scaling, so that users can see the zooming-in process. For this, you can use the <code>animation()</code> modifier on the <code>Button</code> view:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var scaleFactor: CGFloat = 1\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .onAppear(perform: {\r\n self.scaleFactor = 2.5\r\n })\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n .scaleEffect(scaleFactor)\r\n .animation(.default)\r\n }\r\n}</pre>\r\nThe <code>.default</code> property actually belongs to the <code>Animation</code> struct, so you can rewrite the above statement as follows:\r\n<pre class=\"code\">.animation(&lt;strong&gt;Animation&lt;/strong&gt;.default)</pre>\r\nWhen you now load the Button view again, the button zooms in two and a half times.\r\n<h2 id=\"tab1\" ><a name=\"_Toc33534804\"></a>Specifying the type of animation in SwiftUI</h2>\r\nBy default, the button will zoom in at a linear speed. You can also use the <code>easeInOur()</code> modifier if you want the animation to start slow, pick up speed, and then slow down again:\r\n<pre class=\"code\"> .animation(\r\n .easeInOut(duration: 2)\r\n )</pre>\r\nThe <code>duration</code> parameter indicates how much time is given for the animation to complete in SwiftUI. In this example, the zoom animation must complete in two seconds.\r\n\r\nIf you want to start fast and then slow down, use the <code>easeOut()</code> modifier:\r\n<pre class=\"code\"> .animation(\r\n .easeOut(duration: 2)\r\n )</pre>\r\nBoth the <code>easeInOut()</code> and <code>easeOut()</code> modifiers are type methods of the <code>Animation</code> struct.\r\n<h2 id=\"tab2\" ><a name=\"_Toc33534805\"></a>Repeating the animation in SwiftUI</h2>\r\nMany times, you want the animation to repeat a number of times. For this you can apply the repeatCount() modifier:\r\n<pre class=\"code\"> .animation(\r\n Animation.easeInOut(duration: 2)\r\n .repeatCount(2, autoreverses: true)\r\n )</pre>\r\nThe <code>easeInOut()</code> is a type method of the <code>Animation</code> struct, and it returns an <code>Animation</code> struct. So, in this case, you call the <code>repeatCount()</code> modifier of the <code>Animation</code> struct to repeat the animation a number of times (twice, in this case). The <code>autoreverses</code> parameter allows you to reverse the animation, so for this particular case the size of the button changes from small to big, and then reverses and changes from big to small.\r\n\r\nThe image below shows the animation that is repeated twice. Notice that at the end of the second animation, the button reverts back to the larger size as specified in the scaleFactor state variable:\r\n<pre class=\"code\">.scaleEffect(scaleFactor) // changed to 2.5 in onAppear()</pre>\r\n[caption id=\"attachment_274234\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274234 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-scaling.png\" alt=\"animate button SwiftUI\" width=\"556\" height=\"231\" /> Animating the changing of the scale of the button.[/caption]\r\n\r\n \r\n\r\nIf you want the animation to repeat forever, use the <code>repeatForever()</code> modifier:\r\n<pre class=\"code\"> .animation(\r\n Animation.easeInOut(duration: 2)\r\n .repeatForever(autoreverses: true)\r\n )</pre>\r\n<h2 id=\"tab3\" ><a name=\"_Toc33534806\"></a>Stopping the animation in SwiftUI</h2>\r\nAlthough you can animate nonstop in SwiftUI, there are times where you need to stop the animation. Here’s another example:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var opacity:Double = 1.0\r\n\r\n var body: some View {\r\n Button(action: {\r\n })\r\n {\r\n Text(\"Click Me\")\r\n .fontWeight(.bold)\r\n .font(.title)\r\n .foregroundColor(.blue)\r\n .padding()\r\n .background(Color.yellow)\r\n .overlay(\r\n Rectangle()\r\n .stroke(Color.blue, lineWidth: 5)\r\n )\r\n .opacity(opacity)\r\n .onAppear() {\r\n let baseAnimation =\r\n Animation.linear(duration: 1)\r\n withAnimation (\r\n baseAnimation.repeatForever(\r\n autoreverses: true))\r\n {\r\n self.opacity = 0.2\r\n }\r\n }\r\n }\r\n }\r\n}</pre>\r\nThe preceding code snippet shows a <code>Button</code> view with its opacity initially set to 1.0. When it appears, you perform a <em>linear animation</em> (animating with constant speed) to change the opacity of the button down to 0.2, all within a duration of 1 second. In the next 1 second, it then changes to fully opaque again.\r\n\r\nUnlike the earlier example, this example does not use the <code>animation()</code> modifier for animation. Instead, you use the <code>withAnimation</code> block. The <code>withAnimation</code> block lets you explicitly tell SwiftUI what to animate.\r\n\r\nThe image below shows the button fully opaque when it’s loaded and then gradually changes its opacity to 0.2.\r\n\r\n[caption id=\"attachment_274235\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274235 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-dim-button-view.jpg\" alt=\"dim button view in SwiftUI\" width=\"556\" height=\"558\" /> Dimming the Button view in SwiftUI.[/caption]\r\n\r\n \r\n\r\nThe animation is perpetual, so to stop it, you need to do some work in SwiftUI. For this, you can use a Boolean state variable (let’s call it animate) and use it to determine if the animation should continue:\r\n<pre class=\"code\"> withAnimation (self.animate ?\r\n baseAnimation.repeatForever(\r\n autoreverses: true) :\r\n Animation.default) {\r\n self.opacity = 0.2\r\n }</pre>\r\nIn the preceding Swift code snippet, if the animate state variable is <code>true</code>, you’ll perform the animation perpetually, or you can set the animation to <code>default</code> (which will only perform the animation once).\r\n\r\nThe following code snippet stops the animation when the button is tapped and sets the opacity of the button back to 1:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var opacity:Double = 1.0\r\n @State private var animate = true\r\n\r\n var body: some View {\r\n Button(action: {\r\n self.animate = false\r\n self.opacity = 1.0\r\n })\r\n {\r\n Text(\"Click Me\")\r\n .fontWeight(.bold)\r\n .font(.title)\r\n .foregroundColor(.blue)\r\n .padding()\r\n .background(Color.yellow)\r\n .overlay(\r\n Rectangle()\r\n .stroke(Color.blue, lineWidth: 5)\r\n )\r\n .opacity(opacity)\r\n .onAppear() {\r\n let baseAnimation =\r\n Animation.linear(duration: 1)\r\n withAnimation (self.animate ?\r\n baseAnimation.repeatForever(\r\n autoreverses: true) :\r\n Animation.default) {\r\n self.opacity = 0.2\r\n }\r\n }\r\n }\r\n }\r\n}</pre>\r\nRemember to follow the <a href=\"https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/animation\" target=\"_blank\" rel=\"noopener\">Apple Human Interface Guidelines (HIG)</a> when it comes to animating your UI. This also applies to custom animations.\r\n\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/10-great-swiftui-resources/\" target=\"_blank\" rel=\"noopener\">SwiftUI resources</a>.","description":"To animate a view in <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a>, apply the <code>animation()</code> modifier on it. SwiftUI animates any changes made to animatable properties of a view. For example, the various properties of a view in SwiftUI — such as its color, opacity, rotation, size, and other properties — are all animatable. As usual, the best way to understand this concept is to use an example.\r\n\r\nFirst, create a rounded button that shows the Confirm caption:\r\n<pre class=\"code\">struct ContentView: View {\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n }\r\n}</pre>\r\n[caption id=\"attachment_274232\" align=\"aligncenter\" width=\"294\"]<img class=\"wp-image-274232 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-button-view-294x586.jpg\" alt=\"SwiftUI button view\" width=\"294\" height=\"586\" /> Displaying the rounded Button view in SwiftUI.[/caption]\r\n\r\n \r\n\r\nApply some scaling (zooming) to the button using the <code>scaleEffect()</code> modifier:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var scaleFactor: CGFloat = 1\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .onAppear(perform: {\r\n self.scaleFactor = 2.5\r\n })\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n .scaleEffect(scaleFactor)\r\n }\r\n}</pre>\r\nWhat you want to do here is zoom the button to two and a half times its original size. The scaling will be performed as soon as the <code>Button</code> view is shown in <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/\" target=\"_blank\" rel=\"noopener\">SwiftUI</a>. The following image shows the button zoomed in to two and a half times its original size when it first appears.\r\n\r\n[caption id=\"attachment_274233\" align=\"aligncenter\" width=\"292\"]<img class=\"wp-image-274233 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-zoom-button-292x586.jpg\" alt=\"SwiftUI zoom button\" width=\"292\" height=\"586\" /> Zooming the Button view two and a half times in SwiftUI.[/caption]\r\n\r\n \r\n\r\nWhat you really want is to slow down the scaling, so that users can see the zooming-in process. For this, you can use the <code>animation()</code> modifier on the <code>Button</code> view:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var scaleFactor: CGFloat = 1\r\n\r\n var body: some View {\r\n Button(action: {\r\n }) {\r\n Text(\"Confirm\")\r\n .bold()\r\n }\r\n .onAppear(perform: {\r\n self.scaleFactor = 2.5\r\n })\r\n .padding(40)\r\n .background(Color.green)\r\n .foregroundColor(.white)\r\n .clipShape(Circle())\r\n .scaleEffect(scaleFactor)\r\n .animation(.default)\r\n }\r\n}</pre>\r\nThe <code>.default</code> property actually belongs to the <code>Animation</code> struct, so you can rewrite the above statement as follows:\r\n<pre class=\"code\">.animation(&lt;strong&gt;Animation&lt;/strong&gt;.default)</pre>\r\nWhen you now load the Button view again, the button zooms in two and a half times.\r\n<h2 id=\"tab1\" ><a name=\"_Toc33534804\"></a>Specifying the type of animation in SwiftUI</h2>\r\nBy default, the button will zoom in at a linear speed. You can also use the <code>easeInOur()</code> modifier if you want the animation to start slow, pick up speed, and then slow down again:\r\n<pre class=\"code\"> .animation(\r\n .easeInOut(duration: 2)\r\n )</pre>\r\nThe <code>duration</code> parameter indicates how much time is given for the animation to complete in SwiftUI. In this example, the zoom animation must complete in two seconds.\r\n\r\nIf you want to start fast and then slow down, use the <code>easeOut()</code> modifier:\r\n<pre class=\"code\"> .animation(\r\n .easeOut(duration: 2)\r\n )</pre>\r\nBoth the <code>easeInOut()</code> and <code>easeOut()</code> modifiers are type methods of the <code>Animation</code> struct.\r\n<h2 id=\"tab2\" ><a name=\"_Toc33534805\"></a>Repeating the animation in SwiftUI</h2>\r\nMany times, you want the animation to repeat a number of times. For this you can apply the repeatCount() modifier:\r\n<pre class=\"code\"> .animation(\r\n Animation.easeInOut(duration: 2)\r\n .repeatCount(2, autoreverses: true)\r\n )</pre>\r\nThe <code>easeInOut()</code> is a type method of the <code>Animation</code> struct, and it returns an <code>Animation</code> struct. So, in this case, you call the <code>repeatCount()</code> modifier of the <code>Animation</code> struct to repeat the animation a number of times (twice, in this case). The <code>autoreverses</code> parameter allows you to reverse the animation, so for this particular case the size of the button changes from small to big, and then reverses and changes from big to small.\r\n\r\nThe image below shows the animation that is repeated twice. Notice that at the end of the second animation, the button reverts back to the larger size as specified in the scaleFactor state variable:\r\n<pre class=\"code\">.scaleEffect(scaleFactor) // changed to 2.5 in onAppear()</pre>\r\n[caption id=\"attachment_274234\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274234 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-scaling.png\" alt=\"animate button SwiftUI\" width=\"556\" height=\"231\" /> Animating the changing of the scale of the button.[/caption]\r\n\r\n \r\n\r\nIf you want the animation to repeat forever, use the <code>repeatForever()</code> modifier:\r\n<pre class=\"code\"> .animation(\r\n Animation.easeInOut(duration: 2)\r\n .repeatForever(autoreverses: true)\r\n )</pre>\r\n<h2 id=\"tab3\" ><a name=\"_Toc33534806\"></a>Stopping the animation in SwiftUI</h2>\r\nAlthough you can animate nonstop in SwiftUI, there are times where you need to stop the animation. Here’s another example:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var opacity:Double = 1.0\r\n\r\n var body: some View {\r\n Button(action: {\r\n })\r\n {\r\n Text(\"Click Me\")\r\n .fontWeight(.bold)\r\n .font(.title)\r\n .foregroundColor(.blue)\r\n .padding()\r\n .background(Color.yellow)\r\n .overlay(\r\n Rectangle()\r\n .stroke(Color.blue, lineWidth: 5)\r\n )\r\n .opacity(opacity)\r\n .onAppear() {\r\n let baseAnimation =\r\n Animation.linear(duration: 1)\r\n withAnimation (\r\n baseAnimation.repeatForever(\r\n autoreverses: true))\r\n {\r\n self.opacity = 0.2\r\n }\r\n }\r\n }\r\n }\r\n}</pre>\r\nThe preceding code snippet shows a <code>Button</code> view with its opacity initially set to 1.0. When it appears, you perform a <em>linear animation</em> (animating with constant speed) to change the opacity of the button down to 0.2, all within a duration of 1 second. In the next 1 second, it then changes to fully opaque again.\r\n\r\nUnlike the earlier example, this example does not use the <code>animation()</code> modifier for animation. Instead, you use the <code>withAnimation</code> block. The <code>withAnimation</code> block lets you explicitly tell SwiftUI what to animate.\r\n\r\nThe image below shows the button fully opaque when it’s loaded and then gradually changes its opacity to 0.2.\r\n\r\n[caption id=\"attachment_274235\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274235 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-dim-button-view.jpg\" alt=\"dim button view in SwiftUI\" width=\"556\" height=\"558\" /> Dimming the Button view in SwiftUI.[/caption]\r\n\r\n \r\n\r\nThe animation is perpetual, so to stop it, you need to do some work in SwiftUI. For this, you can use a Boolean state variable (let’s call it animate) and use it to determine if the animation should continue:\r\n<pre class=\"code\"> withAnimation (self.animate ?\r\n baseAnimation.repeatForever(\r\n autoreverses: true) :\r\n Animation.default) {\r\n self.opacity = 0.2\r\n }</pre>\r\nIn the preceding Swift code snippet, if the animate state variable is <code>true</code>, you’ll perform the animation perpetually, or you can set the animation to <code>default</code> (which will only perform the animation once).\r\n\r\nThe following code snippet stops the animation when the button is tapped and sets the opacity of the button back to 1:\r\n<pre class=\"code\">struct ContentView: View {\r\n @State private var opacity:Double = 1.0\r\n @State private var animate = true\r\n\r\n var body: some View {\r\n Button(action: {\r\n self.animate = false\r\n self.opacity = 1.0\r\n })\r\n {\r\n Text(\"Click Me\")\r\n .fontWeight(.bold)\r\n .font(.title)\r\n .foregroundColor(.blue)\r\n .padding()\r\n .background(Color.yellow)\r\n .overlay(\r\n Rectangle()\r\n .stroke(Color.blue, lineWidth: 5)\r\n )\r\n .opacity(opacity)\r\n .onAppear() {\r\n let baseAnimation =\r\n Animation.linear(duration: 1)\r\n withAnimation (self.animate ?\r\n baseAnimation.repeatForever(\r\n autoreverses: true) :\r\n Animation.default) {\r\n self.opacity = 0.2\r\n }\r\n }\r\n }\r\n }\r\n}</pre>\r\nRemember to follow the <a href=\"https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/animation\" target=\"_blank\" rel=\"noopener\">Apple Human Interface Guidelines (HIG)</a> when it comes to animating your UI. This also applies to custom animations.\r\n\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/10-great-swiftui-resources/\" target=\"_blank\" rel=\"noopener\">SwiftUI resources</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Specifying the type of animation in SwiftUI","target":"#tab1"},{"label":"Repeating the animation in SwiftUI","target":"#tab2"},{"label":"Stopping the animation in SwiftUI","target":"#tab3"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48babff\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b48bb5c6\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-08-10T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274231},{"headers":{"creationTime":"2020-08-17T01:55:42+00:00","modifiedTime":"2022-03-25T16:29:25+00:00","timestamp":"2022-09-14T18:19:30+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"SwiftUI For Dummies Cheat Sheet","strippedTitle":"swiftui for dummies cheat sheet","slug":"swiftui-for-dummies-cheat-sheet","canonicalUrl":"","seo":{"metaDescription":"Discover how SwiftUI makes creating iPhone stacked and tabbed applications easy. Also learn how to use the Share Sheet to share something in your app.","noIndex":0,"noFollow":0},"content":"SwiftUI makes creating iPhone stacked and tabbed apps easy! You can add shake fail feedback using animation, so your users know when their login attempt has failed. And you can give users the option of sharing something in your app, using the Share Sheet.","description":"SwiftUI makes creating iPhone stacked and tabbed apps easy! You can add shake fail feedback using animation, so your users know when their login attempt has failed. And you can give users the option of sharing something in your app, using the Share Sheet.","blurb":"","authors":[],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b32e0b7b\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221b32e1644\"></div></div>"},"articleType":{"articleType":"Cheat Sheet","articleList":[{"articleId":0,"title":"","slug":null,"categoryList":[],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/"}}],"content":[{"title":"Creating a Stacked and Tabbed Navigation Application","thumb":null,"image":null,"content":"<p>In iOS, you often encounter applications that combine the use of stacked and tabbed navigations. Creating this kind of design is easy to accomplish using SwiftUI. The following figure shows how such an application may look.</p>\n<p><img loading=\"lazy\" class=\"alignnone size-full wp-image-272597\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-application.jpg\" alt=\"SwiftUI application\" width=\"535\" height=\"356\" /></p>\n<p>The application has two tab items:</p>\n<ul>\n<li><code>TabView1 </code>corresponds to the first tab item.</li>\n<li><code>TabView2 </code>corresponds to the second tab item.</li>\n</ul>\n<p>In <code>TabView1</code>, there is a button that says “Tap Me!” When the user taps this button, the application navigates to <code>DetailView</code>.</p>\n<p>To implement this in SwiftUI, you just need to create three views (you can create them in separate <a href=\"https://dummies-wp-admin.dummies.com/programming/macintosh/swift/swift-for-dummies-cheat-sheet/\">Swift</a> files, or put them all in one single file):</p>\n<pre class=\"“code”\">import SwiftUI\r\n\r\nstruct TabView1: View {\r\n var body: some View {\r\n NavigationView {\r\n NavigationLink(destination: DetailView()) {\r\n Text(\"Tap me!\")\r\n }\r\n .navigationBarTitle(\"TabView1\")\r\n }\r\n }\r\n}\r\n\r\nstruct TabView2: View {\r\n var body: some View {\r\n NavigationView {\r\n Text(\"TabView2\")\r\n .navigationBarTitle(\"TabView2\")\r\n }\r\n }\r\n}\r\n\r\nstruct DetailView: View {\r\n var body: some View {\r\n Text(\"DetailView\")\r\n .navigationBarTitle(\"DetailView\", \r\n displayMode: .inline)\r\n }\r\n}\r\n</pre>\n<p><code>NavigationLink </code>is a button that, when pressed, triggers a navigation presentation. <code>NavigationView </code>is for presenting a stack of views representing a visible path in a navigation hierarchy.<br />\nTo create the tab items, use the <code>TabView </code>view:</p>\n<pre class=\"“code”\">struct ContentView: View {\r\n var body: some View {\r\n TabView {\r\n TabView1()\r\n .tabItem {\r\n Image(systemName: \"doc.richtext\")\r\n Text(\"News\")\r\n }\r\n \r\n TabView2()\r\n .tabItem {\r\n Image(systemName: \"gear\")\r\n Text(\"Preferences\")\r\n }\r\n }\r\n }\r\n}\r\n</pre>\n<p>The <code>tabItem()</code> modifier displays a tab item for each view.</p>\n"},{"title":"Creating Shake Fail Feedback Using Animation","thumb":null,"image":null,"content":"<p>Most iOS users are familiar with this: If you enter an incorrect passcode when unlocking your iPhone, the dots (representing your entered passcode) on your iPhone “shake,” letting you know that your passcode is wrong. This shaking is a useful form of UI feedback — it lets the user know that the login has failed.</p>\n<p>How about implanting this animation in your own app using SwiftUI? Turns out, it isn’t that difficult! You can make use of SwiftUI’s <code>animation() </code>modifier.</p>\n<p>The following code snippet contains a <code>SecureField </code>view with the <code>animation()</code> modifier set:</p>\n<pre class=\"“code”\">struct ContentView: View {\r\n @State var offset:CGFloat = 0\r\n @State private var username: String = \"\"\r\n @State private var password: String = \"\"\r\n \r\n var body: some View {\r\n VStack {\r\n Text(\"Username\")\r\n TextField(\"Enter username\", text:$username)\r\n .frame(width: 300, height: 30)\r\n .border(Color.black)\r\n \r\n Text(\"Password\")\r\n SecureField(\"Enter a password\", \r\n text: $password)\r\n .frame(width: 300, height: 30)\r\n .offset(x: offset) // amount to \"shake\"\r\n .animation(\r\n offset != 0 ? \r\n Animation.default\r\n .repeatCount(5).speed(4)\r\n :\r\n nil) // if offset is not zero, animate\r\n .border(Color.black)\r\n\r\n Button(action: {\r\n if true { // simulates login failed\r\n self.offset = 20 // set \"shake\" amount\r\n\r\n // after a delay of 0.5 seconds, set \r\n // offset to 0 to bring back the \r\n // SecureField to its original \r\n // position \r\n DispatchQueue.main.asyncAfter(\r\n deadline: .now() + 0.5) {\r\n self.offset = 0\r\n }\r\n }\r\n }) {\r\n Text(\"Login\")\r\n }\r\n }\r\n }\r\n}\r\n</pre>\n<p>The <code>SecureField </code>view has its <code>offset </code>set to a value stored in the <code>offset </code>state variable, which is in turn bound to the <code>animation()</code> modifier. If the login fails, the <code>offset </code>state variable is set to 20 and the <code>SecureField </code>will start to animate to its new location.</p>\n<p>This animation is repeated five times and, by speeding it up, the “shaking” effect is created. One side effect of the animation is that, at the end of the animation, the <code>SecureField </code>will be permanently offset by 20 points. To remedy this, half a second after the animation starts, you set the <code>offset </code>state variable back to 0, which effectively brings the <code>SecureField </code>back to its original location at the end of the animation. The following figure shows the UI containing the SecureField.</p>\n<p><img loading=\"lazy\" class=\"alignnone size-full wp-image-272600\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-securefield.jpg\" alt=\"Securefield in SwiftUI\" width=\"201\" height=\"400\" /></p>\n"},{"title":"Displaying the Share Sheet","thumb":null,"image":null,"content":"<p>The <em>Share Sheet</em> is an action sheet that shows the item that you’re sharing, with optional buttons at the bottom. Using the Share Sheet, you can easily share items of interest with other users through AirDrop, Messages, Mail, Notes, and other apps on your device.</p>\n<p>The following code snippets shows an Image view showing an image of a Macintosh SE computer. It also has a navigation button at the top showing a share icon (see the figure):</p>\n<pre class=\"“code”\">struct ContentView: View {\r\n func shareURLButton() {\r\n let img = UIImage(named: \"Macintosh_SE\")\r\n let avc = UIActivityViewController(\r\n activityItems: [img!],\r\n applicationActivities: nil)\r\n \r\n UIApplication.shared.windows.first?\r\n .rootViewController?.present(\r\n avc, animated: true, completion: nil)\r\n }\r\n\r\n var body: some View {\r\n NavigationView {\r\n Image(\"Macintosh_SE\")\r\n .resizable()\r\n .frame(width: 200.0, height: 220.0)\r\n .navigationBarItems(trailing:\r\n Button(action: {\r\n self.shareURLButton()\r\n }) {\r\n Image(systemName: \r\n \"square.and.arrow.up\")\r\n }\r\n )\r\n .navigationBarTitle(\"Share Sheet Example\")\r\n }\r\n }\r\n}\r\n</pre>\n<p>When the Share icon is tapped, the Share Sheet displays, as shown on the right side of the figure. Users will be able to copy the image, save a copy of it to the Photos app, assign it to a contact, and so on.</p>\n<p><img loading=\"lazy\" class=\"alignnone size-full wp-image-272601\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-share-sheet.jpg\" alt=\"Share Sheet\" width=\"401\" height=\"400\" /></p>\n<p class=\"article-tips tip\">If you want to allows users to save the image to the Photos app, you need to add the <code>NSPhotoLibraryAddUsageDescription</code> key to the <code>Info.plist</code> file and assign it a value.</p>\n<p> You can also make the Image view context sensitive using the contextMenu() modifier:</p>\n<pre class=\"“code”\"> var body: some View {\r\n NavigationView {\r\n Image(\"Macintosh_SE\")\r\n .resizable()\r\n .frame(width: 200.0, height: 220.0)\r\n .navigationBarItems(trailing:\r\n Button(action: {\r\n self.shareURLButton()\r\n }) {\r\n Image(systemName: \r\n \"square.and.arrow.up\")\r\n }\r\n )\r\n .contextMenu {\r\n Button(action: {\r\n self.shareURLButton()\r\n }) {\r\n Text(\"Share\")\r\n Image(systemName: \r\n \"square.and.arrow.up\")\r\n }\r\n }\r\n .navigationBarTitle(\"Share Sheet Example\")\r\n }\r\n }\r\n</pre>\n<p>The following figure shows the context menu displaying after long-pressing the image.</p>\n<p>Tapping the Share menu displays the Share Sheet.</p>\n<p><img loading=\"lazy\" class=\"alignnone size-full wp-image-272599\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-context-menu.jpg\" alt=\"Context menu Swift\" width=\"203\" height=\"400\" /></p>\n"}],"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Six months","lifeExpectancySetFrom":"2022-03-25T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":272596},{"headers":{"creationTime":"2016-03-27T16:47:37+00:00","modifiedTime":"2022-03-22T20:35:52+00:00","timestamp":"2022-09-14T18:19:29+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"Swift For Dummies Cheat Sheet","strippedTitle":"swift for dummies cheat sheet","slug":"swift-for-dummies-cheat-sheet","canonicalUrl":"","seo":{"metaDescription":"Learn some of the basics of the Swift programming language, including Swift classes and working with both Swift and Objective-C.","noIndex":0,"noFollow":0},"content":"Swift is Apple’s programming language for developers to use with iOS and OS X devices.\r\n\r\nSwift has been designed both to work alongside its predecessor, Objective-C, and to one day be Objective-C’s replacement. When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language —either Objective-C or Swift.\r\n\r\nSwift inherits much of Objective-C’s functionality — anyone comfortable with Objective-C’s types, collections, functions, classes, and flow control will be familiar with those structures in Swift, as well.","description":"Swift is Apple’s programming language for developers to use with iOS and OS X devices.\r\n\r\nSwift has been designed both to work alongside its predecessor, Objective-C, and to one day be Objective-C’s replacement. When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language —either Objective-C or Swift.\r\n\r\nSwift inherits much of Objective-C’s functionality — anyone comfortable with Objective-C’s types, collections, functions, classes, and flow control will be familiar with those structures in Swift, as well.","blurb":"","authors":[{"authorId":9263,"name":"Jesse Feiler","slug":"jesse-feiler","description":" <p><b>Jesse Feiler</b> is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast&#8217;s The Roundtable.</p>","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9263"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":145720,"title":"The Anatomy of a Swift Class","slug":"the-anatomy-of-a-swift-class","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145720"}},{"articleId":145709,"title":"Choosing How to Implement Functionality in Swift","slug":"choosing-how-to-implement-functionality-in-swift","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145709"}},{"articleId":145710,"title":"10 Tips for Switching between Objective-C and Swift","slug":"10-tips-for-switching-between-objective-c-and-swift","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145710"}},{"articleId":145711,"title":"Working with both Swift and Objective-C","slug":"working-with-both-swift-and-objective-c","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145711"}},{"articleId":145707,"title":"Building Swift Outlets and Actions with Xcode","slug":"building-swift-outlets-and-actions-with-xcode","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145707"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281876,"slug":"swift-for-dummies","isbn":"9781119022220","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119022223/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119022223/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119022223-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119022223/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119022223/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swift-for-dummies-cover-9781119022220-203x255.jpg","width":203,"height":255},"title":"Swift For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"9263\">Jesse Feiler</b></b> is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast&#8217;s The Roundtable.</p>","authors":[{"authorId":9263,"name":"Jesse Feiler","slug":"jesse-feiler","description":" <p><b>Jesse Feiler</b> is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast&#8217;s The Roundtable.</p>","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9263"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119022220&quot;]}]\" id=\"du-slot-63221b314c9b3\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119022220&quot;]}]\" id=\"du-slot-63221b314d405\"></div></div>"},"articleType":{"articleType":"Cheat Sheet","articleList":[{"articleId":145720,"title":"The Anatomy of a Swift Class","slug":"the-anatomy-of-a-swift-class","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145720"}},{"articleId":145690,"title":"How to Update Xcode for a New Swift Release","slug":"how-to-update-xcode-for-a-new-swift-release","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145690"}},{"articleId":145711,"title":"Working with both Swift and Objective-C","slug":"working-with-both-swift-and-objective-c","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/145711"}}],"content":[{"title":"The anatomy of a Swift class","thumb":null,"image":null,"content":"<p>Classes are the heart of any object-oriented programming language. Unlike classes in Objective-C and some other languages, Swift’s classes need no header declaration. Instead, you get the entire class (or structure or enumeration) definition in a format like this:</p>\n<pre class=\"code\">class MyClass {\r\n var storedNumber: Int = 0\r\n init (myNumber storedNumber: Int) {\r\n self.storedNumber = storedNumber\r\n }\r\n func simpleDescription() -&gt; String {\r\n return String(self.storedNumber)\r\n }\r\n}\r\nvar test = MyClass(myNumber: 15)\r\nprintln (\"myNumber is \" + test.simpleDescription());</pre>\n<p>The code in this example defines a class. Note the following characteristics:</p>\n<ul class=\"level-one\">\n<li>\n<p class=\"first-para\"><b>It declares a stored property.</b> It is an <span class=\"code\">Int</span> set initially to 0.</p>\n</li>\n<li>\n<p class=\"first-para\"><b>It creates an initializer that takes an </b><span class=\"code\">Int</span><b> as a parameter.</b> The external name is <span class=\"code\">myNumber</span> and the internal name is <span class=\"code\">storedNumber</span>. The initializer sets the class instance value <span class=\"code\">self.storedNumber </span>using the <span class=\"code\">storedNumber</span> parameter (with the external name <span class=\"code\">myNumber</span>).</p>\n</li>\n<li>\n<p class=\"first-para\"><b>It declares a function called </b><span class=\"code\">simpleDescription</span><b> that returns a </b><span class=\"code\">String</span><b> representation of the stored number.</b></p>\n</li>\n</ul>\n"},{"title":"How to update Xcode for a new Swift release","thumb":null,"image":null,"content":"<p>New releases of Xcode (downloadable from <a href=\"http://developer.apple.com\" target=\"_blank\" rel=\"noopener\">developer.apple.com</a> for the beta and pre-release versions and from the <a href=\"http://store.apple.com/us\" target=\"_blank\" rel=\"noopener\">Mac App Store</a> for released versions) include documentation and APIs for new versions of Swift and the Cocoa and Cocoa Touch APIs.</p>\n<p>If you need to load older versions, go to the Downloads tab at Xcode→Preferences to review what needs to be downloaded. The unchecked items are available for download. The checked items have already been downloaded.</p>\n<p><img loading=\"lazy\" src=\"https://www.dummies.com/wp-content/uploads/462615.image0.jpg\" alt=\"image0.jpg\" width=\"535\" height=\"354\" /></p>\n"},{"title":"Working with both Swift and Objective-C","thumb":null,"image":null,"content":"<p>As of the start of 2015, almost all of the Cocoa and Cocoa Touch frameworks are written in Objective-C, and Swift can use them easily. (Of course it can; this was one of Swift’s design goals.)</p>\n<p>Even so, some aspects of the frameworks work well in Swift, but perhaps not as elegantly as you might like. In particular, these include the issues involved with passing pointers (used a great deal in the Objective-C frameworks) to and from Swift.</p>\n<p>A related issue is the use of <span class=\"code\">nil</span> (as in <span class=\"code\">nil</span> pointers). Swift addresses this issue with the use of <i>optional</i> types — types such as <span class=\"code\">Int?</span>, which are related to non-optional types such as <span class=\"code\">Int</span> but which can accept the value of <span class=\"code\">nil</span>. (Sometimes optional types are called <i>nullable</i> types.) In Swift, you can <i>unwrap</i> an optional to deal directly with the underlying value that may be <span class=\"code\">nil</span>. You unwrap an optional value of type <span class=\"code\">Int?</span> by using an exclamation point, as in <span class=\"code\">myOptional!</span>.</p>\n<p class=\"Remember\">Although developers inside Apple have been working with Swift for several years, most programmers only have half a year’s experience with the new language. In this short time, many developers have remarked on the fact that you still need to know a good bit about Objective-C to use Swift.</p>\n<p class=\"Remember\">How much you’ll need to know is hard to say, since virtually everyone who uses Swift today is already highly experienced with Objective-C. The experienced coders notice the pieces of Objective-C peeking through the Swift code.</p>\n<p>If you&#8217;re starting from scratch, though, it’s fair to say you’ll need what linguists call a <i>passive</i> knowledge of Objective-C (meaning you can read and understand it) before you can develop an <i>active</i> knowledge of Swift (meaning you can read, understand, and write it).</p>\n"}],"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"One year","lifeExpectancySetFrom":"2022-03-22T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":207583},{"headers":{"creationTime":"2020-06-05T21:58:19+00:00","modifiedTime":"2022-02-14T14:18:18+00:00","timestamp":"2022-09-14T18:19:06+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"Flutter For Dummies Cheat Sheet","strippedTitle":"flutter for dummies cheat sheet","slug":"flutter-for-dummies-cheat-sheet","canonicalUrl":"","seo":{"metaDescription":"This Cheat Sheet is bursting with Flutter code, which you are welcome to claim as your own—from Hello World to Animation.","noIndex":0,"noFollow":0},"content":"Flutter's <a href=\"https://api.flutter.dev/\" target=\"_blank\" rel=\"noopener\">online documentation</a> is a great source of information, but sometimes you'd rather glance quickly at an example. This cheat sheet has some sample code. Just grab it and go!\r\n\r\n[caption id=\"attachment_271271\" align=\"alignnone\" width=\"556\"]<img class=\"size-full wp-image-271271\" src=\"https://www.dummies.com/wp-content/uploads/flutter-concept.jpg\" alt=\"Flutter UI\" width=\"556\" height=\"238\" /> ©Eny Setiyowati/Shutterstock.com[/caption]","description":"Flutter's <a href=\"https://api.flutter.dev/\" target=\"_blank\" rel=\"noopener\">online documentation</a> is a great source of information, but sometimes you'd rather glance quickly at an example. This cheat sheet has some sample code. Just grab it and go!\r\n\r\n[caption id=\"attachment_271271\" align=\"alignnone\" width=\"556\"]<img class=\"size-full wp-image-271271\" src=\"https://www.dummies.com/wp-content/uploads/flutter-concept.jpg\" alt=\"Flutter UI\" width=\"556\" height=\"238\" /> ©Eny Setiyowati/Shutterstock.com[/caption]","blurb":"","authors":[{"authorId":9069,"name":"Barry Burd","slug":"barry-burd","description":" <p><b>Dr. Barry Burd</b> holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of <i>Beginning Programming with Java For Dummies, Java for Android For Dummies,</i> and <i>Flutter For Dummies.</i></p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9069"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[],"relatedArticles":{"fromBook":[{"articleId":272261,"title":"Setting Device Orientation in Your Flutter App","slug":"setting-device-orientation-in-your-flutter-app","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/272261"}},{"articleId":272254,"title":"Using Android Studio to Develop Flutter Apps","slug":"using-android-studio-to-develop-flutter-apps","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/272254"}},{"articleId":272228,"title":"Flutter Animation: Making Size and Color Changes","slug":"flutter-animation-making-size-and-color-changes","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/272228"}},{"articleId":272214,"title":"Running Your First Flutter App in Android Studio","slug":"running-your-first-flutter-app-in-android-studio","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/272214"}},{"articleId":272026,"title":"What You Need to Program Flutter Apps: Installing the Necessary Software","slug":"what-you-need-to-program-flutter-apps-installing-the-necessary-software","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/272026"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274224,"title":"How to Use UIKit in SwiftUI","slug":"how-to-use-uikit-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274224"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281723,"slug":"flutter-for-dummies","isbn":"9781119612582","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119612586/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119612586/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119612586-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119612586/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119612586/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/flutter-for-dummies-cover-9781119612582-203x255.jpg","width":203,"height":255},"title":"Flutter For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b>Dr. <b data-author-id=\"9069\">Barry Burd</b></b> holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of <i>Beginning Programming with Java For Dummies, Java for Android For Dummies,</i> and <i>Flutter For Dummies.</i></p>","authors":[{"authorId":9069,"name":"Barry Burd","slug":"barry-burd","description":" <p><b>Dr. Barry Burd</b> holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of <i>Beginning Programming with Java For Dummies, Java for Android For Dummies,</i> and <i>Flutter For Dummies.</i></p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/9069"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119612582&quot;]}]\" id=\"du-slot-63221b1a63680\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119612582&quot;]}]\" id=\"du-slot-63221b1a64034\"></div></div>"},"articleType":{"articleType":"Cheat Sheet","articleList":[{"articleId":0,"title":"","slug":null,"categoryList":[],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/"}}],"content":[{"title":"A \"Hello World\" Dart Program","thumb":null,"image":null,"content":"<pre class=\"code\">main() =&gt; print('Hello World');</pre>\n"},{"title":"A \"Hello World\" Flutter Program","thumb":null,"image":null,"content":"<pre class=\"“code”\">import 'package:flutter/material.dart';\r\n\r\nmain() =&gt; runApp(HelloApp());\r\n\r\nclass HelloApp extends StatelessWidget {\r\n Widget build(BuildContext context) {\r\n return MaterialApp(\r\n home: Material(\r\n child: Text(\"Hello world!\"),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"A Simple Scaffold","thumb":null,"image":null,"content":"<pre class=\"“code”\">Scaffold(\r\n appBar: AppBar(\r\n title: Text(\"I'm aan AppBar.\"),\r\n ),\r\n body: Center(\r\n child: Text(\"I'm a Text widget.\"),\r\n ),\r\n floatingActionButton: FloatingActionButton(\r\n child: Icon(Icons.ac_unit),\r\n ),\r\n drawer: Drawer(\r\n child: Center(child: Text(\"I'm a drawer.\")),\r\n ),\r\n)\r\n\r\n</pre>\n"},{"title":"A Cupertino App","thumb":null,"image":null,"content":"<pre class=\"“code”\">import 'package:flutter/cupertino.dart';\r\n\r\nvoid main() =&gt; runApp(CupterinoApp());\r\n\r\nclass CupterinoApp extends StatelessWidget {\r\n @override\r\n Widget build(BuildContext context) {\r\n return CupertinoApp(\r\n home: CupertinoPageScaffold(\r\n navigationBar: CupertinoNavigationBar(\r\n backgroundColor: Color.fromRGBO(66, 165, 245, 1.0),\r\n middle: Text(\"I'm a navigation bar\"),\r\n ),\r\n child: Center(\r\n child: Text('Hello from Cupertino, Californa!'),\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"A Column","thumb":null,"image":null,"content":"<pre class=\"“code”\">Column(\r\n mainAxisAlignment: MainAxisAlignment.center,\r\n children: [\r\n Text(\"I'm on top.\"),\r\n Text(\"I'm in the middle.\"),\r\n Text(\"I'm the bottom.\"),\r\n ],\r\n)\r\n</pre>\n"},{"title":"Responding to a Button Press","thumb":null,"image":null,"content":"<pre class=\"“code”\">import 'package:flutter/material.dart';\r\n\r\nvoid main() =&gt; runApp(ButtonDemo());\r\n\r\nclass ButtonDemo extends StatelessWidget {\r\n Widget build(BuildContext context) {\r\n return MaterialApp(\r\n home: MyHomePage(),\r\n );\r\n }\r\n}\r\n\r\nclass MyHomePage extends StatefulWidget {\r\n _MyHomePageState createState() =&gt; _MyHomePageState();\r\n}\r\n\r\nclass _MyHomePageState extends State {\r\n String _whatToDisplay;\r\n void initState() {\r\n _whatToDisplay = 'Click Me';\r\n }\r\n\r\n void _doSomething() {\r\n setState(() {\r\n _whatToDisplay = 'Thank you for clicking';\r\n });\r\n }\r\n\r\n Widget build(BuildContext context) {\r\n return Scaffold(\r\n body: Center(\r\n child: RaisedButton(\r\n child: Text(_whatToDisplay),\r\n onPressed: _doSomething,\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"Some Useful Layout Widgets","thumb":null,"image":null,"content":"<pre class=\"“code”\">Material(\r\n child: SafeArea(\r\n child: Column(\r\n children: [\r\n Expanded(\r\n child: Container(\r\n height: 50.0,\r\n color: Colors.blue,\r\n ),\r\n ),\r\n SizedBox(\r\n height: 50.0,\r\n ),\r\n Container(\r\n alignment: Alignment.bottomRight,\r\n height: 100.0,\r\n color: Colors.blue,\r\n child: Padding(\r\n padding: const EdgeInsets.all(20.0),\r\n child: Text(\r\n 'Hello',\r\n style: TextStyle(backgroundColor: Colors.red),\r\n ),\r\n ),\r\n ),\r\n ],\r\n ),\r\n ),\r\n)\r\n</pre>\n"},{"title":"A Text Field","thumb":null,"image":null,"content":"<pre class=\"“code”\">class _MyHomePageState extends State {\r\n final _myController = TextEditingController();\r\n\r\n @override\r\n void dispose() {\r\n _myController.dispose();\r\n super.dispose();\r\n }\r\n\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Center(\r\n child: Column(\r\n mainAxisAlignment: MainAxisAlignment.center,\r\n children: [\r\n TextField(\r\n decoration: InputDecoration(labelText: \"Type something:\"),\r\n controller: _myController,\r\n ),\r\n RaisedButton(\r\n child: Text(\"UPPERCASE\"),\r\n onPressed: () =&gt;\r\n _myController.text = _myController.text.toUpperCase(),\r\n ),\r\n ],\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"A Slider","thumb":null,"image":null,"content":"<pre class=\"“code”\">class _MyHomePageState extends State {\r\n double _sliderValue = 1.0;\r\n\r\n void _refreshSlider(double newValue) {\r\n setState(() {\r\n _sliderValue = newValue;\r\n });\r\n }\r\n\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Center(\r\n child: Column(\r\n mainAxisAlignment: MainAxisAlignment.center,\r\n children: [\r\n Text(_sliderValue.toStringAsFixed(2)),\r\n Slider(\r\n value: _sliderValue,\r\n onChanged: _refreshSlider,\r\n min: 1.0,\r\n max: 10.0,\r\n )\r\n ],\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"Radio Buttons","thumb":null,"image":null,"content":"<pre class=\"code\">class _MyHomePageState extends State {\r\n int _radioValue;\r\n\r\n void _refreshRadio(int newValue) {\r\n setState(() {\r\n _radioValue = newValue;\r\n });\r\n }\r\n\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Center(\r\n child: Column(\r\n mainAxisAlignment: MainAxisAlignment.center,\r\n children: [\r\n Text(_radioValue?.toString() ?? 'Select One'),\r\n Row(\r\n mainAxisAlignment: MainAxisAlignment.center,\r\n children: [\r\n Text('0'),\r\n Radio(\r\n value: 0,\r\n groupValue: _radioValue,\r\n onChanged: _refreshRadio),\r\n Text('1'),\r\n Radio(\r\n value: 1,\r\n groupValue: _radioValue,\r\n onChanged: _refreshRadio),\r\n Text('2'),\r\n Radio(\r\n value: 2,\r\n groupValue: _radioValue,\r\n onChanged: _refreshRadio,\r\n )\r\n ],\r\n ),\r\n ],\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"Basic Navigation","thumb":null,"image":null,"content":"<pre class=\"code\">class FirstPage extends StatelessWidget {\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Center(\r\n child: RaisedButton(\r\n child: Text('Go to second page'),\r\n onPressed: () {\r\n Navigator.push(\r\n context,\r\n MaterialPageRoute(\r\n builder: (context) =&gt; SecondPage(),\r\n ),\r\n );\r\n },\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n\r\nclass SecondPage extends StatelessWidget {\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Center(\r\n child: RaisedButton(\r\n onPressed: () {\r\n Navigator.pop(context);\r\n },\r\n child: Text('Go back!'),\r\n ),\r\n ),\r\n );\r\n }\r\n}\r\n</pre>\n"},{"title":"A List","thumb":null,"image":null,"content":"<pre class=\"code\">List movieName = [\r\n \"Casablanca\",\r\n \"Citizen Kane\",\r\n \"Lawrence of Arabia\",\r\n];\r\n\r\nListView.builder(\r\n itemCount: movieName.length,\r\n itemBuilder: (context, index) {\r\n return ListTile(\r\n title: Text(movieName[index]),\r\n onTap: () =&gt; _goToDetailPage(movieName[index]));\r\n },\r\n)\r\n</pre>\n"},{"title":"Animation","thumb":null,"image":null,"content":"<pre class=\"code\">class MyHomePageState extends State\r\n with SingleTickerProviderStateMixin {\r\n Animation animation;\r\n AnimationController controller;\r\n\r\n @override\r\n void initState() {\r\n super.initState();\r\n controller =\r\n AnimationController(duration: const Duration(seconds: 3), vsync: this);\r\n animation = Tween(begin: 100.0, end: 500.0).animate(controller)\r\n ..addListener(() {\r\n setState(() {});\r\n });\r\n controller.forward();\r\n }\r\n\r\n @override\r\n Widget build(BuildContext context) {\r\n return Material(\r\n child: Stack(\r\n children: [\r\n Positioned(\r\n left: 150.0,\r\n top: animation.value,\r\n child: Icon(\r\n Icons.music_note,\r\n size: 70.0,\r\n ),\r\n ),\r\n ],\r\n ),\r\n );\r\n }\r\n\r\n @override\r\n void dispose() {\r\n controller.dispose();\r\n super.dispose();\r\n }\r\n}\r\n</pre>\n"}],"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":"Six months","lifeExpectancySetFrom":"2022-02-14T00:00:00+00:00","dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":271270},{"headers":{"creationTime":"2020-10-29T19:11:05+00:00","modifiedTime":"2021-08-26T13:10:49+00:00","timestamp":"2022-09-14T18:18:33+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"App Development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"},"slug":"app-development","categoryId":33594}],"title":"How to Use UIKit in SwiftUI","strippedTitle":"how to use uikit in swiftui","slug":"how-to-use-uikit-in-swiftui","canonicalUrl":"","seo":{"metaDescription":"It's time to learn how to use UIKit with SwiftUI. Get the scoop and be a better developer with this guide from Dummies.com.","noIndex":0,"noFollow":0},"content":"Did you know you can use UIKit in <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/?keyword=swiftui&index=1&isSearch=1\">SwiftUI</a>? It’s true! When you develop iOS apps using Storyboard in Xcode, you use the <code>UIKit</code> for all UI matters. <code>UIKit</code> is the framework that forms the core components of all iOS applications. Among all the classes in the<code> UIKit</code>, view and view controllers are the most commonly used classes.\r\n\r\nView controllers (<code>UIViewController</code>) play a crucial role in your apps — they act as the skeleton of your application. A view controller is basically a class that manages a set of views (to display to the user), while coordinating with model (data) objects.\r\n<p class=\"article-tips tech\">Because the view controller is connected to your Storyboard (an external file), it has very little control of what’s happening on the view side of things (and vice versa). You may be familiar with this — connect an event in your Interface Builder to a function in your code in Swift and then later on you delete the function. However, the Interface Builder doesn’t know that your function is now gone, and all hell will break loose when that event is invoked during runtime. This problem is precisely what SwiftUI tries to resolve.</p>\r\nThe various widgets — such as <code>Button</code>, <code>Label</code>, <code>TextField</code>, and <code>Switch</code> — are represented by the subclasses of <code>UIView</code>.\r\n<p class=\"article-tips tip\">This article discusses how to use UIKit within a SwiftUI project, but the converse is also true — <a href=\"http://www.answertopia.com/swiftui/integrating-swiftui-with-uikit\">you would also want to use SwiftUI in an existing UIKit project</a>. Note that after you add SwiftUI to your UIKit project, your apps will only run on iOS 13.0 and later, macOS 10.15 and later, tvOS 13.0 and later, and watchOS 6.0 and later.</p>\r\nThe image below shows a <code>UIViewController</code> instances containing a number of <code>UIView</code> instances.\r\n\r\n[caption id=\"attachment_274225\" align=\"aligncenter\" width=\"264\"]<img class=\"wp-image-274225 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-legacy-view-264x586.jpg\" alt=\"SwiftUI Legacy View\" width=\"264\" height=\"586\" /> Legacy View controller and views.[/caption]\r\n\r\n \r\n<h2 id=\"tab1\" ><a name=\"_Toc32674002\"></a>Understanding the UIKit View Controller life cycle</h2>\r\nIn order to handle the various states of a view controller, a view controller has a set of events, known as the life cycle of a view controller. The life cycle of a view controller has a variety of events, including (but not limited to) the following:\r\n<ul>\r\n \t<li><code>viewDidLoad</code>: Called after the controller’s view is loaded into memory</li>\r\n \t<li><code>loadView</code>: Creates the view that the controller manages</li>\r\n \t<li><code>viewWillAppear</code>: Notifies the view controller that its view is about to be added to a view hierarchy</li>\r\n \t<li><code>viewDidAppear</code>: Notifies the view controller that its view was added to a view hierarchy</li>\r\n \t<li><code>viewWillDisappear</code>: Notifies the view controller that its view is about to be removed from a view hierarchy</li>\r\n \t<li><code>viewDidDisappear</code>: Notifies the view controller that its view was removed from a view hierarchy</li>\r\n \t<li><code>didReceiveMemoryWarning</code>: Sent to the view controller when the app receives a memory warning</li>\r\n</ul>\r\nThe following Swift code shows how to handle the various events of a view controller.\r\n<pre class=\"code\">import UIKit\r\n\r\nclass ViewController: UIViewController {\r\n\r\n override func viewDidLoad() {\r\n super.viewDidLoad()\r\n }\r\n\r\n override func loadView() {\r\n super.loadView()\r\n }\r\n\r\n override func viewWillAppear(_ animated: Bool) {\r\n super.viewWillAppear(animated)\r\n }\r\n\r\n override func viewDidAppear(_ animated: Bool) {\r\n super.viewDidAppear(animated)\r\n }\r\n\r\n override func viewWillDisappear(_ animated: Bool) {\r\n super.viewWillDisappear(animated)\r\n }\r\n\r\n override func viewDidDisappear(_ animated: Bool) {\r\n super.viewDidDisappear(animated)\r\n }\r\n\r\n override func didReceiveMemoryWarning() {\r\n super.didReceiveMemoryWarning()\r\n }\r\n}</pre>\r\nThe various events are fired during the lifetime of the view controller. For example, you often initialize your variables during the <code>viewDidLoad</code> event (it fires only once when the view controller is first loaded). If you needed to update the view whenever the view controller appears, you would perform the updates in the <code>viewDidAppear</code> event (fired every time the view comes to the foreground). Or if you need to build the UI dynamically during loading time, you can do it in the <code>loadView</code> event.\r\n<h2 id=\"tab2\" ><a name=\"_Toc32674003\"></a>Understanding the SwiftUI view life cycle</h2>\r\nCompared to the <code>UIViewControlle</code>r life cycles, the life cycle of a view in SwiftUI is much simpler and more straightforward. In SwiftUI, there is no concept of a view controller. Instead, everything is a <code>View</code>.\r\n\r\nIn SwiftUI, <code>View</code> has only two events:\r\n<ul>\r\n \t<li style=\"list-style-type: none;\">\r\n<ul>\r\n \t<li><code>onAppear</code></li>\r\n \t<li><code>onDisappear</code></li>\r\n</ul>\r\n</li>\r\n</ul>\r\nYou can attach these two events to any views, and SwiftUI will execute them when they occur.\r\n<h3><a name=\"_Toc32674004\"></a>Working with the onAppear and onDisappear events in SwiftUI</h3>\r\nWhen a view appears, the <code>onAppear</code> event will be fired. Likewise, when the view disappears, the <code>onDisappear</code> event will be fired.\r\n\r\nLet’s illustrate the use of the <code>onAppear</code> event:\r\n<pre class=\"code\"> func fetchData() {\r\n ...\r\n }\r\n\r\n var body: some View {\r\n List(articles, id: \\.url) { item in\r\n VStack(alignment: .leading) {\r\n Text(item.title)\r\n .font(.headline)\r\n Text(item.description ?? \"\")\r\n .font(.footnote)\r\n }\r\n }.onAppear(perform: fetchData)\r\n }</pre>\r\nWhen the<code> List</code> view first appears, it will fire the <code>onAppear</code> event, which you then use to call the <code>fetchData()</code> function to load data from the web. For that example, it’s quite straightforward to understand when the <code>onAppear</code> event fires.\r\n\r\nA more involved example would be one comprising a<code> NavigationView</code> and a <code>TabView</code>. The following image shows an example where the <code>ContentView</code> contains a <code>TabView</code>, which in turn also contains a<code> NavigationView</code>.\r\n\r\n[caption id=\"attachment_274226\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274226 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-views.png\" alt=\"SwiftUI views\" width=\"556\" height=\"535\" /> Three views in SwiftUI embedded within NavigationView and TabView.[/caption]\r\n\r\n \r\n\r\nThe following Swift code snippet shows the implementation of the three views that you’ve just seen. To understand when the <code>onAppear</code> and <code>onDisappear</code> events are fired when the user moves from one screen to another, you insert <code>print</code> statements, as shown in the following code:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct View1: View {\r\n var body: some View {\r\n Text(\"View1\")\r\n .onAppear{\r\n print(\"onAppear in View1\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in View1\")\r\n }\r\n }\r\n}\r\n\r\nstruct View2: View {\r\n var body: some View {\r\n Text(\"View2\")\r\n .onAppear{\r\n print(\"onAppear in View2\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in View2\")\r\n }\r\n }\r\n}\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n TabView {\r\n NavigationView{\r\n NavigationLink(destination: View1()) {\r\n Text(\"Next\")\r\n }\r\n }.onAppear{\r\n print(\"onAppear in ContentView\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in ContentView\")\r\n }\r\n .tabItem {\r\n Image(systemName:\r\n \"viewfinder.circle.fill\")\r\n Text(\"ContentView\")\r\n }\r\n\r\n View2()\r\n .tabItem {\r\n Image(systemName: \"camera.viewfinder\")\r\n Text(\"View2\")\r\n }\r\n }\r\n .onAppear{\r\n print(\"onAppear in TabView\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in TabView\")\r\n }\r\n }\r\n}</pre>\r\nWhen the app is first loaded, you see the following outputs:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView</pre>\r\nYou can see that <code>TabView</code> first appeared, followed by <code>ContentView</code>. When you click the Next button, it navigates to <code>View1</code>.\r\n\r\nThe following statement in bold shows the additional statement printed:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\n&lt;strong&gt;onAppear in View1&lt;/strong&gt;</pre>\r\nEven though <code>ContentView</code> is now hidden, it hasn’t disappeared yet (because there is no output indicating its disappearance).\r\n\r\nNow, click the Back button to go back to ContentView. This time, you see the following additional output:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\n&lt;strong&gt;onDisappear in View1&lt;/strong&gt;</pre>\r\nSo <code>View1</code> has disappeared. Click the <code>View2</code> item on the tab bar. <code>View2</code> is now loaded.\r\n\r\nHere’s the output:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\nonDisappear in View1\r\n&lt;strong&gt;onDisappear in ContentView&lt;/strong&gt;\r\n&lt;strong&gt;onAppear in View2&lt;/strong&gt;</pre>\r\nNow <code>ContentView</code> has disappeared and <code>View2</code> appears.\r\n\r\nFinally, click <code>ContentView</code> item on the tab bar and notice that<code> View2</code> has disappeared and <code>ContentView</code> has appeared again:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\nonDisappear in View1\r\nonDisappear in ContentView\r\nonAppear in View2\r\n&lt;strong&gt;onDisappear in View2&lt;/strong&gt;\r\n&lt;strong&gt;onAppear in ContentView&lt;/strong&gt;</pre>\r\nAs you can see from the example, the <code>onAppear</code> event allows you to know when a view comes onscreen. This is useful in cases where you want to load data on demand. Suppose you have a tabbed application with five tab items and each of these tab pages separately loads data from the web. It would be useful to load the data only when the user views a particular page. Otherwise, the entire iOS app would feel sluggish when it tries to load all the data at the same time when the app starts up.\r\n<h3><a name=\"_Toc32674005\"></a>Instantiating properties of a view in SwiftUI</h3>\r\nBesides understanding when the two events are fired, it’s also important to understand how <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/?keyword=swiftui&index=2&isSearch=1\">SwiftUI</a> processes a <code>View</code> when it’s created and the sequences in which properties and binding objects are processed.\r\n\r\nYou may already know that the <code>View</code> is a <code>struct</code>. Very often, views have properties, which allows you to pass in additional information to customize the behaviors of views.\r\n\r\nConsider the following simple example of a <code>View</code> named <code>MyView</code>:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n var greetings: String\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nIn the<code> MyView </code>struct, you have a property named <code>greetings</code>. It is of type<code> String</code>, but it hasn’t been initialized yet.\r\n\r\nWhen you try to use<code> MyView</code>, as in the following code snippet,\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack{\r\n MyView(\"Hello, World!\")\r\n }\r\n }\r\n}</pre>\r\nYou get the error: <code>Missing argument label 'greetings:' in call</code>. This is because you need to initialize the value of the greetings property in MyView, which is the first thing the compiler tries to do when instantiating the struct.\r\n\r\nTo fix this, pass in the argument for the <code>greetings</code> property when calling <code>MyView</code>, like this:\r\n<pre class=\"code\"> MyView(greetings: \"Hello, World!\")</pre>\r\n<h3><a name=\"_Toc32674006\"></a>Using initializers in a SwiftUI view</h3>\r\nStructs can also have initializers (constructors). If MyView has an explicit initializer, like the following:\r\n<pre class=\"code\">struct MyView: View {\r\n var greetings: String\r\n\r\n init(_ str:String) {\r\n self.greetings = str\r\n }\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nThen <code>greetings</code> must be initialized via the initializer for <code>MyView</code>:\r\n<pre class=\"code\">MyView(\"Hello, World!\")</pre>\r\n<h3><a name=\"_Toc32674007\"></a>Using binding variables in a SwiftUI view</h3>\r\nIf <code>MyView</code> has a <code>@Binding</code> variable, like this:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n @Binding var text: String\r\n\r\n var greetings: String\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}&lt;/pre\r\n\r\n\r\nThen you have to initialize it through the parameters:</pre>\r\n<pre class=\"code\">struct ContentView: View {\r\n @State var text: String = \"\"\r\n var body: some View {\r\n MyView(greetings: \"Hello, World!\", text: $text)\r\n }\r\n}</pre>\r\n<p class=\"article-tips tip\">Note that the binding variable argument must come after the <code>greetings</code> argument.</p>\r\nIf <code>MyView</code> has an explicit initializer, you have to specify the type of the <code>Binding</code> object in your initializer, like this:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n @Binding var text: String\r\n\r\n var greetings: String\r\n\r\n init(_ str:String, _ text: Binding) {\r\n self.greetings = str\r\n self._text = text\r\n }\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nObserve that the <code>text @Binding</code> variable has an underscore (_) in the initializer:\r\n<pre class=\"code\"> self._text = text</pre>\r\nAnd now when you create an instance of the MyView struct, you can bind the state variable through the initializer, like this:\r\n<pre class=\"code\">MyView(\"Hello, World!\", &lt;strong&gt;$text&lt;/strong&gt;)</pre>\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/10-great-swiftui-resources/?keyword=swiftui&index=1&isSearch=1\">SwiftUI resources</a>.","description":"Did you know you can use UIKit in <a href=\"https://www.dummies.com/programming/macintosh/swift/swiftui-for-dummies-cheat-sheet/?keyword=swiftui&index=1&isSearch=1\">SwiftUI</a>? It’s true! When you develop iOS apps using Storyboard in Xcode, you use the <code>UIKit</code> for all UI matters. <code>UIKit</code> is the framework that forms the core components of all iOS applications. Among all the classes in the<code> UIKit</code>, view and view controllers are the most commonly used classes.\r\n\r\nView controllers (<code>UIViewController</code>) play a crucial role in your apps — they act as the skeleton of your application. A view controller is basically a class that manages a set of views (to display to the user), while coordinating with model (data) objects.\r\n<p class=\"article-tips tech\">Because the view controller is connected to your Storyboard (an external file), it has very little control of what’s happening on the view side of things (and vice versa). You may be familiar with this — connect an event in your Interface Builder to a function in your code in Swift and then later on you delete the function. However, the Interface Builder doesn’t know that your function is now gone, and all hell will break loose when that event is invoked during runtime. This problem is precisely what SwiftUI tries to resolve.</p>\r\nThe various widgets — such as <code>Button</code>, <code>Label</code>, <code>TextField</code>, and <code>Switch</code> — are represented by the subclasses of <code>UIView</code>.\r\n<p class=\"article-tips tip\">This article discusses how to use UIKit within a SwiftUI project, but the converse is also true — <a href=\"http://www.answertopia.com/swiftui/integrating-swiftui-with-uikit\">you would also want to use SwiftUI in an existing UIKit project</a>. Note that after you add SwiftUI to your UIKit project, your apps will only run on iOS 13.0 and later, macOS 10.15 and later, tvOS 13.0 and later, and watchOS 6.0 and later.</p>\r\nThe image below shows a <code>UIViewController</code> instances containing a number of <code>UIView</code> instances.\r\n\r\n[caption id=\"attachment_274225\" align=\"aligncenter\" width=\"264\"]<img class=\"wp-image-274225 size-large\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-legacy-view-264x586.jpg\" alt=\"SwiftUI Legacy View\" width=\"264\" height=\"586\" /> Legacy View controller and views.[/caption]\r\n\r\n \r\n<h2 id=\"tab1\" ><a name=\"_Toc32674002\"></a>Understanding the UIKit View Controller life cycle</h2>\r\nIn order to handle the various states of a view controller, a view controller has a set of events, known as the life cycle of a view controller. The life cycle of a view controller has a variety of events, including (but not limited to) the following:\r\n<ul>\r\n \t<li><code>viewDidLoad</code>: Called after the controller’s view is loaded into memory</li>\r\n \t<li><code>loadView</code>: Creates the view that the controller manages</li>\r\n \t<li><code>viewWillAppear</code>: Notifies the view controller that its view is about to be added to a view hierarchy</li>\r\n \t<li><code>viewDidAppear</code>: Notifies the view controller that its view was added to a view hierarchy</li>\r\n \t<li><code>viewWillDisappear</code>: Notifies the view controller that its view is about to be removed from a view hierarchy</li>\r\n \t<li><code>viewDidDisappear</code>: Notifies the view controller that its view was removed from a view hierarchy</li>\r\n \t<li><code>didReceiveMemoryWarning</code>: Sent to the view controller when the app receives a memory warning</li>\r\n</ul>\r\nThe following Swift code shows how to handle the various events of a view controller.\r\n<pre class=\"code\">import UIKit\r\n\r\nclass ViewController: UIViewController {\r\n\r\n override func viewDidLoad() {\r\n super.viewDidLoad()\r\n }\r\n\r\n override func loadView() {\r\n super.loadView()\r\n }\r\n\r\n override func viewWillAppear(_ animated: Bool) {\r\n super.viewWillAppear(animated)\r\n }\r\n\r\n override func viewDidAppear(_ animated: Bool) {\r\n super.viewDidAppear(animated)\r\n }\r\n\r\n override func viewWillDisappear(_ animated: Bool) {\r\n super.viewWillDisappear(animated)\r\n }\r\n\r\n override func viewDidDisappear(_ animated: Bool) {\r\n super.viewDidDisappear(animated)\r\n }\r\n\r\n override func didReceiveMemoryWarning() {\r\n super.didReceiveMemoryWarning()\r\n }\r\n}</pre>\r\nThe various events are fired during the lifetime of the view controller. For example, you often initialize your variables during the <code>viewDidLoad</code> event (it fires only once when the view controller is first loaded). If you needed to update the view whenever the view controller appears, you would perform the updates in the <code>viewDidAppear</code> event (fired every time the view comes to the foreground). Or if you need to build the UI dynamically during loading time, you can do it in the <code>loadView</code> event.\r\n<h2 id=\"tab2\" ><a name=\"_Toc32674003\"></a>Understanding the SwiftUI view life cycle</h2>\r\nCompared to the <code>UIViewControlle</code>r life cycles, the life cycle of a view in SwiftUI is much simpler and more straightforward. In SwiftUI, there is no concept of a view controller. Instead, everything is a <code>View</code>.\r\n\r\nIn SwiftUI, <code>View</code> has only two events:\r\n<ul>\r\n \t<li style=\"list-style-type: none;\">\r\n<ul>\r\n \t<li><code>onAppear</code></li>\r\n \t<li><code>onDisappear</code></li>\r\n</ul>\r\n</li>\r\n</ul>\r\nYou can attach these two events to any views, and SwiftUI will execute them when they occur.\r\n<h3><a name=\"_Toc32674004\"></a>Working with the onAppear and onDisappear events in SwiftUI</h3>\r\nWhen a view appears, the <code>onAppear</code> event will be fired. Likewise, when the view disappears, the <code>onDisappear</code> event will be fired.\r\n\r\nLet’s illustrate the use of the <code>onAppear</code> event:\r\n<pre class=\"code\"> func fetchData() {\r\n ...\r\n }\r\n\r\n var body: some View {\r\n List(articles, id: \\.url) { item in\r\n VStack(alignment: .leading) {\r\n Text(item.title)\r\n .font(.headline)\r\n Text(item.description ?? \"\")\r\n .font(.footnote)\r\n }\r\n }.onAppear(perform: fetchData)\r\n }</pre>\r\nWhen the<code> List</code> view first appears, it will fire the <code>onAppear</code> event, which you then use to call the <code>fetchData()</code> function to load data from the web. For that example, it’s quite straightforward to understand when the <code>onAppear</code> event fires.\r\n\r\nA more involved example would be one comprising a<code> NavigationView</code> and a <code>TabView</code>. The following image shows an example where the <code>ContentView</code> contains a <code>TabView</code>, which in turn also contains a<code> NavigationView</code>.\r\n\r\n[caption id=\"attachment_274226\" align=\"aligncenter\" width=\"556\"]<img class=\"wp-image-274226 size-full\" src=\"https://www.dummies.com/wp-content/uploads/swiftui-views.png\" alt=\"SwiftUI views\" width=\"556\" height=\"535\" /> Three views in SwiftUI embedded within NavigationView and TabView.[/caption]\r\n\r\n \r\n\r\nThe following Swift code snippet shows the implementation of the three views that you’ve just seen. To understand when the <code>onAppear</code> and <code>onDisappear</code> events are fired when the user moves from one screen to another, you insert <code>print</code> statements, as shown in the following code:\r\n<pre class=\"code\">import SwiftUI\r\n\r\nstruct View1: View {\r\n var body: some View {\r\n Text(\"View1\")\r\n .onAppear{\r\n print(\"onAppear in View1\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in View1\")\r\n }\r\n }\r\n}\r\n\r\nstruct View2: View {\r\n var body: some View {\r\n Text(\"View2\")\r\n .onAppear{\r\n print(\"onAppear in View2\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in View2\")\r\n }\r\n }\r\n}\r\n\r\nstruct ContentView: View {\r\n var body: some View {\r\n TabView {\r\n NavigationView{\r\n NavigationLink(destination: View1()) {\r\n Text(\"Next\")\r\n }\r\n }.onAppear{\r\n print(\"onAppear in ContentView\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in ContentView\")\r\n }\r\n .tabItem {\r\n Image(systemName:\r\n \"viewfinder.circle.fill\")\r\n Text(\"ContentView\")\r\n }\r\n\r\n View2()\r\n .tabItem {\r\n Image(systemName: \"camera.viewfinder\")\r\n Text(\"View2\")\r\n }\r\n }\r\n .onAppear{\r\n print(\"onAppear in TabView\")\r\n }\r\n .onDisappear{\r\n print(\"onDisappear in TabView\")\r\n }\r\n }\r\n}</pre>\r\nWhen the app is first loaded, you see the following outputs:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView</pre>\r\nYou can see that <code>TabView</code> first appeared, followed by <code>ContentView</code>. When you click the Next button, it navigates to <code>View1</code>.\r\n\r\nThe following statement in bold shows the additional statement printed:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\n&lt;strong&gt;onAppear in View1&lt;/strong&gt;</pre>\r\nEven though <code>ContentView</code> is now hidden, it hasn’t disappeared yet (because there is no output indicating its disappearance).\r\n\r\nNow, click the Back button to go back to ContentView. This time, you see the following additional output:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\n&lt;strong&gt;onDisappear in View1&lt;/strong&gt;</pre>\r\nSo <code>View1</code> has disappeared. Click the <code>View2</code> item on the tab bar. <code>View2</code> is now loaded.\r\n\r\nHere’s the output:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\nonDisappear in View1\r\n&lt;strong&gt;onDisappear in ContentView&lt;/strong&gt;\r\n&lt;strong&gt;onAppear in View2&lt;/strong&gt;</pre>\r\nNow <code>ContentView</code> has disappeared and <code>View2</code> appears.\r\n\r\nFinally, click <code>ContentView</code> item on the tab bar and notice that<code> View2</code> has disappeared and <code>ContentView</code> has appeared again:\r\n<pre class=\"code\">onAppear in TabView\r\nonAppear in ContentView\r\nonAppear in View1\r\nonDisappear in View1\r\nonDisappear in ContentView\r\nonAppear in View2\r\n&lt;strong&gt;onDisappear in View2&lt;/strong&gt;\r\n&lt;strong&gt;onAppear in ContentView&lt;/strong&gt;</pre>\r\nAs you can see from the example, the <code>onAppear</code> event allows you to know when a view comes onscreen. This is useful in cases where you want to load data on demand. Suppose you have a tabbed application with five tab items and each of these tab pages separately loads data from the web. It would be useful to load the data only when the user views a particular page. Otherwise, the entire iOS app would feel sluggish when it tries to load all the data at the same time when the app starts up.\r\n<h3><a name=\"_Toc32674005\"></a>Instantiating properties of a view in SwiftUI</h3>\r\nBesides understanding when the two events are fired, it’s also important to understand how <a href=\"https://www.dummies.com/programming/macintosh/9-swiftui-tips-and-tricks/?keyword=swiftui&index=2&isSearch=1\">SwiftUI</a> processes a <code>View</code> when it’s created and the sequences in which properties and binding objects are processed.\r\n\r\nYou may already know that the <code>View</code> is a <code>struct</code>. Very often, views have properties, which allows you to pass in additional information to customize the behaviors of views.\r\n\r\nConsider the following simple example of a <code>View</code> named <code>MyView</code>:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n var greetings: String\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nIn the<code> MyView </code>struct, you have a property named <code>greetings</code>. It is of type<code> String</code>, but it hasn’t been initialized yet.\r\n\r\nWhen you try to use<code> MyView</code>, as in the following code snippet,\r\n<pre class=\"code\">struct ContentView: View {\r\n var body: some View {\r\n VStack{\r\n MyView(\"Hello, World!\")\r\n }\r\n }\r\n}</pre>\r\nYou get the error: <code>Missing argument label 'greetings:' in call</code>. This is because you need to initialize the value of the greetings property in MyView, which is the first thing the compiler tries to do when instantiating the struct.\r\n\r\nTo fix this, pass in the argument for the <code>greetings</code> property when calling <code>MyView</code>, like this:\r\n<pre class=\"code\"> MyView(greetings: \"Hello, World!\")</pre>\r\n<h3><a name=\"_Toc32674006\"></a>Using initializers in a SwiftUI view</h3>\r\nStructs can also have initializers (constructors). If MyView has an explicit initializer, like the following:\r\n<pre class=\"code\">struct MyView: View {\r\n var greetings: String\r\n\r\n init(_ str:String) {\r\n self.greetings = str\r\n }\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nThen <code>greetings</code> must be initialized via the initializer for <code>MyView</code>:\r\n<pre class=\"code\">MyView(\"Hello, World!\")</pre>\r\n<h3><a name=\"_Toc32674007\"></a>Using binding variables in a SwiftUI view</h3>\r\nIf <code>MyView</code> has a <code>@Binding</code> variable, like this:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n @Binding var text: String\r\n\r\n var greetings: String\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}&lt;/pre\r\n\r\n\r\nThen you have to initialize it through the parameters:</pre>\r\n<pre class=\"code\">struct ContentView: View {\r\n @State var text: String = \"\"\r\n var body: some View {\r\n MyView(greetings: \"Hello, World!\", text: $text)\r\n }\r\n}</pre>\r\n<p class=\"article-tips tip\">Note that the binding variable argument must come after the <code>greetings</code> argument.</p>\r\nIf <code>MyView</code> has an explicit initializer, you have to specify the type of the <code>Binding</code> object in your initializer, like this:\r\n<pre class=\"code\">struct MyView: View {\r\n\r\n @Binding var text: String\r\n\r\n var greetings: String\r\n\r\n init(_ str:String, _ text: Binding) {\r\n self.greetings = str\r\n self._text = text\r\n }\r\n\r\n var body: some View {\r\n Text(greetings)\r\n }\r\n}</pre>\r\nObserve that the <code>text @Binding</code> variable has an underscore (_) in the initializer:\r\n<pre class=\"code\"> self._text = text</pre>\r\nAnd now when you create an instance of the MyView struct, you can bind the state variable through the initializer, like this:\r\n<pre class=\"code\">MyView(\"Hello, World!\", &lt;strong&gt;$text&lt;/strong&gt;)</pre>\r\nWant to learn more? Check out these <a href=\"https://www.dummies.com/programming/macintosh/10-great-swiftui-resources/?keyword=swiftui&index=1&isSearch=1\">SwiftUI resources</a>.","blurb":"","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"primaryCategoryTaxonomy":{"categoryId":33594,"title":"App Development","slug":"app-development","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33594"}},"secondaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":[{"articleId":192609,"title":"How to Pray the Rosary: A Comprehensive Guide","slug":"how-to-pray-the-rosary","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/192609"}},{"articleId":208741,"title":"Kabbalah For Dummies Cheat Sheet","slug":"kabbalah-for-dummies-cheat-sheet","categoryList":["body-mind-spirit","religion-spirituality","kabbalah"],"_links":{"self":"/articles/208741"}},{"articleId":230957,"title":"Nikon D3400 For Dummies Cheat Sheet","slug":"nikon-d3400-dummies-cheat-sheet","categoryList":["home-auto-hobbies","photography"],"_links":{"self":"/articles/230957"}},{"articleId":235851,"title":"Praying the Rosary and Meditating on the Mysteries","slug":"praying-rosary-meditating-mysteries","categoryList":["body-mind-spirit","religion-spirituality","christianity","catholicism"],"_links":{"self":"/articles/235851"}},{"articleId":284787,"title":"What Your Society Says About You","slug":"what-your-society-says-about-you","categoryList":["academics-the-arts","humanities"],"_links":{"self":"/articles/284787"}}],"inThisArticle":[{"label":"Understanding the UIKit View Controller life cycle","target":"#tab1"},{"label":"Understanding the SwiftUI view life cycle","target":"#tab2"}],"relatedArticles":{"fromBook":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}],"fromCategory":[{"articleId":274241,"title":"How to Make Your Own Animation in SwiftUI","slug":"how-to-make-your-own-animation-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274241"}},{"articleId":274231,"title":"Understanding How to Animate in SwiftUI","slug":"understanding-how-to-animate-in-swiftui","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274231"}},{"articleId":274217,"title":"Swift Closures","slug":"swift-closures","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274217"}},{"articleId":274211,"title":"A Quick Intro to Swift Functions","slug":"a-quick-intro-to-swift-functions","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274211"}},{"articleId":274206,"title":"10 Great SwiftUI Resources","slug":"10-great-swiftui-resources","categoryList":["technology","programming-web-design","app-development"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/274206"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281877,"slug":"swiftui-for-dummies","isbn":"9781119652687","categoryList":["technology","programming-web-design","app-development"],"amazon":{"default":"https://www.amazon.com/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119652685-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119652685/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/swiftui-for-dummies-cover-9781119652687-203x255.jpg","width":203,"height":255},"title":"SwiftUI For Dummies","testBankPinActivationLink":"","bookOutOfPrint":true,"authorsInfo":"<p><b><b data-author-id=\"33413\">Wei-Meng Lee</b></b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p>","authors":[{"authorId":33413,"name":"Wei-Meng Lee","slug":"wei-meng-lee","description":" <p><b>Wei-Meng Lee</b> is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and <i>CODE Magazine</i>. He is also the author of <i>SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning,</i> and <i>Learning WatchKit Programming</i>.</p> ","hasArticle":false,"_links":{"self":"https://dummies-api.dummies.com/v2/authors/33413"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221af9049ff\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{&quot;key&quot;:&quot;cat&quot;,&quot;values&quot;:[&quot;technology&quot;,&quot;programming-web-design&quot;,&quot;app-development&quot;]},{&quot;key&quot;:&quot;isbn&quot;,&quot;values&quot;:[&quot;9781119652687&quot;]}]\" id=\"du-slot-63221af9053b2\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0},"sponsorAd":"","sponsorEbookTitle":"","sponsorEbookLink":"","sponsorEbookImage":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":null,"lifeExpectancySetFrom":null,"dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":274224}],"_links":{"self":{"self":"https://dummies-api.dummies.com/v2/categories/33594/categoryArticles?sortField=time&sortOrder=1&size=10&offset=0"},"next":{"self":"https://dummies-api.dummies.com/v2/categories/33594/categoryArticles?sortField=time&sortOrder=1&size=10&offset=10"},"last":{"self":"https://dummies-api.dummies.com/v2/categories/33594/categoryArticles?sortField=time&sortOrder=1&size=10&offset=75"}}},"objectTitle":"","status":"success","pageType":"article-category","objectId":"33594","page":1,"sortField":"time","sortOrder":1,"categoriesIds":[],"articleTypes":[],"filterData":{"categoriesFilter":[{"itemId":0,"itemName":"All Categories","count":85}],"articleTypeFilter":[{"articleType":"All Types","count":85},{"articleType":"Articles","count":81},{"articleType":"Cheat Sheet","count":4}]},"filterDataLoadedStatus":"success","pageSize":10},"adsState":{"pageScripts":{"headers":{"timestamp":"2025-04-17T15:50:01+00:00"},"adsId":0,"data":{"scripts":[{"pages":["all"],"location":"header","script":"<!--Optimizely Script-->\r\n<script src=\"https://cdn.optimizely.com/js/10563184655.js\"></script>","enabled":false},{"pages":["all"],"location":"header","script":"<!-- comScore Tag -->\r\n<script>var _comscore = _comscore || [];_comscore.push({ c1: \"2\", c2: \"15097263\" });(function() {var s = document.createElement(\"script\"), el = document.getElementsByTagName(\"script\")[0]; s.async = true;s.src = (document.location.protocol == \"https:\" ? \"https://sb\" : \"http://b\") + \".scorecardresearch.com/beacon.js\";el.parentNode.insertBefore(s, el);})();</script><noscript><img src=\"https://sb.scorecardresearch.com/p?c1=2&c2=15097263&cv=2.0&cj=1\" /></noscript>\r\n<!-- / comScore Tag -->","enabled":true},{"pages":["all"],"location":"footer","script":"<!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->\r\n<script type='text/javascript'>\r\n(function(){var g=function(e,h,f,g){\r\nthis.get=function(a){for(var a=a+\"=\",c=document.cookie.split(\";\"),b=0,e=c.length;b<e;b++){for(var d=c[b];\" \"==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};\r\nthis.set=function(a,c){var b=\"\",b=new Date;b.setTime(b.getTime()+6048E5);b=\"; expires=\"+b.toGMTString();document.cookie=a+\"=\"+c+b+\"; path=/; \"};\r\nthis.check=function(){var a=this.get(f);if(a)a=a.split(\":\");else if(100!=e)\"v\"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(\":\"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case \"v\":return!1;case \"r\":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(\":\")),!c}return!0};\r\nthis.go=function(){if(this.check()){var a=document.createElement(\"script\");a.type=\"text/javascript\";a.src=g;document.body&&document.body.appendChild(a)}};\r\nthis.start=function(){var t=this;\"complete\"!==document.readyState?window.addEventListener?window.addEventListener(\"load\",function(){t.go()},!1):window.attachEvent&&window.attachEvent(\"onload\",function(){t.go()}):t.go()};};\r\ntry{(new g(100,\"r\",\"QSI_S_ZN_5o5yqpvMVjgDOuN\",\"https://zn5o5yqpvmvjgdoun-wiley.siteintercept.qualtrics.com/SIE/?Q_ZID=ZN_5o5yqpvMVjgDOuN\")).start()}catch(i){}})();\r\n</script><div id='ZN_5o5yqpvMVjgDOuN'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>\r\n<!--END WEBSITE FEEDBACK SNIPPET-->","enabled":false},{"pages":["all"],"location":"header","script":"<!-- Hotjar Tracking Code for http://www.dummies.com -->\r\n<script>\r\n (function(h,o,t,j,a,r){\r\n h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};\r\n h._hjSettings={hjid:257151,hjsv:6};\r\n a=o.getElementsByTagName('head')[0];\r\n r=o.createElement('script');r.async=1;\r\n r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;\r\n a.appendChild(r);\r\n })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');\r\n</script>","enabled":false},{"pages":["article"],"location":"header","script":"<!-- //Connect Container: dummies --> <script src=\"//get.s-onetag.com/bffe21a1-6bb8-4928-9449-7beadb468dae/tag.min.js\" async defer></script>","enabled":true},{"pages":["homepage"],"location":"header","script":"<meta name=\"facebook-domain-verification\" content=\"irk8y0irxf718trg3uwwuexg6xpva0\" />","enabled":true},{"pages":["homepage","article","category","search"],"location":"footer","script":"<!-- Facebook Pixel Code -->\r\n<noscript>\r\n<img height=\"1\" width=\"1\" src=\"https://www.facebook.com/tr?id=256338321977984&ev=PageView&noscript=1\"/>\r\n</noscript>\r\n<!-- End Facebook Pixel Code -->","enabled":true}]}},"pageScriptsLoadedStatus":"success"},"navigationState":{"navigationCollections":[{"collectionId":287568,"title":"BYOB (Be Your Own Boss)","hasSubCategories":false,"url":"/collection/for-the-entry-level-entrepreneur-287568"},{"collectionId":293237,"title":"Be a Rad Dad","hasSubCategories":false,"url":"/collection/be-the-best-dad-293237"},{"collectionId":295890,"title":"Career Shifting","hasSubCategories":false,"url":"/collection/career-shifting-295890"},{"collectionId":294090,"title":"Contemplating the Cosmos","hasSubCategories":false,"url":"/collection/theres-something-about-space-294090"},{"collectionId":287563,"title":"For Those Seeking Peace of Mind","hasSubCategories":false,"url":"/collection/for-those-seeking-peace-of-mind-287563"},{"collectionId":287570,"title":"For the Aspiring Aficionado","hasSubCategories":false,"url":"/collection/for-the-bougielicious-287570"},{"collectionId":291903,"title":"For the Budding Cannabis Enthusiast","hasSubCategories":false,"url":"/collection/for-the-budding-cannabis-enthusiast-291903"},{"collectionId":299891,"title":"For the College Bound","hasSubCategories":false,"url":"/collection/for-the-college-bound-299891"},{"collectionId":291934,"title":"For the Exam-Season Crammer","hasSubCategories":false,"url":"/collection/for-the-exam-season-crammer-291934"},{"collectionId":301547,"title":"For the Game Day Prepper","hasSubCategories":false,"url":"/collection/big-game-day-prep-made-easy-301547"}],"navigationCollectionsLoadedStatus":"success","navigationCategories":{"books":{"0":{"data":[{"categoryId":33512,"title":"Technology","hasSubCategories":true,"url":"/category/books/technology-33512"},{"categoryId":33662,"title":"Academics & The Arts","hasSubCategories":true,"url":"/category/books/academics-the-arts-33662"},{"categoryId":33809,"title":"Home, Auto, & Hobbies","hasSubCategories":true,"url":"/category/books/home-auto-hobbies-33809"},{"categoryId":34038,"title":"Body, Mind, & Spirit","hasSubCategories":true,"url":"/category/books/body-mind-spirit-34038"},{"categoryId":34224,"title":"Business, Careers, & Money","hasSubCategories":true,"url":"/category/books/business-careers-money-34224"}],"breadcrumbs":[],"categoryTitle":"Level 0 Category","mainCategoryUrl":"/category/books/level-0-category-0"}},"articles":{"0":{"data":[{"categoryId":33512,"title":"Technology","hasSubCategories":true,"url":"/category/articles/technology-33512"},{"categoryId":33662,"title":"Academics & The Arts","hasSubCategories":true,"url":"/category/articles/academics-the-arts-33662"},{"categoryId":33809,"title":"Home, Auto, & Hobbies","hasSubCategories":true,"url":"/category/articles/home-auto-hobbies-33809"},{"categoryId":34038,"title":"Body, Mind, & Spirit","hasSubCategories":true,"url":"/category/articles/body-mind-spirit-34038"},{"categoryId":34224,"title":"Business, Careers, & Money","hasSubCategories":true,"url":"/category/articles/business-careers-money-34224"}],"breadcrumbs":[],"categoryTitle":"Level 0 Category","mainCategoryUrl":"/category/articles/level-0-category-0"}}},"navigationCategoriesLoadedStatus":"success"},"searchState":{"searchList":[],"searchStatus":"initial","relatedArticlesList":[],"relatedArticlesStatus":"initial"},"routeState":{"name":"ArticleCategory","path":"/category/articles/app-development-33594/","hash":"","query":{},"params":{"category":"app-development-33594"},"fullPath":"/category/articles/app-development-33594/","meta":{"routeType":"category","breadcrumbInfo":{"suffix":"Articles","baseRoute":"/category/articles"},"prerenderWithAsyncData":true},"from":{"name":null,"path":"/","hash":"","query":{},"params":{},"fullPath":"/","meta":{}}},"profileState":{"auth":{},"userOptions":{},"status":"success"}}
Logo
  • Articles Open Article Categories
  • Books Open Book Categories
  • Collections Open Collections list
  • Custom Solutions

Article Categories

Book Categories

Collections

Explore all collections
BYOB (Be Your Own Boss)
Be a Rad Dad
Career Shifting
Contemplating the Cosmos
For Those Seeking Peace of Mind
For the Aspiring Aficionado
For the Budding Cannabis Enthusiast
For the College Bound
For the Exam-Season Crammer
For the Game Day Prepper
Log In
  • Home
  • Technology Articles
  • Programming & Web Design Articles
  • App Development Articles

App Development Articles

Facebooks and Instas and Tiktoks, oh my. Check out our articles on how ideas become world-famous apps.

Articles From App Development

page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8
page 9

Filter Results

85 results
85 results
App Development 9 SwiftUI Tips and Tricks

Article / Updated 08-10-2022

SwiftUI makes creating your iOS applications easy and efficient. However, there are neat tricks that are not so obvious. Here, you learn some of these tips and tricks so that you can become a better SwiftUI developer. Resume SwiftUI’s live preview My number-one pet peeve about SwiftUI is that the live preview feature in Xcode doesn’t always work. Very often, changes made to your code will cause the automatic previewing feature to pause. Even though your code is perfectly correct and there is no error, the live preview just can’t seem to update automatically. Of course, you could click the Resume button to update the preview, but you waste precious time moving your mouse to click the button. A better way is to press ⌘+Option+P. This causes the live preview to resume and update itself. Now that you know this trick, there is no reason to click the Resume button anymore! You may also want to check out the list of shortcuts for working in Xcode. Combine text views in SwiftUI Here is a neat little trick that you should know if you want to display the various words in a sentence in different colors and sizes. Instead of using the HStack view to group various Text views together, you can simply use the plus (+) operator to add different Text views together, like this: struct ContentView: View { var body: some View { Text("Red ") .foregroundColor(.red) .font(.largeTitle) + Text("Green ") .foregroundColor(.green) .font(.body) + Text("Blue") .foregroundColor(.blue) .font(.title) } } How cool is that? Here’s the output. If you want all the texts to be of the same font size, group them together using a Group view and apply the font() modifier on the Group view: struct ContentView: View { var body: some View { Group { Text("Red ") .foregroundColor(.red) + Text("Green ") .foregroundColor(.green) + Text("Blue") .foregroundColor(.blue) } .font(.largeTitle) } } Create custom modifiers in SwiftUI Swift modifiers allow you to change the behaviors of views. Consider the following example: import SwiftUI struct ContentView: View { var body: some View { VStack { Text("Leonardo da Vinci") .bold() .font(.largeTitle) .foregroundColor(.blue) .shadow(radius: 2) Text("Vincent van Gogh") .bold() .font(.largeTitle) .foregroundColor(.blue) .shadow(radius: 2) } } } Here, you apply the same set of modifiers to the two Text views. You often do that when you want to ensure consistencies in your UI (for example, applying the same set of UI styles when displaying certain information in your application). Instead of repeating the same set of modifiers again and again, wouldn’t it be easier if you could just encapsulate all the modifiers into yet another modifier? What you can do it is create another struct that conforms to the ViewModifier protocol. This protocol requires you to implement a body() method that has a Content parameter. You then apply whatever modifiers you want to this Content argument and return it: import SwiftUI struct Title: ViewModifier { func body(content: Content) -> some View { content .font(.largeTitle) .foregroundColor(.blue) .shadow(radius: 2) } } To use the newly created Title struct on the Text view, apply the modifier() modifier and pass in the Title struct, like this: struct ContentView: View { var body: some View { VStack { Text("Leonardo da Vinci") .bold() .modifier(Title()) Text("Vincent van Gogh") .bold() .modifier(Title()) } } } To make the Title struct look more like a true modifier, create an extension to the View protocol and give it a name — say, titleStyle: import SwiftUI extension View { func titleStyle() -> some View { self.modifier(Title()) } } You can now apply the titleStyle() modifier to the two Text views: struct ContentView: View { var body: some View { VStack { Text("Leonardo da Vinci") .bold() .titleStyle() Text("Vincent van Gogh") .bold() .titleStyle() } } } Display multiple alerts in SwiftUI Usually, in SwiftUI you apply a single alert() modifier to a single view. For example, when the user taps a button, you can display an alert by using the alert() modifier to the button. If you have multiple buttons, you can attach an alert() modifier to each button. However, there are times when you need to display multiple different alerts for a single view. Applying multiple alert() modifiers to a single view will not work correctly, because the last modifier will override the earlier ones. To solve this problem, you can use a single alert() modifier, and use a switch statement within the modifier to decide which alert to display. The following example shows a button that, when it’s clicked, generates a random number of either 1 or 2 and uses it to decide which alert to display: struct ContentView: View { @State private var displayAlert = false @State private var alertToDisplay = 0 var body: some View { Button(action: { self.alertToDisplay = Int.random(in: 1..<3) self.displayAlert = true }) { Text("Display Alert") } .alert(isPresented: $displayAlert) { switch alertToDisplay { case 1: return Alert(title: Text("Alert 1"), message: Text("This is Alert 1")) default: return Alert(title: Text("Alert 2"), message: Text("This is Alert 2")) } } } } Enable debug preview in SwiftUI By default, the preview canvas doesn’t display outputs printed using the print() function. This isn’t useful, however, because often you want to use the print() function as a quick debugging option. The good news is, you can easily fix this. In the preview canvas, right-click the Play button and select Debug Preview. Now if you tap the button, your code will print the output in the Output window: struct ContentView: View { var body: some View { Button ("Tap Me") { print("Button was tapped...") } } } If the Output window is not shown in Xcode, press ⌘+Shift+C and it should appear. Preview your SwiftUI app using different devices You’re familiar with using the preview canvas to preview your app. By default, Xcode automatically picks an appropriate device based on your target. You can preview your app on different modes — light mode and dark mode — using the environment() modifier: struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() .environment(\.colorScheme, .light) ContentView() .environment(\.colorScheme, .dark) } } } In addition to previewing in different modes, you can alter the size of the preview window, allowing you to have a glimpse of how your UI will look under different screen dimensions. You can do so using the previewLayout() modifier: static var previews: some View { Group { ContentView() .environment(\.colorScheme, .light) .previewLayout((.fixed(width: 400, height: 600))) ContentView() .environment(\.colorScheme, .dark) } } The image below shows the top preview displaying your UI in a dimension of 400 x 600 pixels. Note that clicking the Live Preview button will revert the preview back to the default size. If you want to preview your UI on multiple devices, you can use a ForEach loop, supply a list of device names, and then use the previewDevice() modifier on the ContentView, like this: static var previews: some View { ForEach(["iPhone 11", "iPhone SE"], id: \.self) { deviceName in ContentView() .environment(\.colorScheme, .light) .previewDevice(PreviewDevice( rawValue: deviceName)) .previewDisplayName(deviceName) } } The following image shows the preview on the iPhone 11 and the iPhone SE. Notice that you can display the name of the device using the previewDisplayName() modifier. Check out the full list of devices that you can preview. Dark mode only works on NavigationView As stated, you can use the environment() modifier to set the preview to dark mode so that you can see how your UI will look like in dark mode. However, it seems like the dark preview mode only works for the NavigationView. For example, consider the following example where you have two Text views contained within a VStack view: import SwiftUI struct ContentView: View { var body: some View { VStack { Text("Leonardo da Vinci") Text("Vincent van Gogh") } } } Suppose you use the environment() modifier to set the preview mode to dark, like this: struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environment(\.colorScheme, .dark) } } The words in the Text views automatically change to white, but the background remains white (running on the simulator or an actual device doesn’t have this issue), as shown below. So, essentially, you get a white screen. To fix this problem, wrap the ContentView view using a ZStack and set its background to black, like this: struct ContentView_Previews: PreviewProvider { static var previews: some View { ZStack { Color(.black) ContentView() } .edgesIgnoringSafeArea(.all) .environment(\.colorScheme, .dark) } } The image below shows the text showing up on a black background. Extract subviews in SwiftUI Your UI may contain quite a large number of views. This is very common if you have a complicated UI. However, you can simplify your UI by extracting some of the views as subviews. Consider the following example: import SwiftUI struct ContentView: View { var body: some View { HStack { Image("weimenglee") .resizable() .frame(width: CGFloat(120), height: CGFloat(120)) .cornerRadius(CGFloat(15), antialiased: true) VStack { Text("Wei-Meng Lee") .font(.largeTitle) .bold() Text("Founder") Text("Developer Learning Solutions") .italic() Text("http://calendar.learn2develop.net") Text("@weimenglee") } } } } To break down the UI into smaller subviews so that your UI is more modular and manageable, follow these steps: In the preview canvas, select the Image view and press the ⌘ key. Select Extract Subview. Name the new view PhotoView. The Image view will now be extracted as a new struct named PhotoView: struct ContentView: View { var body: some View { HStack { PhotoView() VStack { Text("Wei-Meng Lee") .font(.largeTitle) .bold() Text("Founder") Text("Developer Learning Solutions") .italic() Text("http://calendar.learn2develop.net") Text("@weimenglee") } } } } struct PhotoView: View { var body: some View { Image("weimenglee") .resizable() .frame(width: CGFloat(120), height: CGFloat(120)) .cornerRadius(CGFloat(15), antialiased: true) } } You can now also extract the VStack and save it as another struct named DetailsView. Now your UI looks like the following, which is more maintainable: struct ContentView: View { var body: some View { HStack { PhotoView() DetailsView() } } } struct PhotoView: View { ... } struct DetailsView: View { var body: some View { VStack { Text("Wei-Meng Lee") .font(.largeTitle) .bold() Text("Founder") Text("Developer Learning Solutions") .italic() Text("http://calendar.learn2develop.net") Text("@weimenglee") } } } Display a context menu in SwiftUI One of the innovative features of iPhone is the support for Haptic Touch (which replaces the 3D Touch on older iPhones). Using Haptic Touch, you can long-press an item on your iPhone and a context-sensitive menu appears (if the app you’re using supports it). You can support this feature in SwiftUI as well. To attach a context menu to a view, use the contextMenu() modifier: To attach a context menu to a view, use the contextMenu() modifier: struct ContentView: View { var body: some View { Image("Mac Pro") .resizable() .frame(width: 300, height: 280) .contextMenu { Button(action: { print("Save Image button tapped...") }) { Text("Save Image") Image(systemName: "tray.and.arrow.down") } Button(action: { print("Add to Cart button tapped...") }) { Text("Add to Cart") Image(systemName: "plus") } } } } To create a context menu, you provide a list of Button views, and the content of each button is automatically wrapped using an HStack view. Now when you long-press the Image view, a context menu appears. Want to learn more? Check out our SwifUI Cheat Sheet.

View Article
App Development What Is Swift Programming? Understanding What SwiftUI Is

Article / Updated 08-10-2022

SwiftUI is a declarative programming framework for developing UIs for iOS, iPadOS, watchOS, tvOS, and macOS applications. In fact, SwiftUI was invented by the watchOS group at Apple. Before SwiftUI was introduced, most developers use UIKit and Storyboard (which is still supported by Apple in the current version of Xcode to design a UI. Using UIKit and Storyboard, developers drag and drop View controls onto View Controllers and connect them to outlets and actions on the View Controller classes. This model of building UIs is known as Model View Controller (MVC), which creates a clean separation between UI and business logic. The following shows a simple implementation in UIKit and Storyboard. Here, a Button and Label view have been added to the View Controller in Storyboard; two outlets and an action have been created to connect to them: class ViewController: UIViewController { <strong> @IBOutlet weak var lbl: UILabel! @IBOutlet weak var button: UIButton! @IBAction func btnClicked(_ sender: Any) { lbl.text = "Button tapped" }</strong> For laying out the views, you use auto-layout to position the button and label in the middle of the screen (both horizontally and vertically). To customize the look and feel of the button, you can code it in the loadView() method, like this: override func loadView() { super.loadView() <strong>// background color button.backgroundColor = UIColor.yellow // button text and color button.setTitle("Submit", for: .normal) button.setTitleColor(.black, for: .normal) // padding button.contentEdgeInsets = UIEdgeInsets( top: 10, left: 10, bottom: 10, right: 10) // border button.layer.borderColor = UIColor.darkGray.cgColor button.layer.borderWidth = 3.0 // text font button.titleLabel!.font = UIFont.systemFont(ofSize: 26, weight: UIFont.Weight.regular) // rounder corners button.layer.cornerRadius = 10 // auto adjust button size button.sizeToFit() </strong> } The following image shows the button that has customized. UIKit is an event-driven framework, where you can reference each view in your view controller, update its appearance, or handle an event through delegates when some events occurred. In contrast, SwiftUI is a state-driven, declarative framework. In SwiftUI, you can implement all the above with the following statements: struct ContentView: View { <strong> @State private var label = "label"</strong> var body: some View { <strong>VStack { Button(action: { self.label = "Button tapped" }) { Text("Submit") .padding(EdgeInsets( top: 10, leading: 10, bottom: 10, trailing: 10)) .background(Color.yellow) .foregroundColor(Color.black) .border(Color.gray, width: 3) .font(Font.system(size: 26.0)) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(Color.gray, lineWidth: 5) </strong> <strong> ) } Text(label) .padding() }</strong> } } Notice that all the views are now created declaratively using code — no more drag-and-drop in Storyboard. Layouts are now also specified declaratively using code (the VStack in this example stacks all the views vertically). Delegates are now replaced with closures. More important, views are now a function of state (and not a sequence of events) — the text displayed by the Text view is now bound to the state variable label. When the button is tapped, you change the value of the label state variable, which automatically updates the text displayed in the Text view. This programming paradigm is known as reactive programming. The image below shows the various views in action. Want to learn more? Check out our SwiftUI Cheat Sheet.

View Article
App Development A Quick Intro to Swift Functions

Article / Updated 08-10-2022

Are you ready to build iOS apps using an innovative and intuitive user interface? Then, SwiftUI is for you! But before you dive in, you’ll need to know about Swift functions. Here’s a quick intro. In Swift, a function is defined using the func keyword, like this: func doSomething() { print("doSomething") } The preceding code snippet defines a function called doSomething. It does not take in any inputs (known as parameters) and does not return a value (technically, it does return a Void value). To call the function, simply call its name followed by a pair of empty parentheses: doSomething() Understanding input parameters A function can also optionally define one or more named typed inputs. The following function takes in one single typed input parameter: func doSomething(num: Int) { print(num) } To call this function, call its name and pass in an integer value (known as an argument) with the parameter name, like this: doSomething(num: 5) The following function takes in two input parameters, both of type Int: func doSomething(num1: Int, num2: Int) { print(num1, num2) } To call this function, pass it two integer values as the argument: doSomething(num1: 5, num2: 6) Returning a value Functions are not required to return a value. However, if you want the function to return a value, use the -> operator after the function declaration. The following function returns an integer value: func doSomething(num1: Int, num2: Int, num3: Int) -> Int { return num1 + num2 + num3 } You use the return keyword to return a value from a function and then exit it. When the function returns a value, you can assign it to a variable or constant, like this: var sum = doSomething(num1:5, num2:6, num3: 7) Functions are not limited to returning a single value. In some cases, it’s important for functions to return multiple values (or even functions). In Swift, you can use a tuple type in a function to return multiple values. Want to learn more? Check out these SwiftUI tips and tricks.

View Article
App Development A Brief Primer on Swift Programming: Basic Syntax

Article / Updated 08-10-2022

Swift is a type-safe language, which means that the programming language makes it clear to you the types of values your code is working with. The following article discusses how to declare constants and variables and how to work with strings and comments when programming with Swift. Swift constants In Swift, you create a constant using the let keyword: let radius = 3.45 // Double let numOfColumns = 5 // Int let myName = "Wei-Meng Lee" // String Notice that there is no need to specify the data type — the data types are inferred automatically. If you want to declare the type of constant, you can do so using the colon operator (:) followed by the data type, as shown here: let diameter<strong>:Double</strong> = 8 After a constant is created, you can no longer change its value. Always use a let when you need to store values that do not change. Swift variables To declare a variable, you use the var keyword: var myAge = 25 var circumference = 2 * 3.14 * radius After a variable is created, you can change its value. In Swift, values are never implicitly converted to another type. For example, suppose you’re trying to concatenate a string and the value of a variable. In the following example, you need to explicitly use the String() function to convert the value of myAge to a string value before concatenating it with another string: var strMyAge = "My age is " + String(myAge) To get the text representation of a value (constant or variable), you can also use the description property, like this: myAge.description. Swift strings One of the common tasks in programming is inserting values of variables into a string. In Swift, you use string interpolation and it has the following format: "Your string literal <strong>\(</strong><em>variable_name</em><strong>)</strong>" The following statement shows an example: let firstName = "Wei-Meng" let lastName = "Lee" var strName = "My name is \(firstName) \(lastName)" You can also use this method to include a Double value in your string (or even perform mathematical operations or function calls): var strResult = "The circumference is \(circumference)" Swift comments In Swift, as in most programming languages, you insert comments into your code using two forward slashes (//): // this is another comment If you have several lines of comments, it’s better to use the /* and */ combination to denote a block of statements as comments: /* this is a comment this is another comment */ Want to learn more? Check out our SwiftUI Cheat Sheet.

View Article
App Development Swift Closures

Article / Updated 08-10-2022

One important feature in Swift is closure. Closures are self-contained blocks of code that can be passed to functions to be executed as independent code units. Think of a closure as a function without a name. In fact, functions are actually special cases of closures. Swift offers various ways to optimize closures so that they’re brief and succinct. The various optimizations include the following: Inferring parameter types and return types Implicit returns from single-statement closures Shorthand argument names Trailing closure syntax Operator closure Understanding Swift closures The best way to understand Swift closures is to use an example. Suppose you have the following array of integers: let numbers = [5,2,8,7,9,4,3,1] Assume you want to sort this array in ascending order. You could write your own function to perform the sorting, or you could use the sorted() function available in Swift. The sorted() function takes two arguments: An array to be sorted A closure that takes two arguments of the same type as the array and returns a true if the first value appears before the second value Using Swift functions as closures In Swift, functions are special types of closures. As mentioned, the sorted() function needs a closure that takes two arguments of the same type as the array, returning a true if the first value appears before the second value. The following Swift function fulfils that requirement: func ascending(num1:Int, num2:Int) -> Bool { return num1 The ascending() function takes two arguments of type Int and returns a Bool value. If num1 is less than num2, it returns true. You can now pass this function to the sorted() function, as shown here: var sortedNumbers = numbers.sorted(by: ascending) The sorted() function now returns the array that is sorted in ascending order. The sorted() function does not modify the original array. It returns the sorted array as a new array. Assigning Swift closures to variables As mentioned earlier, functions are special types of closures. In fact, a closure is a function without a name. However, you can assign a closure to a variable — for example, the ascending() function discussed earlier can be written as a closure assigned to a variable: var compareClosure : (Int, Int)->Bool = { (num1:Int, num2:Int) -> Bool in return num1 < num2 } To use the compareClosure closure with the sorted() function, pass in the compareClosure variable: sortedNumbers = numbers.sorted(by: <strong>compareClosure</strong>) Writing Swift closures inline You can pass a function into the sorted() function as a closure function, but a better way is to write the closure inline, which obviates the need to define a function explicitly or assign it to a variable. Rewriting the earlier example would yield the following: sortedNumbers = numbers.sorted(by: { (num1:Int, num2:Int) -> Bool in return num1 < num2 } ) As you can see, the ascending() function name is now gone; all you’ve supplied is the parameter list and the content of the function. If you want to sort the array in descending order, you can simply change the comparison operator: sortedNumbers = numbers.sorted(by: { (num1:Int, num2:Int) -> Bool in return num1 > num2 } ) Understanding type inference Because the type of the first argument of the closure function must be the same as the type of array you’re sorting, it’s actually redundant to specify the type in the closure, because the compiler can infer that from the type of array you’re using: var fruits = ["orange", "apple", "durian", "rambutan", "pineapple"] print(fruits.sorted(by: { (fruit1, fruit2) in return fruit1 If your closure has only a single statement, you can even omit the return keyword: print(fruits.sorted(by: { (fruit1, fruit2) in fruit1 Using shorthand argument names Above, names were given to arguments within a closure. In fact, this is also optional, because Swift automatically provides shorthand names to the parameters, which you can refer to as $0, $1, and so on. The previous code snippet could be rewritten as follows without using named parameters: print(fruits.sorted(by: { $0<$1 }) ) To make the closure really terse, you can write everything on one line: print(fruits.sorted(by:{ $0<$1 })) Working with Swift’s operator function You saw that the closure for the sorted() function was reduced to the following: print(fruits.sorted(by:{ $0<$1 })) One of the implementations of the lesser than (<) operator is actually a function that works with two operands of type String. Because of this, you can actually simply specify the < operator in place of the closure, and the compiler will automatically infer that you want to use the particular implementation of the < operator. The preceding statement can be reduced to the following: print(fruits.sorted(by:<strong><</strong>)) If you want to sort the array in descending order, simply use the greater than (>) operator: print(fruits.sorted(by:<strong>></strong>)) Using trailing closures in Swift Consider the closure that you saw earlier: print(fruits.sorted(by: { (fruit1, fruit2) in return fruit1 Notice that the closure is passed in as a second argument of the sorted() function. For long closures, this syntax may be a little messy. If the closure is the final argument of a function, you can rewrite this closure as a trailing closure. A trailing closure is written outside of the parentheses of the function call. The preceding code snippet, when rewritten using the trailing closure, looks like this: print(fruits.sorted() { (fruit1, fruit2) in return fruit1 Using the shorthand argument name, the closure can be shortened to the following: print(fruits.sorted()<strong>{$0<$1}</strong>) Want to learn more? Check out our SwiftUI Cheat Sheet.

View Article
App Development Understanding How to Animate in SwiftUI

Article / Updated 08-10-2022

To animate a view in SwiftUI, apply the animation() modifier on it. SwiftUI animates any changes made to animatable properties of a view. For example, the various properties of a view in SwiftUI — such as its color, opacity, rotation, size, and other properties — are all animatable. As usual, the best way to understand this concept is to use an example. First, create a rounded button that shows the Confirm caption: struct ContentView: View { var body: some View { Button(action: { }) { Text("Confirm") .bold() } .padding(40) .background(Color.green) .foregroundColor(.white) .clipShape(Circle()) } } Apply some scaling (zooming) to the button using the scaleEffect() modifier: struct ContentView: View { @State private var scaleFactor: CGFloat = 1 var body: some View { Button(action: { }) { Text("Confirm") .bold() } .onAppear(perform: { self.scaleFactor = 2.5 }) .padding(40) .background(Color.green) .foregroundColor(.white) .clipShape(Circle()) .scaleEffect(scaleFactor) } } What you want to do here is zoom the button to two and a half times its original size. The scaling will be performed as soon as the Button view is shown in SwiftUI. The following image shows the button zoomed in to two and a half times its original size when it first appears. What you really want is to slow down the scaling, so that users can see the zooming-in process. For this, you can use the animation() modifier on the Button view: struct ContentView: View { @State private var scaleFactor: CGFloat = 1 var body: some View { Button(action: { }) { Text("Confirm") .bold() } .onAppear(perform: { self.scaleFactor = 2.5 }) .padding(40) .background(Color.green) .foregroundColor(.white) .clipShape(Circle()) .scaleEffect(scaleFactor) .animation(.default) } } The .default property actually belongs to the Animation struct, so you can rewrite the above statement as follows: .animation(<strong>Animation</strong>.default) When you now load the Button view again, the button zooms in two and a half times. Specifying the type of animation in SwiftUI By default, the button will zoom in at a linear speed. You can also use the easeInOur() modifier if you want the animation to start slow, pick up speed, and then slow down again: .animation( .easeInOut(duration: 2) ) The duration parameter indicates how much time is given for the animation to complete in SwiftUI. In this example, the zoom animation must complete in two seconds. If you want to start fast and then slow down, use the easeOut() modifier: .animation( .easeOut(duration: 2) ) Both the easeInOut() and easeOut() modifiers are type methods of the Animation struct. Repeating the animation in SwiftUI Many times, you want the animation to repeat a number of times. For this you can apply the repeatCount() modifier: .animation( Animation.easeInOut(duration: 2) .repeatCount(2, autoreverses: true) ) The easeInOut() is a type method of the Animation struct, and it returns an Animation struct. So, in this case, you call the repeatCount() modifier of the Animation struct to repeat the animation a number of times (twice, in this case). The autoreverses parameter allows you to reverse the animation, so for this particular case the size of the button changes from small to big, and then reverses and changes from big to small. The image below shows the animation that is repeated twice. Notice that at the end of the second animation, the button reverts back to the larger size as specified in the scaleFactor state variable: .scaleEffect(scaleFactor) // changed to 2.5 in onAppear() If you want the animation to repeat forever, use the repeatForever() modifier: .animation( Animation.easeInOut(duration: 2) .repeatForever(autoreverses: true) ) Stopping the animation in SwiftUI Although you can animate nonstop in SwiftUI, there are times where you need to stop the animation. Here’s another example: struct ContentView: View { @State private var opacity:Double = 1.0 var body: some View { Button(action: { }) { Text("Click Me") .fontWeight(.bold) .font(.title) .foregroundColor(.blue) .padding() .background(Color.yellow) .overlay( Rectangle() .stroke(Color.blue, lineWidth: 5) ) .opacity(opacity) .onAppear() { let baseAnimation = Animation.linear(duration: 1) withAnimation ( baseAnimation.repeatForever( autoreverses: true)) { self.opacity = 0.2 } } } } } The preceding code snippet shows a Button view with its opacity initially set to 1.0. When it appears, you perform a linear animation (animating with constant speed) to change the opacity of the button down to 0.2, all within a duration of 1 second. In the next 1 second, it then changes to fully opaque again. Unlike the earlier example, this example does not use the animation() modifier for animation. Instead, you use the withAnimation block. The withAnimation block lets you explicitly tell SwiftUI what to animate. The image below shows the button fully opaque when it’s loaded and then gradually changes its opacity to 0.2. The animation is perpetual, so to stop it, you need to do some work in SwiftUI. For this, you can use a Boolean state variable (let’s call it animate) and use it to determine if the animation should continue: withAnimation (self.animate ? baseAnimation.repeatForever( autoreverses: true) : Animation.default) { self.opacity = 0.2 } In the preceding Swift code snippet, if the animate state variable is true, you’ll perform the animation perpetually, or you can set the animation to default (which will only perform the animation once). The following code snippet stops the animation when the button is tapped and sets the opacity of the button back to 1: struct ContentView: View { @State private var opacity:Double = 1.0 @State private var animate = true var body: some View { Button(action: { self.animate = false self.opacity = 1.0 }) { Text("Click Me") .fontWeight(.bold) .font(.title) .foregroundColor(.blue) .padding() .background(Color.yellow) .overlay( Rectangle() .stroke(Color.blue, lineWidth: 5) ) .opacity(opacity) .onAppear() { let baseAnimation = Animation.linear(duration: 1) withAnimation (self.animate ? baseAnimation.repeatForever( autoreverses: true) : Animation.default) { self.opacity = 0.2 } } } } } Remember to follow the Apple Human Interface Guidelines (HIG) when it comes to animating your UI. This also applies to custom animations. Want to learn more? Check out these SwiftUI resources.

View Article
App Development SwiftUI For Dummies Cheat Sheet

Cheat Sheet / Updated 03-25-2022

SwiftUI makes creating iPhone stacked and tabbed apps easy! You can add shake fail feedback using animation, so your users know when their login attempt has failed. And you can give users the option of sharing something in your app, using the Share Sheet.

View Cheat Sheet
App Development Swift For Dummies Cheat Sheet

Cheat Sheet / Updated 03-22-2022

Swift is Apple’s programming language for developers to use with iOS and OS X devices. Swift has been designed both to work alongside its predecessor, Objective-C, and to one day be Objective-C’s replacement. When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language —either Objective-C or Swift. Swift inherits much of Objective-C’s functionality — anyone comfortable with Objective-C’s types, collections, functions, classes, and flow control will be familiar with those structures in Swift, as well.

View Cheat Sheet
App Development Flutter For Dummies Cheat Sheet

Cheat Sheet / Updated 02-14-2022

Flutter's online documentation is a great source of information, but sometimes you'd rather glance quickly at an example. This cheat sheet has some sample code. Just grab it and go!

View Cheat Sheet
App Development How to Use UIKit in SwiftUI

Article / Updated 08-26-2021

Did you know you can use UIKit in SwiftUI? It’s true! When you develop iOS apps using Storyboard in Xcode, you use the UIKit for all UI matters. UIKit is the framework that forms the core components of all iOS applications. Among all the classes in the UIKit, view and view controllers are the most commonly used classes. View controllers (UIViewController) play a crucial role in your apps — they act as the skeleton of your application. A view controller is basically a class that manages a set of views (to display to the user), while coordinating with model (data) objects. Because the view controller is connected to your Storyboard (an external file), it has very little control of what’s happening on the view side of things (and vice versa). You may be familiar with this — connect an event in your Interface Builder to a function in your code in Swift and then later on you delete the function. However, the Interface Builder doesn’t know that your function is now gone, and all hell will break loose when that event is invoked during runtime. This problem is precisely what SwiftUI tries to resolve. The various widgets — such as Button, Label, TextField, and Switch — are represented by the subclasses of UIView. This article discusses how to use UIKit within a SwiftUI project, but the converse is also true — you would also want to use SwiftUI in an existing UIKit project. Note that after you add SwiftUI to your UIKit project, your apps will only run on iOS 13.0 and later, macOS 10.15 and later, tvOS 13.0 and later, and watchOS 6.0 and later. The image below shows a UIViewController instances containing a number of UIView instances. Understanding the UIKit View Controller life cycle In order to handle the various states of a view controller, a view controller has a set of events, known as the life cycle of a view controller. The life cycle of a view controller has a variety of events, including (but not limited to) the following: viewDidLoad: Called after the controller’s view is loaded into memory loadView: Creates the view that the controller manages viewWillAppear: Notifies the view controller that its view is about to be added to a view hierarchy viewDidAppear: Notifies the view controller that its view was added to a view hierarchy viewWillDisappear: Notifies the view controller that its view is about to be removed from a view hierarchy viewDidDisappear: Notifies the view controller that its view was removed from a view hierarchy didReceiveMemoryWarning: Sent to the view controller when the app receives a memory warning The following Swift code shows how to handle the various events of a view controller. import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func loadView() { super.loadView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } The various events are fired during the lifetime of the view controller. For example, you often initialize your variables during the viewDidLoad event (it fires only once when the view controller is first loaded). If you needed to update the view whenever the view controller appears, you would perform the updates in the viewDidAppear event (fired every time the view comes to the foreground). Or if you need to build the UI dynamically during loading time, you can do it in the loadView event. Understanding the SwiftUI view life cycle Compared to the UIViewController life cycles, the life cycle of a view in SwiftUI is much simpler and more straightforward. In SwiftUI, there is no concept of a view controller. Instead, everything is a View. In SwiftUI, View has only two events: onAppear onDisappear You can attach these two events to any views, and SwiftUI will execute them when they occur. Working with the onAppear and onDisappear events in SwiftUI When a view appears, the onAppear event will be fired. Likewise, when the view disappears, the onDisappear event will be fired. Let’s illustrate the use of the onAppear event: func fetchData() { ... } var body: some View { List(articles, id: \.url) { item in VStack(alignment: .leading) { Text(item.title) .font(.headline) Text(item.description ?? "") .font(.footnote) } }.onAppear(perform: fetchData) } When the List view first appears, it will fire the onAppear event, which you then use to call the fetchData() function to load data from the web. For that example, it’s quite straightforward to understand when the onAppear event fires. A more involved example would be one comprising a NavigationView and a TabView. The following image shows an example where the ContentView contains a TabView, which in turn also contains a NavigationView. The following Swift code snippet shows the implementation of the three views that you’ve just seen. To understand when the onAppear and onDisappear events are fired when the user moves from one screen to another, you insert print statements, as shown in the following code: import SwiftUI struct View1: View { var body: some View { Text("View1") .onAppear{ print("onAppear in View1") } .onDisappear{ print("onDisappear in View1") } } } struct View2: View { var body: some View { Text("View2") .onAppear{ print("onAppear in View2") } .onDisappear{ print("onDisappear in View2") } } } struct ContentView: View { var body: some View { TabView { NavigationView{ NavigationLink(destination: View1()) { Text("Next") } }.onAppear{ print("onAppear in ContentView") } .onDisappear{ print("onDisappear in ContentView") } .tabItem { Image(systemName: "viewfinder.circle.fill") Text("ContentView") } View2() .tabItem { Image(systemName: "camera.viewfinder") Text("View2") } } .onAppear{ print("onAppear in TabView") } .onDisappear{ print("onDisappear in TabView") } } } When the app is first loaded, you see the following outputs: onAppear in TabView onAppear in ContentView You can see that TabView first appeared, followed by ContentView. When you click the Next button, it navigates to View1. The following statement in bold shows the additional statement printed: onAppear in TabView onAppear in ContentView <strong>onAppear in View1</strong> Even though ContentView is now hidden, it hasn’t disappeared yet (because there is no output indicating its disappearance). Now, click the Back button to go back to ContentView. This time, you see the following additional output: onAppear in TabView onAppear in ContentView onAppear in View1 <strong>onDisappear in View1</strong> So View1 has disappeared. Click the View2 item on the tab bar. View2 is now loaded. Here’s the output: onAppear in TabView onAppear in ContentView onAppear in View1 onDisappear in View1 <strong>onDisappear in ContentView</strong> <strong>onAppear in View2</strong> Now ContentView has disappeared and View2 appears. Finally, click ContentView item on the tab bar and notice that View2 has disappeared and ContentView has appeared again: onAppear in TabView onAppear in ContentView onAppear in View1 onDisappear in View1 onDisappear in ContentView onAppear in View2 <strong>onDisappear in View2</strong> <strong>onAppear in ContentView</strong> As you can see from the example, the onAppear event allows you to know when a view comes onscreen. This is useful in cases where you want to load data on demand. Suppose you have a tabbed application with five tab items and each of these tab pages separately loads data from the web. It would be useful to load the data only when the user views a particular page. Otherwise, the entire iOS app would feel sluggish when it tries to load all the data at the same time when the app starts up. Instantiating properties of a view in SwiftUI Besides understanding when the two events are fired, it’s also important to understand how SwiftUI processes a View when it’s created and the sequences in which properties and binding objects are processed. You may already know that the View is a struct. Very often, views have properties, which allows you to pass in additional information to customize the behaviors of views. Consider the following simple example of a View named MyView: struct MyView: View { var greetings: String var body: some View { Text(greetings) } } In the MyView struct, you have a property named greetings. It is of type String, but it hasn’t been initialized yet. When you try to use MyView, as in the following code snippet, struct ContentView: View { var body: some View { VStack{ MyView("Hello, World!") } } } You get the error: Missing argument label 'greetings:' in call. This is because you need to initialize the value of the greetings property in MyView, which is the first thing the compiler tries to do when instantiating the struct. To fix this, pass in the argument for the greetings property when calling MyView, like this: MyView(greetings: "Hello, World!") Using initializers in a SwiftUI view Structs can also have initializers (constructors). If MyView has an explicit initializer, like the following: struct MyView: View { var greetings: String init(_ str:String) { self.greetings = str } var body: some View { Text(greetings) } } Then greetings must be initialized via the initializer for MyView: MyView("Hello, World!") Using binding variables in a SwiftUI view If MyView has a @Binding variable, like this: struct MyView: View { @Binding var text: String var greetings: String var body: some View { Text(greetings) } }</pre Then you have to initialize it through the parameters: struct ContentView: View { @State var text: String = "" var body: some View { MyView(greetings: "Hello, World!", text: $text) } } Note that the binding variable argument must come after the greetings argument. If MyView has an explicit initializer, you have to specify the type of the Binding object in your initializer, like this: struct MyView: View { @Binding var text: String var greetings: String init(_ str:String, _ text: Binding) { self.greetings = str self._text = text } var body: some View { Text(greetings) } } Observe that the text @Binding variable has an underscore (_) in the initializer: self._text = text And now when you create an instance of the MyView struct, you can bind the state variable through the initializer, like this: MyView("Hello, World!", <strong>$text</strong>) Want to learn more? Check out these SwiftUI resources.

View Article
page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8
page 9

Quick Links

  • About For Dummies
  • Contact Us
  • Activate Online Content

Connect

About Dummies

Dummies has always stood for taking on complex concepts and making them easy to understand. Dummies helps everyone be more knowledgeable and confident in applying what they know. Whether it's to pass that big test, qualify for that big promotion or even master that cooking technique; people who rely on dummies, rely on it to learn the critical skills and relevant information necessary for success.

Copyright @ 2000-2024 by John Wiley & Sons, Inc., or related companies. All rights reserved, including rights for text and data mining and training of artificial technologies or similar technologies.

Terms of Use
Privacy Policy
Cookies Settings
Do Not Sell My Personal Info - CA Only