您好,欢迎参加这个为期 14 天的初学者挑战,您将开始您的应用程序
之旅,您将了解应用程序是如何制作的,以及它们如何最终出现在应用程序商店中
您将熟悉 xcode以及如何开始您自己的应用程序项目
您将学习如何使用 swift ui 构建用户界面,您将学习 swift
编程基础知识,以便您现在可以在接下来的 14 节课中阅读和编写简单的 swift
代码'将获得所有这些新技能,并且您将构建您自己的
应用程序,您可以将其安装在您的设备上,并向您的所有朋友和家人展示您所做的事情
比这更重要,但是您将成为非常有信心和兴奋地继续 提高
您
的应用程序开发技能,超出我们在这里所涵盖
的 范围 如果你想学习如何制作一个应用程序我们已经教
了成千上万没有编码经验的人如何编码以及如何制作应用程序,我相信
我们可以为你做同样的事情你为什么在这里学习应用程序开发
让我知道留下一个如果您不介意,
请在下方快速评论并在您下楼的路上快速竖起大拇指,这确实有助于视频的发布,我非常感谢,
所以如果您准备好了,让我们卷起袖子开始吧
我将浏览这个图表,然后在我告诉你从哪里获得所有部分之后,
这一切都从 xcode ide 开始,现在 ide 代表集成开发环境,它是
应用程序和所有工具的术语 开发人员 用于为本课程的其余部分
构建一些东西 ,我们将简称为 xcode,这是我们通过编写
swift 代码构建我们的应用程序的地方,该代码构建用户界面或简称 ui,并将其与我们所有的数据连接
起来我们用来表达我们的逻辑和告诉系统我们想要做什么,我们
甚至可以通过 swift 代码构建 ui,正如您很快就会看到
的 那样 xcode
swift 和 swift ui 是相同的技能和工具用于为所有
苹果平台构建所有应用程序,包括 ios ipad os tv os watch os 和 mac os,在某些情况下,您的
应用程序将能够在多个平台上运行而无需现在有很大的变化 一旦你的应用程序 被构建你可以通过
苹果 的应用程序商店分发它这是通过加入苹果开发者
计划来 完成的
试飞和配置门户
还有更多好处,包括访问 beta 软件和苹果工程师的支持
,我将在配置门户下方提供指向完整列表的链接,让您可以访问
id 工具对您的应用程序进行 识别和代码签名就像在应用程序上添加您的签名,以便苹果
可以识别它的构建者,这对于下载您的
应用程序的最终用户的安全很重要,对您也很重要,因为它可以阻止恶意编码人员假装 一旦 您
的应用程序处于可测试状态 测试飞行允许您邀请人们下载和
测试您的应用程序 他们将能够通过测试飞行程序直接向您发送反馈和错误报告
使用测试飞行以确保您的应用程序在发布前已尽可能完善
,最后,应用程序商店连接是您为应用程序创建应用程序列表的地方,包括
所有元数据和屏幕截图(如果您的应用程序有应用内购买),这也是您
配置它们 的地方 一旦您的应用程序经过测试并且列表准备就绪,您可以将应用程序从 xcode 上传
到应用程序商店 connect 从那里苹果的认证团队将审查您的应用程序,以确保
它符合应用程序商店质量 gui描述这需要几天时间,
如果你失败了也不要担心,因为你可以修复他们指出的任何内容,
如果一切看起来都很好,他们将批准该应用程序,并且你的应用程序将上线恭喜
你在哪里可以获得苹果开发者生态系统的这些不同部分,您
可以从 mac 应用程序商店免费下载 xcode,我将在下面提供一个链接,
您不需要获得 swift 或 swift ui 那些只是 xcode 附带的苹果开发者
程序我'将提供一个链接到下面的注册页面我想提一下,
如果您的目标不是将应用程序分发到应用程序商店,那么加入苹果开发者计划是完全可选的,
不要加入它,您仍然可以了解如何为自己构建应用程序,
这就是苹果开发者生态系统,如果你现在继续这个应用程序之旅,我将带你完成 这个学习路径结束时,你将
使用所有这些 构建自己的 应用程序
我们已经涵盖的工具即使您现在没有任何编码经验
,我向您保证,在本次挑战结束时您会惊讶于您能做的事情
现在我强烈建议您访问 codewithkris.com 并创建
一个您可以使用的帐户同一门课程并获得所有补充材料并获得
所有测验和练习以使您的学习真正有效
事实上如果您现在就去做,那么您可以参加一个测验来加强您已经 掌握的知识
今天在这里学到的下一课我们将直接深入 xcode,如果您不想
错过它,请确保您通过点击下面的订阅按钮订阅频道
并打开铃声通知,以便您获得通知好的,我会在下一课见到你
你好,欢迎在这个 xcode 教程中你将熟悉
你将在其中构建应用程序的开发环境我会告诉你在哪里下载 xcode 以及如何
开始一个新的应用项目,然后我们要去通过 xcode 的主要领域,然后
你的应用程序项目中的每个文件的用途,最后我们将
通过 一些关于如何在 xcode 中导航的快速提示来 结束本课
通过谈论从哪里获得 xcode 它是免费的,因此您无需付费只需
在您的计算机上启动 mac 应用商店,然后搜索 xcode,您将
在搜索结果中进入这样的页面 click into它,你将能够免费下载它
所以我已经下载了它所以这就是为什么它说更新在这里
我希望你忽略这里的警告它实际上是一个非常大的应用程序有很多
不同功能 存在一些错误是可以理解的,如果您查看
评论,有人会抱怨与应用程序无关的其他事情,他们会抱怨
苹果运营业务的方式等等等等,其中一些是嗯
,很老了,好吧,我要你注意在此重要信息中单击此
只是为了确保安装 xcode 的要求并仔细检查您
现在是否有足够的可用硬盘空间 根据我的经验,随着时间的推移,它实际上需要
比这里所说的更多的硬盘空间,所以如果您有 12 gigs 之类的免费内容,它可能不允许您安装
它,因为在安装过程中它实际上占用了更多空间,然后我认为
它会删除一堆文件并且它会停止在这个大小,但是随着时间的推移,当您下载
其他 文件时 开发者组件和额外的 ios 模拟器 这实际上可以变得更高,因此
请确保您有足够的硬盘空间,所以如果由于某种原因您无法
访问 mac 应用商店,您也可以访问苹果上的官方 xcode 页面开发者网站,所以
网址是 developer.apple.com xcode,您可以立即点击此处的资源链接
,然后您将被带到一个页面,您可以在此处下载 xcode,只需 y你到 mac
应用商店实际上你也可以下载 xcode 的 beta 版本现在我不推荐这个 ,因为通常它实际上是他们的 beta 软件的相当多的错误所以
如果你出于某种原因想要下载 ,我建议坚持 使用官方版本
旧版本的 xcode,您可以
在此处向下滚动,您现在可以在此处单击此链接,只需备注即可下载
Apple 软件的 beta 版本,您需要注册他们的 Apple 开发人员计划,我们在
上一课中谈到了下载 旧版本的
xcode 我认为您不需要注册
该计划 对你来说好吧,所以
现在抓住机会下载并安装 xcode,如果你还没有,然后
在你第一次启动时第一次启动它,它会要求你输入管理密码
来安装 add您将要执行此操作的其他开发组件,因此请
在完成后输入您的管理员密码,让我们继续观看视频的其余部分,
现在让我们谈谈如何启动一个全新的 xcode 应用程序project 这应该是
您 启动 xcode
时看到的第一个欢迎屏幕
xcode project from here from here 你
将为你的新项目选择一个模板 你将为此配置项目属性 然后
你将选择一个保存它的地方 所以让我们从选择一个模板开始 对于我们来说, 最基本的一个
是在 ios 和 app 下,所以继续选择它并点击下一步,然后在这里你
将为你的项目配置属性,所以如果你在这里没有团队,
以后 不用担心 你可以在这里添加你的苹果账户,然后你就可以确定项目团队的
一件事是,
如果您有企业或网站,则在此处设置您的组织标识符,您可以在此处使用反向域名样式
名称如果您愿意,甚至可以在这里使用您的名字和姓氏
,然后在这里您可以填写您的应用程序的名称或产品名称,所以如果我在这里进行
测试,您会看到这个捆绑标识符是组织标识符加上
产品名称,这一起形成了这个唯一的包标识符这个包标识符
用于不同的地方来标识你的应用程序,例如在应用商店或供应
门户或应用商店连接中,所以这非常重要不要担心您以后可以更改
项目的捆绑标识符我只是想提请您注意它是如何形成的以及
它的用途接下来您的界面将确保您
选择了 swift ui 并用于生活 循环,您将确保选择了 swift ui 应用程序
,然后最后为语言选择 swift 并且对于这些选项,只需将它们全部取消选中 ,或者如果它们已选中,请立即取消选中它们,
随着时间的推移 ,这些下拉列表的简要说明
随着 ios 应用程序开发的发展,出现了几种编程语言
以及几种构建用户界面的方法,最新最好的方法是 swift ui
和 swift,所以这就是我们想要使用的,让我们继续前进 '对
您在这里的所有选择感到满意,然后选择一个
保存 位置
好吧,欢迎来到你全新的 xcode 项目,现在它可能看起来有所有
不同的面板和区域,但是一旦你知道它是如何分解的,它实际上并没有那么复杂
,xcode 实际上只有四个主要区域让我们从头开始留在这里,我们
有导航器面板或导航器区域,正如您在此处看到的,我们有一个文件列表 ,其中列出
了我们的应用程序项目中的所有不同文件,导航器区域实际上有不同的选项卡
来导航不同的东西,我们将现在进入以后的课程,它设置
为第一个选项卡,当您单击文件时,我们会列出文件列表,它会更改
这个大主区域中显示的内容,这称为编辑器区域,它允许我们编辑 我们在 文件
导航器中选择的文件,您可以看到它适应您选择的文件类型,
如果我选择 dot swift 文件,这些是代码文件,如果我选择这个 xc 资产文件,这是一个图像
库,所以它向我展示了一些东西像这样,编辑器区域是编辑
我在此处选择的文件的地方,因此最后一个选项卡位于最右侧,这称为检查器区域
,它可以向我显示有关我在编辑器区域中选择的内容的其他补充信息或者
它允许 m e 配置或编辑我在编辑器区域中选择的内容,具体取决于
我当前正在使用的编辑器类型,例如这是一个代码编辑器,因为我正在
查看一个 dot swift 文件,所以当我将鼠标悬停在或
在 此处
选择 关键字
向我显示有关我选择的那个文件的信息,包括它的位置和
它包含在哪个应用程序中,如果我们现在正在构建我们的用户界面,如果我要选择其中一个
元素并转到这个选项卡,它将允许我配置它以便总结
这里的检查器面板与您在编辑器区域中选择的内容相关,并且编辑器区域与
您在导航器区域中选择的内容相关,因此这一切都源于您在左侧
首先 选择的内容 然后在顶部我们有这里的工具栏让我向你解释一下这是什么
在最左边和最右边有一个按钮可以隐藏和显示导航器和检查
器 如果你没有很多屏幕空间,这些很方便 下一步我想要提请您
注意在中间 这是状态栏 它告诉您当前正在发生
什么 xcode 在做什么 您是否有任何错误 您是否有任何警告等等
左边有一个下拉菜单选择一个模拟器,这个 ios 模拟器
基本上是一个出现在屏幕上的虚拟设备,您可以在其中运行您的应用程序并
对其进行测试您实际上并不需要物理设备,但如果您有一个并且您将其插入
并且您想要要在您的实际设备上运行您的 xcode 项目,您会发现
一旦插入它就可以从此处选择它,然后在此菜单的左侧,您将在
这里看到几个按钮来运行您的项目,点击此按钮按钮实际上会
在模拟器中 运行您的项目 点击这个停止按钮将停止在模拟器中运行您的项目,
然后一直在右侧还有另外两个按钮
这是库按钮,您将在其中找到不同的用户界面元素不同
的修改方式元素代码片段您添加到项目中的任何资产您为项目
指定的颜色等等这个小库面板对于进行搜索
以及快速选择并将内容添加到我们将要进行的编辑器区域 很有用 在下一
课中进行讨论,但现在这是库区域,您可能不会在开始时使用太多,
这是一个修订或代码审查之类的按钮,如果您使用源代码控制,它将向您
展示您的文件已经随着时间的推移而改变,所以这些是 xcode 用户
界面的四个主要区域,现在让我们回顾一下新项目中的文件让我们从最上面开始,
这是根节点,或者如果你选择它,它就是你的项目文件 编辑器区域将变为
此配置屏幕,供您编辑与您的项目相关的一些详细信息,
例如,这是可更改的捆绑标识符,您可以配置设备方向
,在哪些设备和哪些平台上可以运行类似的东西,如果我们往下一层,你
可以看到这里有两个文件夹,这个文件夹包含你所有的代码文件和
项目文件,这个产品一个包含你构建应用程序并编译它时的输出,它
变成了这个应用程序,最终就是那么少我们发送
到应用商店的可部署捆绑包或包,您实际上不必在这里做太多事情,但这就是它的存储
位置,让我们看一下这个文件,它将以您的产品名称 app.swift 和你
可以在这里看到这个主标签 这里这是你的应用程序的入口点 在这一点上没有
太多需要配置的地方它真正要做的就是创建用户看到的第一个视图
内容视图,您可以看到这个名称映射到 contentview.swift 所以让我们看一下
这个文件代表用户现在看到的视图您可以创建其他视图但默认情况下
您会从这个内容视图开始,是的所有代码都在这里,这意味着用户
界面是由代码生成的,而且还有一种可视化的方式来自定义用户界面,
您将在下一课中看到,让我们继续我们的其他文件,正如我之前提到的,这是
我们的资产库 这是我们可以存储我们的应用程序的颜色以及应用程序图标
以及我们想要添加到项目中的任何其他图像的地方,我们只需将其拖放到这里
这是我们的图像资产,不仅仅是图像,但资产库,然后我们有一个 info.plist,
这是项目的一些附加配置信息,这里有预览内容,
这是另一个资产库,但这些仅用于预生产资产,因此只有图像、
文本和颜色和蒂像名称预览所暗示的那样,您正在测试的 ngs 如果它是
最终会进入您要推送应用商店的应用程序的资产,那么您
可以将它放在此处的资产库中,这样很快对项目中所有文件
的简要说明 在以后的课程中,我们将深入研究每个
文件,您将了解这些文件中的每一个如何在构建您的应用程序中发挥作用
最后一件事我想在本课中做的是给你一些关于在浏览
文件和编辑代码方面导航 xcode 的快速提示,所以首先
让我们谈谈在文件中导航你会注意到这些这里的两个箭头
非常方便,因为它可以让您转到您正在查看的最后一个文件
,虽然现在看起来有点微不足道,但是当您在文件中跳来跳去时,
这变得非常方便,而不必去和从导航中重新选择该文件 您可以直接回击并 跳回
之前的文件 您还会注意到您可以
在此处有多个选项卡,因此您可以按住控制并单击文件
,您可以随时选择在新选项卡中打开您也可以如果您愿意,可以在新窗口中打开,
因为我已经将它作为选项卡,那么它现在不会为我打开第二个选项卡,
如果您想并排放置,您也可以这样做,所以让我们假设我想
并排查看这两个文件,这样我可以关闭它,然后我可以继续,我可以
在右侧添加另一个编辑器窗格,这样我就可以将我的编辑器区域分成两个编辑器区域
,你可以看到在这里我正在查看 contentview.swift 在这里
让我们看一下测试应用程序,因此它们是独立的区域
,我可能只想摆脱我的画布,然后如果您喜欢
它们, 我可以看到这样的两个文件 水平堆叠您可以按住选项,
如果再次点击此按钮,您会看到该图标会正确更改 i t 将在右侧添加另一个编辑器区域,因此您
将分成三个,或者您可以按住选项,您可以在底部添加一个编辑器,
这样您就可以这样做,您也可以在此处按住选项和现在这样做是一种将文件启动到拆分编辑器视图中的快速方法
所以假设我正在查看测试应用程序并且我想将
内容视图打开为单独的编辑器区域我可以按住选项
并单击我的文件想要在单独的编辑器视图中打开,
所以这些是您可以使用文件的一些方式,只是为了回顾一下您可以导航您
可以返回和前进您可以有不同的选项卡,然后您也可以拆分您的编辑器
区域进入编辑器的多个实例现在我想谈谈编辑代码,因为这是
你将要做的很多事情,代码现在看起来很短,但它可以变得
更长,所以知道几种处理方法很方便在顶部你会
看到这种面包屑菜单和您会注意到,根节点对应
于右边,这是一个文件夹或组,您可以看到它,然后这是内容视图,这
是您正在查看的文件,位于 test 内部,在这里我们可以实际上单击它
,您可以跳转到代码的不同部分,您可以看到内容视图与该
正文匹配,因此这是跳转到代码文件
中不同部分的好方法,以防您的代码文件变得很长,您可以 还要在此处添加与您在此处看到的
内容 相对应的
不同注释, 以便您可以在此处看到
这个在未来所以
不要担心如果这有点太快了现在我想谈谈这个小按钮
你已经看到我用它来打开画布但你也可以打开这个迷你地图就在这里
,这个小地图将向您显示您的代码文件的大纲你可以拖动它来浏览你的
代码不幸的是我不能在这里做很多,因为这个代码文件不是很长,但是如果你
有一个非常长的代码文件,它会在这里向你显示那个代码文件的大纲您可以
通过单击并拖动它来轻松导航,您会注意到,即使我突出显示它,
它也会向我展示我的代码的不同部分,
这些部分再次与我们在这里所拥有的内容相对应,这些只是一些快速提示不要担心如果它飞得太快,因为
我们将在接下来的课程中一起使用所有这些东西,所以这是一个快速的 xcode
教程,让你开始,一旦你知道事情在哪里正确,就不会那么复杂,只是为了回顾一下
你发现在哪里下载 xcode以及如何开始一个新的应用程序项目您了解了项目中每个
文件的用途,并且您了解了 xcode 的主要领域,包括导航
器、编辑器、检查器和工具栏最后您还将学习一些有关如何操作的快速提示
导航现在有一个 xcode 不用担心如果它现在有点让人不知所措
,你会觉得 xcode 就像在家里一样,因为我们在接下来的课程中更经常一起使用它
来帮助你安顿下来我实际上创建了一个 xcode 备忘单您可以打印出来
并随身携带,因为您正在学习使用 xcode 来获取它,只需访问
学生仪表板顶部导航中的资源链接,最后我有一个测验让您在
下一课中进行巩固你今天参加测验后学到了什么 我强烈建议
你尝试在自己的计算机上创建自己的 xcode 项目,只是为了在
下一课中进行额外练习,我们将使用 xcode 来构建我们的第一个用户界面 好吧,我我们会在那里见到你
你好,欢迎在本课中你将学习如何使用 xcode
通过 swift ui 构建用户界面我们将首先学习如何预览应用程序,以便你可以实际看到
用户界面的外观然后我会告诉你如何使用 x用于可视化构建
用户界面的代码或简称为 ui 到目前为止,学习一直是
被动的,这意味着您可以坐下来观看视频,但从现在开始,我们将
切换到更主动的学习,我想要你做我在你自己的 xcode 项目中复制它的事情
,我希望你尝试我为你提供的任何挑战,这是最好的学习方式,
坦率地说,如果你只是坐下来观看课程不要做任何
你没有充分利用时间的工作这是我的个人经历,我认为这
对你来说也是一样的,所以如果你准备好了,我们将开始动手让我们开始吧,
让我们从创建一个全新的 xcode 项目开始,
我们将选择 ios 应用程序,我将调用这个 ui 测试
,只要确保界面是 swift ui 生命周期是 swift ui 应用程序和语言是 swift
除此之外你可以给它命名任何你想要的让我们继续保存我们的项目
和li ke 我在上一课中提到 contentview.swift 代表您的视图,但
您可以看到它都是代码,所以您如何真正看到您的 ui 看起来像什么有两种
不同的方法第一种方法是在 ios 模拟器中启动您的应用程序就像我之前提到 的,
所以让我们继续,首先选择一个你喜欢的,所以我要选择 iphone 11,如果这是你第一次启动
ios ,我现在要点击这个构建和运行按钮
模拟器 它需要一段时间才能启动,就像为我启动一个真正的设备一样
,因为我已经启动了模拟器,因为它发生得非常快,
你可以看到默认情况下你的项目有一个 hello world 标签,我们' 稍后再谈,
但首先让我向您展示另一种方式,您可以预览您的应用程序,所以让我们继续并
停止我们的项目,这将阻止应用程序在模拟器中运行第二种方式
是预览你在这个画布中的应用程序就在这里如果
你没有看到这个,你可以点击这里的这个小按钮,并确保
画布旁边有一个复选标记,如果你正在查看一个 dot swift 文件,这是一个
你将要成为 的视图 能够看到这个画布,否则如果你在
这里查看这个入口点文件,你可以看到没有预览,所以让我们回到内容视图,确保我们
在这里有我们的预览,然后单击恢复,它将构建并运行它,然后 如果这是您第一次这样做,您 将
在这里再次看到预览,这可能需要一点时间
让我们在这里使用缩放控件并缩小一点,以便我们现在可以看到整个
事情马上,我想在这里提到几件事,这只是一个预览
,而当您在模拟器中启动它时,您实际上是在虚拟
设备中安装该应用程序,以便您可以与之交互并在这里测试它 您无法与之交互 的预览,
但有一种方法可以让我如果您在此处单击此按钮
实时预览,它会进入一种模式,就像您之前看到的模拟器一样,
但它在此预览画布中,因此您可以继续并点击停止,然后再次变为
仅用于预览的普通预览使用此预览画布的另一个很酷的事情
是,您可以在此处点击此按钮,您可以选择不同的设备您
可以选择布局您可以选择深色模式或浅色模式,您可以选择许多不同的
东西这是首选预览 ui 的方法,因为当您通过
这一侧的代码构建 ui 时,您将能够在此处看到事情的变化,而无需立即
在模拟器中重新启动应用程序让我们深入讨论我们将如何
实际构建用户界面,因此请确保您已突出显示 contentview.swift 并继续
隐藏文件导航器现在这里有一堆代码组成视图
但我们将通过它稍后当您学习一些快速编程
基础知识以避免混淆时,我只想提请您注意一件事,这就是这里的这段
代码我在屏幕上突出显示的内容是生成此标签的内容
这里你在预览中看到的通知我们有一个文本关键字我们有
你可以在这里看到的 hello world 文本,我们也有这个填充元素,它给出了
单词周围的填充让我们来看看这段代码并将其分解我实际上只是
继续删除它,因为您可以看到 xcode 会引发各种投诉
和错误,但不要担心我们现在将立即修复它我们的用户界面元素
必须存在于这个左括号和这个右括号之间,你现在只能有
一个用户界面元素显然没有意义,因为我们的用户
界面由多个元素组成,但这就是容器元素发挥作用的地方
我将在本课中向您展示其中的几个,现在让我们重新创建该文本元素
,因此我们编写的是 text 关键字后跟一对括号,例如圆括号
,然后在里面我们有一对引号标记,然后我们放置我们
想要显示的文本,所以在这里我只是要打个招呼,但你会注意到,
如果你想添加填充,这个蓝色框架非常紧密地包裹在我的 hello 文本上
然后你会写点,然后你只需输入填充并使用自动完成
,你可以在那里选择那个,就像我们用填充重新创建了那个标签一样,
这里是文本元素或这个部分用点填充的标签这称为
修饰符,您可以将修饰符视为元素的附件,
在这种情况下会更改其外观和
行为做个水疗ce 围绕我们的文本元素
,实际上还有更多修饰符我们可以添加到我们的用户界面元素
中,例如我可以添加一个称为背景的修饰符,我只需将它添加到填充的末尾,
我会说这个标签的背景应该是蓝色的
,所以你可以看到我们的预览画布很好地代表了我们通过代码在这里写
的东西如果有任何时候事情不同步,也许你在这里写的代码是在
说背景应该是绿色的,但你在这里看不到它
代码被认为是事实的来源,因为最终预览画布甚至
你在检查器面板中看到的只是代码的视觉表示,
这让我想到了我的下一点when you're building the user interface you don't have
to write code there are so many visual ways for you to build the code let's erase this text
element again and let me show you some of the ways in which you can we can visually build the us er
interface i talked about the library panel before so you can see here that we can simply select
search for the text element select it and we can drag it into our code editor right here
and then we can change the placeholder text but we don't even have to change the text here if you
click on this text element and you go into the inspector panel you can change it here
like that and then also in this inspector panel you'll see that there are a bunch of modifiers
that we can add so to add the padding i could click this to add top padding only
and you can see that the code changes and it's specifying that i only want padding on
the top and you can see it reflected here or i can click this one here
and turn padding on or off and you can see now i have padding on all sides
so in addition to some of the modifiers that you see here down here there's a text box where
you can search for more modifiers so i can search for the background one and click that
and then select that blue background as you can see here and then i can also add that
padding now in addition to using the modifiers that you see here and using this add modifier
text box you can also use the library to add modifiers so this first tab gives you all of
the user interface elements that you can add to your view here on the second tab are modifiers
so as you can see there's the padding one there's the background one so how do you go about adding
these modifiers well you just click and you drag it but here you have to make sure that
you drag it to the end of the code because if you accidentally drag it in the middle of your code
it might not take or you might get something like that and that clearly is an error so
let's undo that so as if that weren't enough there are a couple more ways i want to show you
on how you can modify your user interface elements uh visually instead of writing code first of all
let's finish configuring this background and we're gonna select blue right there or maybe green
okay that's no t changing that so it is changing that but it's not changing here so
i'm gonna go ahead and select color and uh okay we can do green lowercase g all right so you can
hold down command on your keyboard and then you can click on the user interface element
from your preview right here and then there are a number of things you can do with that element
including this one show swift ui inspector and then again you get this add modifier text field
which you can search for modifiers to add so i'm going to add one called blur
you can see that it is blurring the color green and you can see that now my background is a
blurry green now you can do the same thing on the code editor side so you can hold down command and
you can click the text element and you get this menu you can again click show swift ui inspector
and from here you can see that this menu looks like the inspector here and we can also add
modifiers as well so to illustrate my point i've shown you a whole bunch of different ways for yo u
to modify your user interface visually you don't have to write the code but over time as you're
doing this in the visual manner you're seeing the code that is generated over and over again you're
going to get to a point where it's so familiar it's going to be faster for you just to type
it out rather than clicking everywhere so it's a really neat way to learn the user interface code
isn't that pretty cool xcode has come a long way in the past it used to be very fussy to use the
visual interface builder with xcode but swift ui has really changed things for the better
now in this lesson you learned how to use the text element
and how to modify its look and behavior using modifiers in addition to that you also learned
that the ui is actually generated from swift code however there are a multitude of ways in xcode
to build your ui visually and as you construct your ui visually through the preview canvas or
the inspector panel as we demonstrated the swift code in the code editor updates a utomatically to
reflect those changes so this is a great way to learn the swift code now to reinforce what
you've learned in this lesson i have a quiz and a quick challenge for you in the next lesson
so i highly recommend that you go through those to get familiar with using xcode to build uis
the next time we sit together i'll introduce to you additional views and containers that you can
use so that you can build more complicated user interfaces all right i'll see you there
hello and welcome in this lesson you're going to learn how to use a variety of different user
interface elements and containers and then at the end of the lesson i'll show you a couple
of user interfaces that i'd like you to try to build yourself as practice remember you're
going to get a lot more out of this course if you stop throughout the lesson and try to
replicate what i've done on your own xcode project alright enough talking let's get to the fun part
all right so you've learned about the text element now i w ant to show you the image element so
we're going to go ahead and erase this and why don't we use the library to look for the image
element so let's go ahead and drag and drop the image there now the problem is that
we don't have any image to display but before i tell you how to specify that just notice that
it's sort of in the same format as the text element right there is the image keyword here
and then there is a set of round brackets and in the middle we're going to put our image name
now this image name maps to whatever graphic asset we've put into our asset library so if we
open up our file navigator and we go into our asset library you can see that it's all empty
we don't have anything here so let's go ahead and put an image in here if you go into the
lesson resources you're going to see a zip file called logo assets and let's go ahead and unzip
them and then inside you're going to find a local image you're going to find three files actually
and they're named the same way except with an at 2x and an at 3x and that is literally just
two times as big as the first one and this one is three times as big as the first one and the
reason why they come in different sizes is because there exists ios devices with different screen
resolutions so by adding all three sizes the platform will pick the right size to use for the
screen resolution that it's being displayed on so all you have to do is grab all three and then drag
it into the asset library like this it's going to be smart enough to know that those three are
in the same group and it's going to give it a name you can always rename this so you can click it and
you can name it anything you want but this name right here is what you are going to be referencing
in the image element so go ahead and put in quotation marks that image asset name
and you should see it appear here oh actually automatic preview updating paused go ahead and hit
resume all right and there we see our image now by default it displays the image at the size of the
graphic asset that you imported however if you wanted to resize it scale it up or down you
can add a modifier called resizable when you hit that it will be able to stretch when it stretches
if you wanted to maintain the aspect ratio because you can see here it's all stretched
out and it doesn't look like the original image you can add another modifier called aspect ratio
and don't forget even though i am typing out these modifiers through code here
you can always add them through this menu right you can find it right there
and then the aspect ratio modifier allows you to select different ways in which this should
scale so if i say fit it's going to scale it up to fit within the bounds but with maintaining aspect
ratio and while we're adding these modifiers this would be a good point to mention that
a good practice is to hit enter on your modifiers here so that they become aligned because some
elements might have a list of modifiers and by putting them all on a new line they automatically
indent under the user interface element that they pertain to and it becomes very easy to read all
right now you know about text elements and image elements how do we go about combining the two
how do we go about having more than one element for our user interface this is where container
elements come into play so let's go ahead into our library and let's search for a vstack
this is the one that i'm referring to vertical stack and you can go ahead and click and drag
it in here now you're going to get some errors because this counts as an element too now it seems
that xcode hasn't caught up but this wouldn't be a valid ui essentially we have two elements here
what we want to do instead is we want to take our image and i'm going to cut that code and
i'm going to paste it in between this opening bracket and closing bracket of the vertical stack
inside the vertical stack you can put up to 10 elements and it's going to stack them vertically
on top of each other so here i'm going to also put a text element like that and you can see that
now i'm able to have two elements and they are automatically stacked on top of each other
in addition to the vertical stack there is also a horizontal one and instead of v stack that is
h stack and if you change that to an h stack you'll see that it's now stacked horizontally
beside each other and there's also one called zed stack i'm in canada or z stack if you prefer
and this places things on top of each other with the elements at the top being the farthest
in the back so you can see that our text element hello sits on top of the image
now a cool thing is that you can nest these different container elements so i can have let's
say i want my image logo to be the background and on top i want to have two text elements
side by side so then i can use an h stack in here and rather than
typing it out or dragging it from the library i'm going to show you another way in which to
embed your elements into these stacks if you hold down command and click on the element
you've seen this menu before you can embed in h stack and it's just going to create that h stack
for you and that's probably the easiest way to do it so in this h stack i'm going to add
hello world you can see here that now my image is behind this h stack with two text elements
now it seems pretty intuitive using these stacks right but how do you arrange the
elements inside the stacks well there are some options so if i click on this z stack here
actually let's take a look at the h stack so i'm going to go ahead and click that
this one actually has alignment so does that stack doesn't because it just puts everything on top of
each other but for the h stack and the v stack there's an alignment so you can choose to align
everything by their middles align everything by their baselines or align everything by the top
and you can also add spacing so you can see here i'm adding a spacing of three you can
see how it changes the code and it actually adds a spacing there now it's too little for you to
notice but let me add 20. you can see that there is a gap now all right so you've learned that
you can align the elements inside a stack and you can also add spacing between elements in a stack
but i want to show you another way of arranging elements inside of a stack in order to do that
i'm going to change this z-stack into a v-stack so we're going to get something like that now let's
say i wanted this logo to be at the top and i wanted my two text labels here to be at the bottom
one way i could do it is actually by adding spacing in my v stack right so let's say i
had a hundred you can see that they're pushed apart i can add more 300 but this
is a fixed value and as you know there are a ton of different screen sizes and resolutions
so this isn't a good way of approaching it let me get rid of this spacing value instead what
we can use is an element called a spacer so let me show you how that works in between the image
element and the h stac k containing the two text elements i am going to insert a spacer element
and the name of this element is spacer followed by two rounded brackets what this spacer element does
is take up all the available space it just expands and pushes everything away so you can see i've got
the image here i've got the spacer taking up as much space as i can and then my h stack containing
the two elements there the cool thing about the spacer element however is that it plays nice with
other spacer elements in the same stack so if i go up here above the logo and i add another
spacer element what ends up happening is that the two spacer elements both take up an equal
amount of space you can see above and below the war logo there is an equal amount of space if
i add a third spacer element beneath my h stack what do you think is going to happen
well all three spacer elements are going to share the available white space so the first
space for elements here second one here and the third one is there and it' s all
having an equal amount of space this is a great way to space things out equally now in fact i
could do the same thing with my h stack instead of specifying spacing here and notice this time
i'm just going to delete that spacing 20 there instead of changing it in the inspector
i can add a spacer there i'm going to copy that you can see here it takes up all the available
space pushing my two labels to the side but if i add one here on the right side it's gonna
push it to the middle and then if i add one in the middle then it's going to make it all equidistant
awesome you learned how to use the image and spacer elements in addition to the text element
you also learned how to use the v-stack h-stack and z-stack containers now it's time for you to
practice using these views and containers in a few challenges that i have for you in the next lesson
i highly recommend that you try them out the next time we sit together we'll be building
the warcard game user interface i look forward to s eeing you there and good luck with the challenges
hello and welcome in this lesson we're going to be building the war card game user interface
actually on second thought i'm going to have you try it first because i think you can do it
come on you give it an honest try and then we'll go through the solution together
now before we start i do have one request hit that thumbs up button below for some
extra good luck all right let's get started
alright so we're going to start with an xcode project launch xcode and let's create a brand
new xcode project we're going to choose app under ios and you can name this anything you want but i
am going to call this war challenge because that's what it is and it's a challenge that i'm confident
you can do interfaces swift ui lifecycle is swift ui app and language is swift leave the
rest unchecked and let's save it somewhere so i'm going to just save it on my desktop
all right here's our brand new xcode project let's go to the asset library first becaus e we're going
to add all of the image assets that we need for this app if you go into the course resources
folder under this lesson specifically you're going to find a zip file with all of the image assets
so go ahead and unzip that and then let's drag all of these assets into the asset library now you
should have the card back the background for the entire app and then you should have cards 2 to 14
and no you're not missing card number one the ace is card 14 and the reason i numbered them this way
is because we're going to use this number at the end of the card names here to represent the value
and we're going to compare this value to see which card trumps the other and then we're going gonna
have a deal button image and a logo image now just in case i didn't mention it before we have
three different sizes for each image because there are different screen resolutions for ios devices
so all of the newer devices have a super retina display and so they're using the 3x ones and
i don't th ink they actually make devices that use the one x image asset anymore but
this app was from a long time ago and we've rebuilt it many different times so we still
have all three now let me show you the finished user interface and this is the end result that
you're going to try to achieve yourself so this is what it looks like don't pay too much attention
to the spacing as long as you've got everything generally in the right place i think that's great
another thing to mention is that this is supposed to be a button but since we haven't gone through
buttons yet feel free to use an image element for that and that will be perfect for when we
do transition to using buttons and i can show you how to change that image element to a button
uh one other thing i have to mention to you is the concept of the safe area
now the safe area is this region that starts about right here
under the notch and it ends right here above this little handlebar and in some cases
there are actually margins on the lef t and right side as well and anything within this region is
in the safe area now this area is guaranteed not to be obstructed anything outside of the safe area
so anything in this corner or this corner could be obstructed as you can see by icons or by the time
and obviously there's this handlebar here that could be blocking things as well
if you want a full screen background like this green background that we have here you're going
to have to ignore the safe area because by default when you add elements onto the view it will try to
stay within the safe area so there is a modifier that i haven't shown you yet it's called ignore
safe area that you can apply to an image that will allow it to stretch beyond the safe area so
that it reaches the edges and that's probably the only other piece of missing information you need
other than that you've learned about stacks you've learned about image and text elements everything
you could need to build this user interface so go ahead pause this vide o and give it a try yourself
and then afterwards we will come back together and i will walk you through how to build this
so welcome back how did you do were you able to build this user interface
congratulations if you were able to build this or something that resembles this and if you got stuck
or you weren't able to don't worry because we're gonna go through it now and oftentimes i find that
if you try it yourself and get stuck and then later on find the solution those are oftentimes
the best learning experiences all right let's go through this together now now before we dive in
and start building this user interface i want to take a moment to sort of break down what
elements that i can see here so first of all i can see that we will need a zed stack because
we have an image behind all of these elements and so az stack is going to allow us to position
elements on top of each other next we have av stack where elements are stacked on top of each
other vertically so you can see av stack running through this entire user interface top to bottom
now some of the elements in this v stack will actually be contained within an h stack
like these two cards side by side for instance and this element down here is going to be an h stack
of two v stacks so this is av stack containing the two text elements this is av stack containing
the two elements and then you encapsulate them in an h stack so that's the breakdown that i see
and now we're going to jump into our contentview.swift and we'll build it out
all right so here i'm looking at the contentview.swift the first
thing i'm going to do is to change this simulator to iphone 11 and let's hit resume
and in a few seconds time might be longer we'll see a preview here perfect now let's change this
default text element get rid of that let's put az stack there open up a pair of curly brackets
now what's sitting behind all of those elements is an image right and
the image that we have is called background notice that it doesn't reach a ll the way to the top now
it does overlap that safe area a bit i said the safe area was under the notch right here so you
do see that it overflows but doesn't quite really go all the way there so we can add a modifier
called ignores safe area when you do that it's just going to cover everything
so okay so what's going to be on top of this background well like i said before we're going
to have a vertical stack containing all of those elements the first one being the logo and then
we're gonna have it an h stack with two cards and then an image element representing the deal button
and then after that we're going to have the score vertical stacks in a horizontal stack so let me
let me type this out so it makes a little more sense let's start with the logo at the top
we're going to have an image and our image asset name is logo so you can see it just
um just appears at the right size there and that's because our image asset is that size
okay now let's put an h stack in here and inside here we're going
to put two more image elements we're going to put the uh let's put card two
and then card three so we have two cards in an h stack and then after that we're
going to put another image element and this is going to be the deal button
and now comes the score labels so it's going to
be an h stack but inside of the h stack we actually have two v stacks
right each v stack contains two text elements so we're gonna have player
and we're going to have the actual score and then for this one we're going to have cpu
and we're going to have the actual score of the cpu
so we basically have all of our elements laid out now let's add some spacing to them
so to do that we can use spacers so let's start by adding a spacer uh right above
right above the h stack of the two cards below the logo image so i'm going to put a spacer element
right there and what you learned about spacer elements right it takes up all of the available
space however if you have multiple spacer elements in the same con tainer it's going to evenly divide
that space between the two spacers so i'm going to put another spacer right below the cards
so now you can see that there are two equal amount of spaces i'm going to put
another spacer below the deal button or image for now and then i'm going to put
a spacer below the score labels so you got to make sure that you don't put it in the wrong place here
we want to put it below this h stack and if you click this ending bracket you can see that
xcode briefly lights up the beginning bracket so you can verify that that's where you want it
all right and the last thing to do is put a spacer element above that logo so that's right here
now from a vertical point of view it's all spaced out nicely for this h stack with the two cards
why don't we put some spacers in there so let's start by putting a spacer in between the two cards
and then a spacer before all the cards and the spacer after the cards
we're going to do the same thing with the text labels down here
in this h stack we're going to put a spacer in between the two v stacks
and then we're going to put a spacer before it and the spacer after it
alright and now the last thing to do is just to change the font colors
of these text elements and also to change their font weights and font sizes
and maybe add a little bit of space in between the the score and the label
okay so let's click on this text element and take a look at what we could do so if you look
in the inspector panel for the font you can choose one of these pre-defined font sizes for this one
let's choose headline and you can see it it gets a little bolder there let's change this to white
and we're going to do the same thing for the cpu label we're going to change it to headline
we're going to change the color to white then for the actual score we're going to change the font to
let's say sub headline and we're going to change the color to white as well
and for that score label we're going to change it to
sub headline and we're go ing to change it to white as well all right and if we wanted to make it
actually not i think in in the original uh user interface i had it as large title so
i'm going to change it to that so i'm going to change the zero from sub headline to large title
now in order to add some padding in between the label and the score here
what you can do is choose the label let's start with the player here
and let's click on just this bottom padding so enable that and then you can change that
number to let's say 20. you're going to see that increase and that looks like a little bit too much
so maybe we'll stick with 10. we'll do the same thing with cpu here we'll click just the bottom
padding and then we'll add 10. you can see the corresponding code here it's adding padding but
it's specifying only for the bottom edge and at 10 points and this is a good practice anytime you
modify something visually adding a modifier or changing something in the inspector panel here
it's a good practice to take a loo k at what has changed on the code side just so you can
remember over time the more you see it the more you remember that hey if i wanted to
change it to a headline style font i would just have to add a dot font modifier and pass in a
dot headline option same thing for the foreground color for this text element dot foreground color
color dot white you don't need to try to memorize it but just pay attention to it and over time
you're just going to remember and typing it out will end up being faster than having to visually
click around and configure things through the inspector panel or the preview canvas
alright last thing to do make sure you save the project and you're done
so in this lesson you built the ui for the war card game in order to respond to user interaction
and to also programmatically change the card images we're going to have to learn some swift
programming basics so in the next four lessons you're going to be introduced to coding basics
with swift now if this is your firs t time learning to code take it slowly and don't try
to memorize any of the keywords instead a better way is just to do all the quizzes and challenges
at the end of each lesson and to make sure you have access to those visit codeworthchris.com
create your code with chris account or log into your existing one and then enroll in
the 14 day beginner challenge and there you can access all the of the supplementary material
after learning those swift programming basics we're going to come back to this war card game ui
and bring it to life with code alright thanks for watching and i'll see you in the next lesson
hello and welcome in this lesson and in the next three you're going to be learning the basics of
the swift programming language now these are the skills that you're going to have to have in order
to complete the war card game as well as to build the feature apps that we're going to do together
now if you've never coded before i know this might seem a little bit intimidating but i
real ly want you to stick with this and really pay close attention in fact open up xcode on your own
machine and type out exactly what i'm showing you this is really going to help reinforce the
structure of the language and all of the keywords there's no need to memorize anything at all i
guarantee that by the end of this module you'll be writing your own swift code all right let's dive
in i want to start by looking at the view update lifecycle of a simple app and show you where swift
code plays a part in each part of the lifecycle let's start with what you've already learned
in the previous lessons that the ui is generated from swift code we'll call this your view code it
generates a ui for your user to see now typically with an app we have some sort of data that we want
to retrieve and display for example a news app we'd want to get that data from a data source and
then retrieve it into our app and display it in our ui you can use swift code for this the swift
code can go and fetch the da ta and then process it into a format that our app can understand
then using swift code we can also link this data to our view code so that when the ui is rendered
from that view code that data can be displayed to the user and furthermore when the user interacts
with the ui suggest tapping a button we can use swift code to capture that event and respond to it
now based on what the user tapped on we might use some swift code to change our data
when this data change happens because we've linked that data to our view code that data
change is automatically detected and the new ui is re-rendered with the updated data so that the
user can see what has changed now this cycle is essentially all the app is doing over and over and
we'll explore this app view update lifecycle in more detail in future lessons but for now i just
want you to understand that swift code has a part to play in each part of this life cycle all right
from the last few lessons you've already seen the code for building ui so you sort of know what that
view code looks like let's shift our focus over to the data part where we can see what swift code is
used for keeping track of the data and furthermore what does data even look like in our app
in order to try out some of the swift code and to find the answer to our question let's use an
xcode playground a playground is a lightweight way to test some of our code without committing
to a full-fledged app project that we can do here think of an xcode playground like your doodle pad
but for code now to start a new one go to file click on new and then let's click on playground
we're going to choose a blank playground and let's give it a name
and let's save it somewhere we're going to close this navigator tab by clicking this button because
we don't need that now down here in the lower left hand corner you'll notice that we have a button
that called show debug area go ahead and click that to reveal this tray this debug or console
area is where we're going to output a lot of data so just turn that on make sure you see
this little area down here and then this button i want you to click it right now it's going to be
executing the playground it's going to run all of the lines of code in the editor area up here
notice however that you also have this little blue run button along the line numbers and this
lets you select which line you want to execute the code up to so if i hover over at line three and i
hit the button right here it's gonna run lines one two and three as opposed to this button here
which runs everything so the first time you run this playground it might take a
while might show the spinner for up to even a minute i want you to do that and just let it
run until it says ready to continue and that's going to set us up to run some code
in the next part for now let's just go ahead and delete these lines of code so we can start fresh
all right now that you're set up let's go back to our original question what does data look like and
how do we use swift code to keep track of it let's look at a couple of different types of data first
now let's start with a common data type a piece of text in swift you surround
text with quotation marks like this and this is known as a piece of string data
let's add a note for ourselves up here with two forward slashes
when you do that it's called a comment and it's a way for us to leave a note or a little piece of
documentation for us to remind ourselves or other people who might be looking at our code what that
code does and when xcode sees these two forward slashes it's not going to execute this line
now let's take a look at another data type integers so something that looks like this
in swift this is known as int short for integer and what about decimal numbers well
yes that's also a data type that swift can recognize and handle each of these they're
known as a double and swift can also handle boolean values so things like true and false
in swift this is known as bool now string int doubl e and bool these are all called data types
and it's how swift classifies data now these aren't all the data types that are available
but these are the by far the most common ones that you'll be using at least in the beginning and it's
a great starting point for us all right now let's take a look at creating and keeping track of data
in swift there are many ways to keep track of data but two of the most basic ways are using
variables and constants let's go back to our xcode playground and take a look at an example
let's start with our hello string data here now this piece of data on its own is going to be
useless to us unless we have a way to reference and track it and we can do this with a variable
so let's see how we can declare a variable to keep track of this hello piece of data
so we use the var keyword and that's for declaring a new variable
and then we type the name of the variable this name is what we're going to use to reference
that piece of data and recall it so i'm going to call this myvar and then we follow it with a colon
and then after that we put the data type that this variable is going to track
since the data that we want to reference is a piece of string data i'm going to put string here
and then next we usually in the same line that we declare the variable we assign the data to
the variable to keep track of and we can do that using the assignment operator which is just an
equals symbol and then on the right hand side of that we put the data that we want to assign to
this variable i'm going to take that and move that right here so essentially what this line
of code is saying we're declaring a new variable called myvar we are saying that it keeps track of
string type data and then we are assigning this hello string data to that variable it's kind of
like we're attaching a label to this piece of data called myvar now whenever i want to reference that
piece of data all i need to do is reference it by the variable name so let's give this a try we can
u se a special command that will output the data to the console area below here in the playground
and that command is just print followed by two rounded brackets and in between those brackets you
put the variable or whatever data that you want to output so i'm going to do that and then down
here i'm going to stop my playground and execute all the code in it again and then as you can see
down there it says hello that it's the contents of my var which is exactly what we would expect
notice that when i reference my variable i don't need to use the var keyword anymore that was only
to declare the variable and once i've declared my variable i can just reference it by its name
and i can also reassign new data to it i can use it over and over again i don't have to
redeclare it so for example after i declare it and assigned hello to it i can turn around and
assign something else to it let's assign this piece of string data called world
to my var and essentially what we've done here is we've told that variable instead to track
this piece of data so what would you expect if i execute the code in the playground now
we would only output world because myvar no longer is tracking that hello piece of data
now one thing i want to emphasize is the data type of the variable
if i specify that my var is a string type i can only track pieces of string data
so for example if i had an integer like 100 and i tried to assign that to my var well
i would get an error that's not allowed what i need to do instead is declare a new variable of
the in type to keep track of this piece of in data so let's go ahead and use the var keyword and name
it and then colon and then the data type that i want this to track and now that is completely okay
let's try printing that out xcode is not going to help you autocorrect any spelling errors
all right so we have world and 100. now as we're coding more together you'll start to notice
different sorts of naming conventions like what you see here where my variable names start with
a lowercase letter and then every subsequent word in my variable name starts with a capital letter
so that's sort of just a standard naming convention you really could do anything you want
but when you start coding more and working in teams it's important to have
a standard that everybody uses and this is a common one all right now one more thing i want
to talk about before we move on to the next topic is the fact that there are shorthands in xcode you
don't really have to type in all the information for example here we're declaring that this
variable myint is an int type and we're assigning integer data to it but the thing is we could
actually omit that data type and simply assign 100 to it when we do that xcode can see that
this is a piece of in data so it's going to assume that my int is going to only track in types
now that same rule still applies i mean after xcode infers that this variable
is in type because you've assigned 100 to it i cannot go and assign you k now a string to it
that's not going to be allowed because xcode has already detected that you know this should be an
in type so same thing goes for up here i don't need to specify the data type if i'm going to
assign a piece of string data to it right away because that tells xcode that this is going to
be a string type variable so that's just a little shorthand to save you some typing all right so you
learned how to declare a new variable assign data to it and recall that data by using the variable
name you also learned how to assign new data to that variable let's talk about the other way to
keep track of data constants so constants are just like variables except that you can't reassign data
to it once you've assigned the first piece of data to it so let's take a look at how to declare
a constant to keep track of this string data instead of the var keyword you use the let keyword
and then the rest is just the same as a variable so we start with a constant name
my const colon and then you guess that the data type followed by the assignment operator and then
we're going to move that piece of data to the right-hand side of that assignment operator like
that now let's try referencing this constant let's try printing out the data in my const
as you can see it works as expected now let's try to do the thing that's not allowed
let's try to assign something else to it
and as expected we cannot reassign data to it because it is a constant
now constants are useful it's an additional tool that we can use if we don't
expect that piece of data to change and so we don't need to make any changes to it ever
so when would you use a constant over a variable well it really depends what you're trying to do
you'll probably find yourself using variables most of the time because of their versatility
and because data changes however the best practice is to prefer constants over variables
where it makes sense in fact xcode is smart enough to know if you use a variable and you never end
up changing that variable it will suggest that you change that var keyword to a let keyword
and use a constant instead all right let's do a quick recap before we wrap up the lesson you
learned about the view update lifecycle and how swift code plays a part in it you learned about
data types such as string int bool and double you learned about how to use variables and constants
to reference data now i highly recommend that you go through the quiz and challenges for this lesson
to practice what you've learned today there's actually some new training in those challenges
such as how to perform math operations with variables also don't forget that you can print
out the swift cheat sheet from the resources link in the top navbar and keep it handy there's
no need to memorize anything you're making great progress so far and in the next lesson i'll teach
you how to organize your code statements into functions alright i'll see you there
hello and welcome in the previous lesson you learned about swi ft variables and constants
you learn how to create some data and declare a variable or constant to keep track of it
and if you did the challenge you also learned about math operations using variables well in
this lesson you're going to learn how to organize and group together your code statements so that
number one all of the code statements that you've grouped together can work together for a common
task and number two once your code is organized into groups you can choose which group of code
statements to run depending on what task you need to be done these groups of code statements are
known as functions in swift all right now let's take a look at the view update lifecycle diagram
from the previous lesson and see where functions might play a part in this life cycle remember that
when the user interacts with the ui swift code captures that event and reacts to it well here
we might have a couple of different functions depending on how the user interacts with our ui
for example the use r tapping a button might trigger the app to switch screens in that case
maybe we'll run function a to perform that task or on the other hand what if the user taps on an
item to see more detail then in that case we'll run function b to bring up the details screen
now let's go over the code that performs the data retrieval for example we might have a function c
that does the actual retrieval of the data maybe the networking code and it grabs the
data and then gives it to function d as input and the responsibility of this function might be to
process that data and turn it into a format that our app can understand so function d
takes that data as input and it outputs the formatted data for our app
now i could go on but as you can see functions are a basic component of swift
programming it's everywhere so now let's go and see how we can create our own functions
alright so here i have a brand new xcode playground and we're going to take a look
at the function syntax and just in case i haven' t explained it yet the word syntax is simply a word
describing the structure or the grammar of the language so function syntax to declare a new
function you start with the func keyword fu and c so it's a funky function and then you follow it
by the name of the function and then a set of parentheses or rounded brackets and then a set
of curly brackets inside the set of curly brackets you put your code statements anything you want to
execute or run whenever we call this function so let me just put some statements here let's say
declare two constants like this and then let's print you know a plus b so if i run this right now
and execute all these lines of code nothing is going to happen you don't see any output and
that's because we haven't actually called this function in order to call and to execute this
function we just have to reference it by the function name so that's my func followed by
the pair parentheses and that is how you execute all of the code in between here so let's try th is
out i'm going to stop executing and then run my playground again and we get 30 as we expect
if i wanted to run those set of instructions again then i can just simply call it again
and if i print it out now it executes that code twice now i want to go back to that view update
life cycle diagram for just a second because if you notice back in that data retrieval area
i said that we might have two functions c and functions d where c would fetch the data and pass
it into d as input parameters so that function d can work with that data and format it how we need
so a function being able to accept data into it to work with it is a very powerful feature
let's take a look at how we would declare a function that would accept some sort of input
data all right so i'm going to erase these two lines and i'm going to modify my function here
instead of declaring two constants a and b i am going to specify that a and b have to
be passed into the function so the way we do that is through the use of f unction parameters
in between the two rounded brackets that is where we would specify all of the parameters
we want to be passed into this function you can pass in multiple parameters but actually let's
just start with one let's just start with a so first i would put the name of the parameter so i
would want that to be a and then i would put colon specified by the data type that this parameter is
since i expect it to be int i'm going to declare this parameter as a followed by the data type int
and then i can erase this constant from here as you can see this is almost like a variable
declaration or a constant declaration except without the var and without the let here we're
specifying that whenever this function is called one int parameter needs to be passed in along with
it and it's going to be referenced by this parameter name a inside this function so now
you can see that nowhere did i declare a variable a or constant a but i can still
put a as part of my equation a plus b because a is being passed in as a parameter so let's take
a look at what calling this function would look like now i'm going to rely on autocomplete so i'm
going to type in myfun and you can see as soon as i do that it detects my function here
so i'm going to go ahead and click that and you can see that now in the process of calling this
function i also have to pass in an integer piece of data so i'm going to go ahead and pass in let's
pass in something different let's pass in five you can see here there indicates this is the parameter
that i'm passing in let's go ahead stop and execute run my lines of code again and this time
the output is 25 because 5 was being passed into the function plus 20 is 25. now going back to the
view update lifecycle diagram again function d accepts input as a parameter but it also
returns output so that is another very powerful feature of functions being able to take in some
input work with that data and provide some output back to the caller of the function so let' s take a
look at our playground and see how we can specify that a function should return some data so to
modify this function to indicate that it will return some data we go up here right after the
rounded bracket for the parameter and just before the start of the curly brackets in here we write
a dash followed by a greater than symbol which makes sort of like an arrow like output and then
we specify the data type of the output so what i'm going to do is i'm going to output the sum
of a and b instead of printing it out to the console so i'm going to erase this line
and then i'm going to output an int so that's where i specify that right after that dash greater
than symbol now you can see that xcode throws some errors now because in addition to specifying that
your function returns an in you actually have to return an int inside of the code statements
so as the last line of our code we can use the return keyword meaning that this is the data we're
going to return from the function and t hen we specify the in data that we want to return so i'm
going to return a plus b and all is well now keep in mind that whatever the data type you specify up
here in the function declaration that is the data type that you have to return if there's a mismatch
for example if i specified that this function returns an int but i go ahead and return a string
like a piece of text you're going to see xcode
complain about that as well because that is that is incorrect so we're going to return
a plus b and we're going to turn in so why don't we run our function now and see what
happens nothing happens well what's going on i'm returning a plus b so here's what's happening
calling this function is returning that data but i need to somehow reference and track that data
right and that's what a variable is for so i am going to declare a variable up here var
let's declare constant actually since i'm not going to change this let my sum equals
the result of that function so you can understand this code statement right we're declaring a
constant called mysum and then we are calling this function on the same line that returns uh 25 and
we're assigning 25 to my sum so now i can print my sum and let's double check that we get the output
there we go now before we move on there are two very important things that i want to mention
so this return statement actually ends the execution of that function so once this return
statement is run execution returns out of that function so any code statements that you put
down here like let's say i had return ab right there and i printed a plus b right here that
print statement is not going to be run see code after return will never be executed so that's just
important to keep in mind that when you write return and it executes that line of code
the execution stops and gets out of that function another thing that i wanted to mention is this
return type so earlier when i told you that declaring a function didn't have a return type
like that well it actual ly did it was just that the return type was void and void means nothing so
let me let me do a basic demonstration actually let me just declare another function down here
i'll just call this myfunc2
see back then i told you this was a basic declaration of a function but actually that
was a shorthand the full declaration actually has a return type of void like that if you're
not going to return anything but it's just that when you don't return anything
then you don't actually have to specify the return type of void so
so i just thought i'd mention that so you know what that void keyword means so if you
see some function that has a return type of void you know that that basically means
that it's not returning anything all right so now let's reset a little bit it's starting to
get a little messy so let's erase everything except that except our function right here
now i want to show you how we can pass in multiple parameters so instead of specifying b here let's
put b into the parameter lis ting here and have it be passed in instead okay so let me erase
this line of code so that we get b from up here well how do we add another parameter to this one
what you do is simply put comma and then declare another parameter for your function easy right
we're going to name this one b followed by colon and then the data type of b that's going to be
another integer all right so now let's take a look at how we call this function with two parameters
my func you can see that here now you just specify
oh one quick thing is when you're calling functions
an easy way to just fill in the parameters in the list is by pressing tab that just
brings you over to the next parameter that you have to fill so i'll put two and three
let's execute all of this code and we get a result we get no result remember i erased my line of code
so why don't we just print out the result instead of assigning it to a variable this time so i'm
going to go ahead and directly pass that function call into my print statem ent that's going to print
out the output of my function let's go ahead and run that code and we get five now obviously you
can have more than two parameters just put a comma in between each parameter in your function and
another thing i want to mention that's pretty cool with parameters is that you can specify a default
value for a parameter so for example for parameter bi could make this an optional input data
by specifying a default value for this parameter if i do that that means that when this function is
called passing in data for parameter b is going to be optional let's take a look at how this works so
after i specify the data type for my b parameter i can put an equal sign and then i can give it
a value let's say zero is the default value if b is not passed in then b is just going to be zero
now let's erase my function call and let's try calling it again and take a look at what
the autocomplete menu shows us here you can see that there are two different forms of my
function cal l now one is with parameters a and b so i pass in both pieces of data
and one is just simply passing in parameter a if i do that b is just going to be zero
but if i pass in both of them let's say i pass in 2 and 3 again then b is going to be 3 instead of
0. so that's one way to make your parameters optional now i want to talk about argument
labels as you can imagine the more parameters we have the more confusing things are going to
be in terms of these function calls especially when it comes to parameter names like a and b
well sometimes a and b makes sense in the context of the code inside of the function
but to the caller of the function a and b they don't mean anything so there's a
special feature called argument labels and let me show you what that looks like
so i'm going to declare a new function right here i'm gonna call it myfunk as well and i am going to
actually you know what i'm going to just copy this function and make a copy of it and show you how
how argument labels change it so an argument label goes in front of each parameter so each parameter
can have its own argument label and you're essentially just putting a name in front of that
parameter i'm going to call this first parameter i'm going to give it a an argument label called
first number and for my for the second parameter i'm going to give it an argument labeled called
second number so that's literally all it is an argument label is a name in front of the
parameter name separated by a space let's take a look at how this affects the function call
if i type in my func you can see here i still have the these first two ones a and b and that's from
the first function up here um but look down here i have first number and first number and second
number and this corresponds to my second function right here because uh the second
number is still optional right because i have this default value there so if i call that one
my function call becomes this my func first number one and second number three however
internally inside of that function i'm still referencing those parameters using a and b
so argument labels they're they're a way for you to distinguish the naming for a function call
um versus how it's referenced inside the code whereas if you omit the argument labels like we've
done up here then the parameter names are used for both the function call and also the referencing
of those parameters inside of the function so hopefully you notice the difference here one
cool trick you can do with argument labels is if you don't want to show any text in your function
call at all you can use an underscore as your argument label so if you do this
let's see what happens to your function call
so my funk you can see here these two correspond to
what i've done right here using underscores for the argument labels
so if you use an underscore for argument label the function calls just become my func and then
the first piece of data comma second piece of data there's no parameter names
there's no arg ument labels in your function call at all so this makes things really succinct
and really neat and tidy but it also makes things more confusing if it's not clear what
those parameters are supposed to be for so there's a lot of versatility here my personal
preference is simply to do it this first way and i don't usually specify any argument labels at all
and i simply use the parameter names okay last thing i promise before we end off with functions
is i don't know if you've noticed but we've declared two different functions here both
with the same function name we can't do that with variables right if you try to declare variable a
and then variable a again then you're going to get an error on the second one the next code is
going to complain you cannot redeclare variable a for functions things are a little bit different
functions have what's called a function signature and that is comprised of the function name the
parameter listing and then followed by the return type so let's type myf unc and take a
look at what the autocomplete menu gives us as you can see all four of these variations
have the same function name called myfunc but because the parameter values the argument labels
they're different xcode is able to discern and to know which function we're trying to call
right so if i call this one and i don't specify any parameter names or
any argument labels it knows that i'm trying to call this second one right here because
you know this method call this function call i mean it doesn't match this first one
whereas if i do my func and i specify parameter labels a and b then it definitely knows that i'm
trying to call the first one because this call this parameter listing here matches
up here okay so i promise you that we went a little deeper than you probably need to know
right now by showing you all of these um options and and ways that functions can be flexible as
we code together more you'll see me just using more basic forms of functions but at least hey
now you know a lot more and i'm sure you can appreciate how powerful these functions are
all right this lesson was pretty action-packed let's do a recap before we wrap up the lesson
first of all you learned how to declare basic functions and then you learned how to declare
functions which accept input data as parameters furthermore you learn how to declare a function
with multiple parameters and again functions wouldn't nearly be as useful if it couldn't
output data right you learned how to do that using return types and the return
keyword you also learned about argument labels and finally you learned about function signatures
now to really get the hang of functions and to reinforce your learning make sure you do the quiz
and challenge for this lesson and don't forget you have a swift cheat sheet that you can get
from the nav link at the top of your student dashboard and print it out and keep it handy
you don't need to memorize anything you're making great progress and in the
next lesson i'll show you how to organize your functions into structures so i'll see you there
hello and welcome so far you've learned about variables and constants and how they're used
to keep track of data you've also learned about functions for organizing and grouping together
your code statements well in this lesson you're going to learn about structures or structs for
short and these are the basic building blocks to represent your data or to represent something in
your app structures bring together the functions the variables and constants everything you've
learned so far in the last two lessons all into a neat little package all right let's dive in
and see what it's all about now let's do a quick recap first you had code statements like these
and then i showed you how to use functions to organize and group them together now with
structures you can group together your functions you can also have variables and constants keep
track of data inside your structure but outside of any function and we're going to talk about these
a little later in this lesson now let's take a look at our view update lifecycle diagram again
for the view code that represents your ui you might create a structure to represent
your home screen and all of the view code for your home screen would go into that structure
if you had a second screen in your app you might create another structure for that second screen
and all of the view code for that second screen would go into that structure
in this case each structure represents a different screen in your app now let's move over to the
data retrieval part of this diagram you might create a structure and call it a data manager
and you're going to put all of the code and functions related to retrieving and
processing the data inside of that data manager structure in this case the structure doesn't
represent a screen in your app instead it represents a crucial component of your app
so as you can see structures are very flexible and lightweight and they're used al l over your app now
let's go into an xcode playground and take a look at how we can declare our own structure
all right so here i've got a brand new empty playground let's take a look at how we can define
our own structures first you start with the struct keyword followed by a space and then the name of
your structure so i'm going to call this one my struct and then you put a space and you open up
a set of curly brackets inside the curly brackets you would put all of the code in your structure
and that's it we've declared our own structure now before we move on and take a look at what's
inside the structure i want to point out the naming convention of the structure notice that
i've started it off with a capital letter this is the standard convention this is different from
the camel casing that we used for the variables and constants and the function names those started
with a lowercase letter and it had each subsequent word starting with a capital letter whereas for
structures it start s off with a capital letter and then each subsequent word has a capital letter all
right now that you know about naming structures let's go inside and take a look at how we organize
the things inside of the structure so usually at the top of the structure inside the curly brackets
we would declare here all of our variables and constants used to track data that is related to
this structure now these have a special name as i mentioned earlier and we will get to that later
on in this lesson so up here after you declare all of the variables and constants tracking data
for the structure the next section you have are all of the functions related to the structure
now there are no clearly defined sections in a structure you know all of the code really just
goes in between the curly brackets but usually this is how you would organize all of the
different pieces of code inside of your structure so at the top variables and constants and then at
the bottom all of the functions so as you can see st ructures are great for grouping together
functions variables and constants all related for one thing but structures are usually meant to
represent something in your app in the view update lifecycle diagram that you saw earlier we saw
examples of a structure being used to represent a screen of your app as well as to represent a
crucial component of your app like that network manager so why don't we do another example
and i'll show you a structure that is a little bit more concrete let's model it after something
so earlier in the view update lifecycle diagram you saw that we could use structures to represent
a view in our app so let's go with that let's have a hypothetical chat app and let's say that this
structure represents my chat view so i'm going to change the name of my structure to chat view
now under variables and constants i might have a variable to keep track of the
message like the chat message that i'm typing into the chat box so i'm going to call this
message and the type of data this would be would probably be a string and i'm going to assign it
an empty string nothing in between just two quotes so that's what's known as an empty
string now under functions i could have groups of code that would perform different tasks on
this screen for example maybe when the user taps on the send chat button it would execute some
code to send the chat message to the server so i would declare a function so that's funk followed
by let's call this send chat and two rounded parentheses and i'm going to open up a pair
of curly brackets and inside here i would put the code to send the chat message and then in between
the variables and constants and the functions i would have the view code for this screen
that's all of the code for the ui so now in this chat view structure we have a neat little package
containing all of the code for that one screen now earlier i mentioned that the variables and
constants that you declare up at the top of the structure they have a different nam e so now i want
to tell you what that is this variable declaration that i have up here message this is known as
a property of the chat view structure if i had additional variable or constant declarations those
would be known as properties of the chat view structure as well and down here functions actually
also have a different name a function inside of a structure is known as a method of that structure
so this send chat function is actually a method of the chat view so now let's just
update our comments here so that we use the proper terminology instead of variables and
constants up here i'm going to rename this well not rename but just retype my comment and call
those properties and instead of functions these are going to be called methods just so we're clear
now inside of a structure properties and methods can actually work together to fulfill the duties
of the chat view let's take a look at some of the special ways in which they can work together
now let's take a look at this send c hat method for instance if we were to write the code here
to send the chat message it sure would be handy if we could access the actual message
in this message property right well we actually can so if i wrote something like this
print and then inside the parentheses i put the name of the property in fact i can access
that data and the reason for this is because this property is declared in the scope of this
structure so the scope of this structure is anything in between these two curly brackets
essentially the opening and closing curly brackets of the structure so any of the methods that
i declare in here for instance if i declare another one let's call this one delete chat
because these two methods are also in the same scope you know it's inside of the scope of the
chat view i am able to access the property the properties that you declare up here are
accessible to everything within the same scope so that includes all the methods that are declared
down here now i have to say that each method has its own local scope so this send chat method has
a scope inside here and this delete chat method has its own scope in between these curly brackets
so if i declare a variable inside my send chat method let's say var prefix equals chris says
and then let's say i use this prefix and i prepend it to my chat message so the entire chat message
would be chris says and then something so maybe i'll print prefix plus message to get that sort
of effect and i wanted to do the same thing inside delete chat if i try to access the prefix variable
and type print prefix plus message down here inside the delete chat method you'll see that it
xcode complains and it says it cannot find prefix in the scope
because this variable is not declared in the same scope it's declared inside the scope of send chat
so how would we fix this well one of the ways we could do that is to turn this prefix variable into
a property that we declare at the top of our structure you know move it outside of the scope
of sendchat and put it up here into the scope of the chat view instead so now that i'm declaring
my prefix as a property of the chat view you can see that the errors go away and i
can access this prefix property inside both send chat and delete chat methods
now i want to talk about another type of property first let's define what these properties up here
are these are called stored properties and the reason is because when you access these properties
and you reference them by their property name it just returns to you the value it's stored there's
another type of property where when you access it it needs to compute or calculate the value before
it returns it to you so let's take a look at what this second new type of property looks like
so let me start by erasing this prefix property up here and deleting that and then i'm going to
declare this new type of property it starts off just like a normal one you use var space and then
the name of the computed property i'm going to call it mes sage with prefix followed by the name
instead of assigning it some data you open up a set of curly brackets and here you can put the
computational code to compute the value that you will return when this property is called
one thing though because the value is not immediately known xcode can't infer what
the data type is so you actually have to specify the data type after the computed property name
so after message with prefix i'm going to put colon and i'm going to put string because that
is the type of value that this property is going to return this is different from this stored
property up here message where i can actually use the shorthand and erase the data type so
it's just var message equals string and i can do this because i am immediately assigning a value to
that property so xcode can look at that value and it can determine and infer what the data type for
that property should be with a computed property i have to explicitly specify the data type all right
so for my computed property message with prefix let's take a look at the code inside of the curly
brackets here i am going to use the return keyword just like with functions right i'm going to return
chris says so this is a string plus message so now in my send chat method instead of printing prefix
plus message i can just return message with prefix same thing for delete chat instead of prefix plus
message i'm going to return message with prefix so every time this property is accessed
it is going to run the code inside these curly brackets and return that as the value for that
property it needs to compute it that's why it's called a computed property now with computed
properties there's also a shortcut if there's only one line of code in here then i don't need
the return keyword because xcode can assume that this single line of code will output the data that
i want to return for my computer property so i can actually just delete the return keyword
however if i have multiple lines of code then i would de finitely need that return keyword because
xcode doesn't know which line of code is meant to be the value that gets returned so for example
inside my computed property if i say let prefix equals chris says and then down here i have
prefix plus message it's not going to know uh which code statement returns the value so
i actually have to use the return keyword like that and that's going to be fine now as far as
computed properties go there's definitely more we can talk about but this will suffice for now
in later chapters in this course we'll definitely go over computer properties again
all right let's do a quick recap before we wrap up this lesson you learned how
to declare a basic structure you learned about properties and methods in a structure
you learned about scope and you learned about computed properties as well now i know that the
hard part is wrapping your head around these concepts as we code further together you're
going to see these concepts put into practice to help you rem ember what you learned today i
highly recommend that you take the quiz and the challenge for this lesson and don't forget you
have the swift cheat sheet as well i just want to say one thing before we end you did it if you're
brand new to coding these three lessons were the mind-bending ones in the next lesson i'm going
to show you how these concepts relate to your actual xcode project alright i'll see you there
hello and welcome so you've learned a lot of swift in the last few lessons
you started with variables and constants and data types
then you learned about functions and then you learned about structures
that you can group all of those things together to represent or model something in your app
now this lesson is going to be the final piece of the puzzle not saying you're going to be a swift
master or anything but by the end of this lesson you'll see how all of the concepts and code fits
together and works together inside of a swift ui app all right with that said let's dive right in
all right so let's start with an empty playground do you remember back then when you learned about
functions and i taught you how to declare a function by using the func keyword followed by
the function name let's say my function followed by a set of parentheses and then a set of curly
brackets and inside of the curly brackets we would have the code for the function but this is just
a function declaration the no code is run nothing happens it's not until we call the function
that the code inside of that function gets executed right so i would call the function
saying my function and then parentheses if i run my playground right now you can see that
it outputs hello into the console so structures are like that as well when we declare a structure
using the struct keyword followed by the structure name so let's say my structure followed by a set
of curly brackets and then we put the code inside of the structure let me move my function in here
let's declare a property up here var messa ge equals hello and then let's print out my property
message inside of my function this is just a declaration of a structure it doesn't actually
do anything think of it like a blueprint for a building in order for us to use this structure we
need to bring it to life we need to create what's called an instance of the structure you can think
of it like turning this blueprint for a building into an actual building so how do we go about
creating an instance of this structure well that's easy you just write the structure name followed by
a pair of parentheses like that now just in case you're still fuzzy about the concept of
creating an instance of a structure let me give you a couple of different analogies to help you
try to understand this concept some people find it easier when i say that declaring a structure
or the declaration of this structure is kind of like a blueprint for a car or an architecture plan
for a house using that blueprint or using that architecture plan i can create car s
and i can create houses and those are the actual objects whereas the blueprint or the
architecture plan is more of like a template it simply describes how that thing is going to work
once you bring it to life so that's what's happening right here this is a declaration
of a structure it describes all of its properties and functions you know the things that it can do
and then it's only until we bring it to life by creating an instance of it that we can actually
use it so now that we have created an instance of it let's explore what we can do with it
now first of all we need to keep track of this instance because it's considered a piece of data
we need to keep track of it and have a way to reference it so let's create a variable called
i'm just going to call it a for simplicity's sake and i'm going to
assign that new instance to my variable a hey wait a minute if this instance is a piece of data then
what's the data type of this piece of data and what data type is this variable holding
well the data type is the name of your structure that's right so i can actually change my variable
declaration from var a to var a colon my structure yes your structure is its own data type so this
instance that you've created the data type of that is my structure now this little instance has
superpowers because we've designed it that way it can hold data in its message property and it can
output that message using the my function method so how can we go about accessing those things
of this instance well that's where dot notation comes in let's take a look at what dot notation is
so let's reference the variable a followed by a dot or a period and as you can see from the
autocomplete menu you can choose message which is accessing the property or you can select my
function which is going to execute the code in that method so using dot notation you can
access the properties and the methods of that instance let's try this out so first of all i
am going to assign something to the property o f this instance i am going to assign let's say hi
and then i'm going to print out a dot message just to show you that i can indeed access this property
and i can print it out next instead of using this print name in here i'm simply going to call
the method of that instance i'm going to call my function and i'm going to run this code again
and we still get hi because the code inside of this method actually just prints out the property
now this little instance is quite the action hero isn't it it can do all of the things
that we designed it to do now because this structure declaration is like a blueprint or
an architecture plan that means that we can create as many instances of it as we want
so let's go ahead and create a second instance this time i'm going to declare another variable
var b to store another instance of my structure now the important thing to note is that these
are completely independent instances going back to the car blueprint analogy it's like the car
factory made two cars from the same blueprint those two cars are treated as two different
cars same thing here i've just created two instances of my structure for example if i assign
a dot message to be hi and then i print out
b dot message or let me assign something else to b dot message and i print that out you'll see that
for a dot my function calling that method it prints out hi and when i print out b dot message
it outputs world to the console so you can see that each instance keeps track of its
own values inside the message property now you know that you need to create an instance of a
structure in order to use it let's take a look at how instances of structures can work together
now to use an earlier example from the previous lesson suppose i have a chat view in my app so
i've declared a structure to represent this view it groups together all of the properties
the view code and the methods related to my chat view and suppose that i had another structure
to group together all of the networking co de or the database code to save the data let's declare
something like that here so struct let's call this the network or let's call it the
database manager okay and suppose that i had a method in here so func let's call this save data
and the input parameter for this is the data that we want to save so let's say
let's declare a single parameter called data and make it a string type and it returns a value it's
going to return a boolean value true or false indicating whether the save was successful or not
true for successful false for unsuccessful and in real life it wouldn't be feasible to really return
a result instantly like this because depending on network conditions and other factors you
don't want to wait around for the data to save so you don't want execution to stop but for the sake
of simplicity let's just say that we can return a result right away so in here this this code
saves the data and returns a boolean result so in this example i'm just going to return
true so i'm just going to return a hard-coded value because i'm not going to implement this
method the main thing i want to show you is how the chat view is going to use the database manager
to save the message so back in the chat view in this send chat method for example i could
create an instance of the database manager so let's say var db equals database manager followed
by a set of parentheses and just like that i've created a new instance of that database manager
and now if i wanted to save my message i would call its save data method so db dot save data and
i would pass in my message property as the input data i'm going to go ahead and pass in message
but remember when i call this save data method it returns a boolean value for me to indicate
whether that save was successful or not so i can assign the output of that method to a constant
i'm going to call this was success right so i'm going to assign that boolean output
into a new constant called was success or maybe i'll just call it successful a nd then down here
i can write some code check the successful boolean value if unsuccessful
show alert to user now in future lessons you're going to learn how to write these statements
based on conditions but for now this comment will have to do the main takeaway for this example that
i'm showing you is the fact that within the send chat method of the chat view structure
it is using another structures methods by creating an instance of it so that's
how instances of structures can work together to make your app function
and this is essentially all your app is it's different instances of structures
working together to produce the views to handle the user input and to run the logic
now i want to talk about access levels for a second suppose for example in my database manager
i had some sort of information that i was tracking as a property that only the database manager
needed it wouldn't be relevant to any other structure maybe it is a server name or something
like that so let me just writ e a new property in my database manager called server name
and i will assign to it a string called server one now this property wouldn't be
interesting to any other structure but as you can see in the send chat method
i've declared this instance of the database manager if i write db
dot using dot notation i can access that server name property and sometimes you might not want to
expose these things so what you can do is you can specify an access level in front of that property
so in front of var server name that property i can put the keyword private so now it becomes
private var server name and by doing this it keeps that property accessible only
within the scope of the database manager so as you can see i can still access
server name inside of the save data method right it's in the same scope
but in the send chat method of the chat view down here if i use dot notation again
for my instance you can see that i cannot access that property anymore i can't see it
and furthermore you can a ctually do the same thing with functions so i can put private
in front of the funk keyword and now you can see that xcode complains i cannot run this method from
the sendchat method of the chat view now it's a good practice to be aware of which properties and
methods need to be accessible to other instances and other structures and mark everything else as
private doing this is a proactive way to prevent unexpected behavior and bugs from cropping up
alright and now for the final piece of the lesson i want to relate everything
that you've learned so far back to a swift ui app inside xcode so let's go ahead and do that
alright so now let's go ahead and start a brand new ios app project i'm just going to name this
test project and make sure that interface is swift ui and lifecycle is swift ui app language is swift
and we're good to go so i'm just going to save this on the desktop and we're going to first
jump into contentview.swift now i'm just going to change this to iphone 12 and i'm goi ng to hit
resume but the important part is the main thing i wanted to show you really is the code right take
a look at this struct you know that that means that content view is a structure there are some
keywords and bits of code that we're going to gloss over for now because we haven't learned
that yet and now is not the right time to go over it so i will gloss over a couple of things but
i really want to point out the concepts that you have learned so far and show you where they fit in
so this is a structured declaration let me just collapse this code for a second
there you go so you can see that this is a struct the content view is the structure name followed by
colon view and we're going to get to this in just a second and then you can see the curly brackets
containing all of the code for that structure all right so let's expand it again and let's
take a look at what else we've got okay down here we've got the var keyword so that's the start of
a property the name of this property is body okay so after that we've got colon and then we've got
some view now we're going to get to this again in just a second but you can see that there is a set
of curly brackets in here so that tells you that this is a computed property so let me collapse
the code again and you can see that indeed this looks like a computed property var body data type
and then a set of curly brackets inside is the code that gets computed or calculated to return
the value when this property is accessed so can you see all of these concepts that we learned in
the last four lessons are they coming back now i want to talk about this view and some view
so let's talk about this colon view in the declaration of the structure first
judging by how you've used the colon before you might think that this is the data type for the
structure but not quite that doesn't really make sense does it because remember the name of the
structure itself is the data type for instances of that structure so what is this colon vie w after
the structure name well when you're declaring a structure the colon after the structure name
indicates that this structure follows a protocol in this case it follows the view protocol
so what do you think about when you hear the word protocol well for me i think about it as a set of
rules or a set of actions for example kind of like the fire emergency protocol that a building might
have for what to do when a fire occurs or like the building code that a house developer has to
follow to build a house that is safe similarly in swift a protocol is a specification or a set
of rules that a structure has to follow this colon view part indicates that this content view follows
the view protocol in formal swift terminology content view conforms to the view protocol
now one important thing i have to mention is that writing colon followed by the protocol is
saying and declaring that you conform to the protocol but do you actually it's kind of like
raising your hand in and declaring somethi ng but do you actually follow the rules of that protocol
and so the code inside of this structure actually has to satisfy the specifications for
that protocol in this case for the view protocol to conform to it we have to have a body property
that returns some view as you can see here our content view structure does indeed satisfy
that rule so that's why it conforms to the view protocol so now that you understand what protocols
are you can see that the data type for this body property is actually any value that conforms
to the view protocol yes in this case the data type for this property isn't actually a data type
but it's actually any data type that conforms to a certain protocol in this case the view protocol
so inside of this code for this computed property it needs to return some instance
that conforms to the view protocol let's open up this code and see what we have
so what do we have here well we have a single code statement and remember what i said about
computed properties if it's only a single code statement then you can omit the return keyword but
you know i'm going to explicitly specify it so that it's clear for you so what's happening here
it looks like we are creating an instance of a text structure now one way to figure that out is
if you go into the utilities pane or the inspector pane and you go into the quick help tab right here
and you just put your cursor over the thing you want to look at so i'm going to click into this
text so as you can see here indeed text is a structure so we are creating an instance
of the text structure however you'll notice that creating this instance is different from
how we did it before because we used a empty set of parentheses here when we're creating an
instance of this text structure we're passing in some input data so yes you can actually pass
in input data as a parameter into the creation of an instance of a structure these are called
initializers now we haven't talked about that yet and we will in upcoming lesso ns but for
now just understand that there is a way for you to pass in input data into the creation of an
instance of a structure so that's exactly what's happening right here now you might be wondering
does this text structure conform to the view protocol well it must right because according
to this body property whatever is returned for this computed property has to conform to this
so again let's dive into the quick help so i'm going to hover over text i'm going to
go down and in fact i'm going to open up the developer documentation now if you're using
i think xcode 1 12.1 there was a bug that crashed when you tried to open this window
so you just have to update xcode if this crashes for you okay so this is the documentation for
text you can see that it is a structure and if you scroll all the way down i'm going to skip
all this stuff because i want to just show you that it conforms to two protocols actually but
what we're interested in is it does conform to the view protocol all righ t and another thing i want
to point out is that this remember this from early on this is a modifier and now to you it must look
pretty familiar right because it looks like we're calling a method this is dot notation right here
we are creating an instance of the text structure and then we're calling the padding method on that
instance see if i put it on the same line it might look a little more familiar for you
right so i hope the dots are starting to connect no pun intended okay so to relate this back to the
previous structures lesson where i showed you um how to declare a structure we had a couple
of different sections right so at the top here we would declare our properties and in fact this body
property is considered a property right but it also contains our view code so this would be where
our view code goes and then down here we would declare the methods for this structure okay so
i think you understand that this structure called content view represents the main view or the main
s creen of this app but then we say that structures by themselves don't really do anything you need to
create an instance of it for it to work well where are we creating an instance of content view well
for that we need to drill back up to the entry point of the app which is this right here so you
can see this by itself is also a structure and the name of this structure is the name of your project
and it conforms to a protocol called app so let's look at the quick help and see what this app
protocol is all about create an app by declaring a structure that conforms to the app protocol
implement the required body computed property to define the app's content now we have another body
computed property i'm going to skip over some of this scene and window group stuff i want to point
out that this is where we are creating an instance of that content view structure so do you see how
everything fits together furthermore let's go back to content view and let me show you something else
so for this i'm going to open up the canvas again and i'm going to resume the preview
look at this structure down here this is what is powering the preview that you see here this
structure isn't really used as part of your app it's only for previewing in the canvas right here
so it conforms to the preview provider protocol and it's got a property called previews
static keyword ignore for now we'll explain that in a future lesson and down here you can see that
an instance of your content view structure is being created and that's actually what's
being shown here in fact i can apply modifiers to this instance and it's going to change what
we have here so i can use dot notation to call modifiers which now you know are just methods
right of that view or of that instance actually instead of doing that why don't we
use the visual way and see how it changes the code so why don't i preview this i change actually i'm
going to change the scheme to dark mode so you can see it adds a modifier to that instanc e let's also
change the device to ipod touch you can see it adds another modifier called preview device
now what happens if i create another preview because you can click on this button right here
and it's going to create another preview down here you can see what happens to the code well it
created another instance of content view and it's got its own modifiers now this is grouped together
by a container a view container called group which we haven't really covered yet but we will
in the future just know that it groups together views so this instance of content view is for
this one up here and this instance is this one down here see i can change this scheme to light
and you can see it changes that here and i can change this device to iphone 12
and it changes that modifier there so they're independent instances
phew that was a lot to take in and that's why i never recommend for you to memorize anything
the more practice you get the sooner it's going to become second nature to you let's do a quick recap
shall we you learned how to create instances of your structure you learn how to use dot notation
to access the methods and the properties of your instances and you also learn about access levels
so you can control which properties and which methods can be accessed with dot notation finally
you saw how all of these concepts relate back to a swift ui app in xcode now you know what i'm going
to say next reinforce your learnings with the quiz and get hands-on practice with the challenge
and hey if you don't feel like you need the challenge do it anyways just to prove me wrong
now in the following lessons we're going to go back to our war card game and take all of this
newfound swift knowledge and bring that war card game to life in the next lesson i'll show
you how to use the button element to handle user interaction alright i'll see you there
hello and welcome in the previous few lessons you learned the basics of swift
programming and i showed you how those concepts appl y to your xcode project now let's get back
to swift ui and views specifically today i want to talk about the button view let's dive right
in all right so i've got a brand new swift ui project here i thought we would take a look at
creating some button instances in a fresh project together before we go back to the war card game
to use the button instance there so let's go ahead and delete this
text view right here and create some button instances a button is a structure just like that
text was and we need to create a button instance in other words we need to instantiate a button
that's just another way of saying it so let's go ahead and type button followed by opening a left
rounded bracket and that's going to bring up our autocomplete menu there are a couple of different
initializer methods we can use to create a button instance and these initializer methods
remember are just different ways of creating an instance while passing in some data two of the
most common ones that you're going to be using is this one right here where you pass in a string and
this data type string protocol just means anything that conforms to that string protocol and a piece
of text does this one will allow you to just pass in a piece of text to use as the button label
and it will also allow you to pass in a block of code to run when that button is tapped on
so let's take a look at these parameters in more detail so this first parameter for
the label of the button is pretty straightforward here you just pass in a piece of text
i am going to call this button click me and if we update actually our preview won't do anything yet
before we specify the second parameter the data type for this action parameter is something that
you haven't seen yet but it kind of looks like a function signature without the function name right
this is called a closure and simply put you can think of it as a block of code or like a function
without the function name you pass in a block of code as a parameter and when the button is tapped
on it's going to run that block of code again this is called a closure so let's take a look at how we
can specify the closure as a parameter now one of the easiest things you can do is you can highlight
this parameter and just hit enter and xcode is going to automatically open up a closure for you
to type your block of code in but i'm not going to do that right now because i want to go through
the steps and really break it down to you and show you what exactly you're specifying and then at the
end i'll show you what happens when you do hit enter and just let xcode open the closure for you
let's specify that closure manually for now all right so the type of closure that this expects
is the simplest type that you can see it accepts no parameters these two brackets right here these
two rounded brackets that is a parameter list just like you would have when you're declaring a
function but it's empty so there are no parameters and then next you see a dash followed by a greater
than symbol and you know that that means return type right and it returns void void means nothing
so it doesn't return anything and it doesn't accept anything it's very simply a block of code
all right so now that you know the type of function that it's expecting let's go ahead
and specify it so i'm going to delete that and i'm going to open up a pair of curly brackets
now i don't need to return anything i don't need to specify any parameters it's very simply
just a block of code so you can specify that with just a set of curly brackets and in between those
curly brackets you put any code statements you want so i'm going to just print out
hello world and that is your completed button let's run this project and see what happens
okay so we have a button in the middle that says click me when i tap on it it runs the
closure it runs the code in the closure and you can see that in down there in the console
it does print out hello world every time i click this button all right now let 's go back
to our xcode project because that's only one way to instantiate a button i'm going to add
a comment here and call this button instance with closure okay and then i'm also going to
put this inside of av stack actually i'm going to show you a shorthand a cool way to do it i'm
going to put in inside of v stack because i want to show you a couple of other ways to
create buttons so we're going to create a couple of buttons together go ahead and command click on
this button and you can just simply choose embed in v stack when you do that it puts the element
into av stack for you although it it failed to move my comment there so let's put that right
there all right so we've got one button and i want to show you the same button but with the shorthand
there's something called the trailing closure let me show you what that means so button
instance with trailing closure i am going to copy and paste the button we just declared and
create another copy of it so if in a parameter list the last parameter expects a closure
there is a shorthand and how it works is you take that last parameter out of the parameter list
and you simply put the closure after the method call let me show you what i mean so
in this parameter list the closure is that last parameter right so this is a prime candidate for
a trailing closure shortcut i take the closure itself so i'm going to
cut this out of the parameter list and i am simply going to add a space after the ending rounded
bracket and then just paste the closure like that and then i can go ahead and remove the parameter
label or the argument label out of that parameter list like that and these two button declarations
are exactly the same thing it's just that they are written differently one is specifying the
closure inside the parameter list and the other one is specifying it using a trailing closure
and this is why i wanted to show you this manually instead of just letting xcode open a closure for
you because when you let xcode do it i t's going to recognize that that closure parameter is the
last one and it's going to turn it into a trailing closure for you automatically so let me show you
that if i declare another button let's use the same one click me and then i tap on that action
parameter and i either double click it or i hit enter and let xcode open up the closure
it automatically changes it into a trailing closure so i thought that
would be really confusing for you if you'd never seen that before and so at least now
you know uh what a trailing closure is and why you know xcode does this for you okay so that
is just creating one type of button both of these ways are to create buttons where you just have
a piece of text as the label but what if you wanted your button to be an image or you know
an icon or something like that not just a simple piece of text well there is another initializer
method for the button that we can use for that so let's take a look at that button instance
with um with label view so let's go ahead type button open up a bracket and now let's take a look
at this other initializer method with an action and label parameter creates a button that displays
a custom label and you can see from the parameter list that the first oh let me let me go back to
that autocomplete menu taking a look at this parameter list now you can see that this action
closure parameter is the first parameter and then the second parameter is a label now for this label
parameter you can return any view that you want to represent your button so let's go ahead and choose
this initializer method you can see for the action closure right here if i double click it it's not
going to change into a trail enclosure and the reason for that is because it's not the last
parameter in the parameter list so that doesn't qualify to be turned into a trail enclosure
okay so when this button is tapped again i am just going to print out hello world into the console
but for the label you'll notice that i have some freedom to specify what sort of view i want to
return so here it's just returning a text view with a simple piece of text here called button
but i can i can return an image view for example i could return a stack of different views you
can return anything you want let me just resume the preview here so you can see the different
buttons we've declared okay so what i'm going to return here is maybe let's return an h stack
and i'm going to return a text that says edit and i'm also going to return an image in front
of that and for this image i'm going to specify i haven't added any images to our asset library
but i'm going to use something called an sf symbol now we haven't gone through sf symbols yet
we will do so in a future lesson however sf symbols are great because they're basically
an icon set that comes with xcode that you can just use in your apps and these
there are very special features of these sf symbols that we will go through in a future
lesson in this course there is a free mac app ca lled sf symbols that you can download
where you can browse all of the different symbols uh that are available to you for free so for
example i'm just going to use this pencil one each of these has a name which you can simply specify
and you'll be able to use it so for the image the initializer to use if you want to use sf symbols
is called system name and then you specify the name which you saw underneath the icon
the pencil i'm just going to put pencil right there and you can see that that icon appears
all right so now let's run this app in the simulator and take a look at what happens
okay so i can tap this one it says hello world tap that one it says hello world
tap this one also says hello world those are the the closures that i specified for all of
the buttons all right now you know how to specify a simple button with just the text for its label
you know how to specify a button which you can use any view as the button we're going
to go back to our war card game now and turn that d eal button image into an actual button
alright so now i have the war card game that we were working on
all the way back in was it lesson four or five but this is where we got to and if you remember
we had used an image for the steel button and this is the view code for that you can see that it's
just an image now you know how to turn this into a button so i want you to just pause the video right
now and try it on your own in your own project just as a little exercise after you've tried it
out for yourself or if you just got stuck continue playing this video and we'll do it together
okay let's try it out together so i am going to just create a little bit of space
here and we are going to declare a button using a button let's open up brackets
and let's choose this action label initializer method now inside the
action we're just going to open up that block of code but we're not really going to do anything
yet we will do that in the next lesson but for the label instead of a text button la bel and delete
that view and i'm simply going to move our image with the deal button into the label for our button
and just like that you you can't really see any visual change but however if you run this in the
simulator then you will notice that you can tap it it's an actual button another way if you don't
want to launch your simulator is you can hit this button right here for the live preview and
after it gets started yeah then you can go ahead and i have to hit resume on that
okay you can see now in the canvas because i have live preview turned on i can test out the button
that was your first introduction to handling user interaction in a swift ui app the pieces are
really coming together let's do a quick recap you learned how to instantiate buttons and that's just
a fancy way of saying creating button instances you learned about closures and how they're just
blocks of code like functions without a function name and then you learned about trailing closures
which are just a shorthan d and just to remind you a trail enclosure is when you have a closure
as a parameter in a method call and then it gets taken out of that parameter list and
instead is put at the end of that method call now to make sure you really understand all of
these things make sure you do the quiz and attempt the challenge in the next lesson i'm going to show
you a key swift ui concept that is going to allow you to change data and have the ui automatically
detect the change and then update the ui by itself all right i'll see you in the next
lesson hello and welcome in the last lesson you learned about the swift ui button and how to
handle user interaction well in order to change the data and then reflect that change in the ui
we have to learn about state properties and that's what this lesson is all about let's dive right in
all right so i want to revisit that view update life cycle diagram for just a second
do you remember when we showed a link from the data to the view code well let's go ahead a nd
do that with our war card game project so what sort of data do we have in this project well
if you take a look at the user interface here you can see that we need to keep track of which card
the player has which card the cpu has and then also the scores of the player and the cpu
so that's four pieces of data let's create four properties in our content view structure
to represent those four pieces of data so right underneath the opening curly bracket of content
view i'm going to go ahead and declare var uh cpu let's do player first player card equals and um
i'll just mimic the cards that we have there so we're gonna have card two and well actually let
me just i'll change it we can put something else to start and then cpu card equals let's say card
nine and then let's represent the player score and this is going to be an integer let's start
with zero as well cpu score equals zero all right so now we have these four properties representing
the state of the game these four properties ar e our source of truth because it represents
how the ui should look now how do we reflect these pieces of data in our user interface
well we need to reference these properties inside our view code
remember that these properties being declared in the scope of this structure means that it's
available to be referenced in any of the methods in the same structure as well as in this block
of code for our computed body property so if we look down here for this first card
that is right here and we have hard-coded a string in there saying card two instead of
hard-coding a string there let's put a dynamic value by specifying our playercard property
so let's update our automatic preview just to make sure that that runs and everything's good
and you can see that that card changes to card 5 because that is what the value of player card
property is let's do the same thing for the cpu card instead of hard coding card three here let's
put the cpu card property can you see that change and down here for the score instead of a string
of zero let's put our player score property now you're going to notice an error here it says no
exact matches in call to initializer and that's because for initializing a text instance we need
to pass in a piece of string data but player score remember this is an int property so it
contains int data but how we can get around this is we can turn our int into a string
well at least the string representation of a number so the way we can do that is we can create
a new string instance and just pass in the we can pass in the integer so this one would be player
score and we're going to do the same thing for a cpu score we're going to create a new string
and we're going to pass in the cpu score and just like that we have our four pieces of data being
represented in the view code and in turn in the ui now all we have to do is when the user taps on the
button we can update this data in the properties and have the ui automatically change right
well not so fast why d on't we go ahead and try and do that and let's take a look at what happens so
in the last lesson we had changed this deal image into an actual button
right now that action closure is empty let's put some code inside this action closure
for our button here we are going to update the cards and we're also going to update the score
now if you try to update the property like here let's try to update playercard equals card 11
you'll see that you can't xcode will complain and say cannot assign to property self is immutable
now self refers to the instance of a content view and immutable means that it can't be changed you
see instances are value types and because of the way that they are allocated in memory
they can't be changed now i know that makes absolutely no sense to you right now but i
promise you in a future lesson we will talk about that and then it will make complete sense for now
just understand that we can't change the value of our property unless we use a property wrapper
a propert y wrapper is a keyword in front of our property declaration that changes its behavior
now specifically i'm talking about the state property wrapper so let's go ahead back up to our
property declarations and see how we can use this state property wrapper to change the behaviors of
these properties so that we can change the values all we have to do is in front of the var keyword
of our property declaration we are going to write at state and by adding that keyword at state
that is going to indicate that that player card property is actually a state property
and it's going to allow us to update the value in it so let's go ahead and put this
property wrapper in front of all four of our properties so that they are all state properties
state properties have two special characteristics number one is that you can change the data in
them we've already talked about that but number two is that inside the view code
any references to state properties they will get notified of the data changes and th en your ui
will update automatically based on that new data so let's go ahead go down to the action closure
of our button and try to update some of these state properties and let's watch the ui change
okay so here we are and as you can see now the error is gone and i can put cpu
card equals card 12 and let's go ahead and update the score as well might as well just do that so
i'm going to say player score plus equals one that means to increment it by one
cpu score plus equals one as well and we'll save this and then let's go ahead and
do a live preview see if we can do that alright so this is a live preview when i tap on this button
it's going to run the closure here
wasn't that cool so when i tapped on that button we updated the data in the state properties
right and because in our view code it references those state properties they got notified and the
ui was re-rendered to show the new data now the problem is that every time we tap on the button
i mean it's incrementing the score whi ch is cool but the player cards aren't being randomized
so what we can do is we can use the random method of the instructor generate a random number
and then we are going to append that random number to the back of the card string
to generate a new card so let's take a look at how that would work generate a random number
between 2 and 13 because if you look at the asset library we have card 2 all the way to
card 14 actually so i would probably want to generate from 2 to 14. so i'm going to say
let player rand equals int dot random and this method allows us to specify a range
you can specify a range with the lower end of the range dot dot dot and then the upper
end and it should be inclusive if i remember correctly and we'll see in a second and let's
declare another one cpu rand equals int dot random in two dot dot dot 14 and then what we're going to
do is instead of specifying the number inside the hard-coded string i'm just going to specify card
and then i'm going to add player rand r ight and add cpu rand now we might not be able to do this
and as expected we can't because as you know from earlier in this lesson what we're trying
to do here is we're trying to append a integer to a string and what we have to do instead is convert
that integer to a string first get the string representation of that integer and
there this should be dynamic now so let's take a look at this and see if it's what we expect
this is perfect
the cards are randomizing what's not perfect is the score down here
we still need to determine which side wins and then increment the appropriate score so i am
going to comment out these two pieces of code because we don't want to just be incrementing
it by one each time now before we end off this lesson i really want to point out and stress how
powerful this framework is what we're doing here is tapping a button it's running this closure
and we are changing the value in this state property and because the state property is being
referenced inside of our view code here it is detecting that data change and then re-rendering
what we see in the ui and that happens automatically all we are doing is changing the
data in the past with ui kit this system didn't exist what we would have to do instead is update
the data just like we're doing here but we would also have to update each view element manually and
tell it what to display so what we'd have to do is get a reference to this image and then generate an
image from this asset name from the asset library and then set that image asset to this image view
and we would have to do that for this one as well and then we'd have to do it for the text here
and the labels so everything we had to do manually now all we have to do is update the data and any
pieces of ui tied to those state properties will detect the change and update automatically
now by definition a state property is a piece of data that this content view depends on
it's not something that other views would care about or depend on and so by that nature we can
add the keyword private and just control the access level to these pieces of data so that
they are only accessible within the context or the scope of this content view structure since
it's only this content view that depends on these state properties
all right we're almost at the finishing line we just have to compare the card values
and then update the score state properties appropriately
let's do a quick recap now you learned how to reference properties in your view code
you learned about the state property wrapper we also learned about some new terminology
including hard-coded values dynamic values and immutable meaning that it can't be changed now
remember you can get access to all these quizzes and challenges in the next lesson we're going to
go over conditionals and how to compare values using if statements alright i'll see you there
hello and welcome in this lesson we're going to talk about a swift construct that is going
to allow you to write code that says if this then that now this easy to use but powerful syntax is
going to allow you to express logic at a whole new level all right with that said let's dive right in
all right so i've got a brand new playground here i want to show you how if statements work before
we apply it to our war card game project all i have here are a couple of constants actually
more than a couple i have a bunch of constants with different simple values some integers
strings and boolean values and i want to use these constants to demonstrate how if statements work
now again the if statement is very powerful because it allows you to run
code based on some conditions so i'm going to use these constants as my conditions let's first
take a look at a basic if statement declaration i'm going to type it out first and i'll explain
each of the parts so you start with the if keyword and then you put some sort of
value or condition that evaluates to a boolean result so i'm just going to put e
and i'm going to open up a pair of curly brackets and inside here i will just print hello world
all right and that by itself is the most simple if statement as
you can see starts with the if keyword and then followed by either a boolean value
or some sort of code statement that evaluates to a boolean result followed by a set of curly brackets
and inside the curly brackets you put the code you want to run if the condition is true in this case
e is false right so it's not going to run that code because it doesn't evaluate to true however
if i changed this e and i was testing f instead then this code would run because
it evaluates to true now it can get pretty crazy because you can chain these things together so one
of the ways you can chain them together is using end and that's a double ampersand so let me just
indicate that there and how this works is if you'd write f
double ampersand let's say g then now you're testing both conditions and because you're using
and both conditions have to be true in order for t his code to be run so in this case because
f and g are both true right true and true means true okay and another example
is you can use or so these are double pipes the pipe key a lot of beginners they're not
sure how to press it on my mac keyboard this key is right under the delete key and right above the
return key and it's the character on the backslash key so i have to hold down shift and i have to hit
backslash to get that pipe so double pipes it might be different on your keyboard this is or
okay when you use an or instead of an end and you're chaining together two conditions like that
you're saying if either condition 1 is true or condition 2 is true then run this code
so for instance f and g are both true so that'll definitely run this code if i do f and e let's say
e is false remember this code will still run because at least one of the conditions is true
now again this can get pretty crazy because i can keep chaining it i can keep doing ors
or i can even throw an end in there so let's do that but this sort of gets confusing now because
this can be read in a couple of different ways is it e and g and then or f or is it f or e
and g do you see what i'm saying so for if i put brackets around these this might make more sense
if i do this that's saying if f is true or e and g are true then run the code however you know i
could also put brackets around it like this if f or e is true and g is true then run the code so
you can use brackets rounded brackets to help you differentiate which conditions to evaluate first
all right so far we've been using just the boolean values but there's still more i want to show you
with the syntax for an if statement before we go on to looking at integers and strings so along
with the if statement you can also extend that if statement to test another condition because
this is just testing one condition right you can then following the closing curly bracket of the
first code block you write else if and then you write another conditi on so let's say else if e
then put that else if g and then do that so what's going to happen here
is it's going to test this condition if this evaluates to false it's going to then test the
next one it's going to cascade down if this is false then it's going to go down to the next one
at any point while it's checking these conditions if one of them is true then it's going to go into
that branch it's going to run that block of code and it's going to skip the rest so this
allows you to test in this case three different branches or pathways and only choosing one the
first one being true but keeping in mind that it checks these branches from these conditions i mean
from top to bottom so the first one that hits that is true that's the branch that's going
to go on down and finally there is also another feature of if statements there can be a sort of
catch-all branch if none of those conditions above are true then you can have an else
code block so this code block runs at the very end if none of the conditions were
true and it didn't execute any of those branches so this is sort of like your
catch-all or fail-safe and again these are all optional you can have one else if you can have no
else ifs you can not have any else's and you can just have an else so if this condition isn't true
then it's just going to come down here right so this if statement is really powerful the
syntax is really simple to understand but it gives you so much flexibility in
which code statements to run depending on what is happening inside of your app okay so i'm going to
undo this so we can see sort of like a full-fledged if statement here
and i'm going to show you how maybe integers or strings can be evaluated as conditions
now in the example so far i've just been referencing boolean values and that's simple
but working with other data types like integers and strings you might have to use those in an
actual statement in order to evaluate to get a boolean result right for example instead of g
which is just a boolean value true let's use a in order to evaluate a boolean result i have to use a
comparison operator right so i can use greater than if a is greater than zero right this can
evaluate to a true or false and aside from greater than here are another a couple other you can use
so greater than less than you have greater than or equal to and you have less than or equal to
and then there's equality with equality you don't use a single equal sign because that's
for assignment as you can see up here we are assigning these values into constants
to compare equality you use a double equal sign instead so i can say down here does a equals zero
and of course it doesn't so this statement here is going to evaluate to false
and because this is an end operator both of these conditions have to be true and because this one is
false already then it's not going to come into this branch anyways we can change these as well
so you know if b is less than 3 or 4 i mean and if c is equal to 10. so those are some examples
of comparison operators that evaluate to true or false now for strings you can also do that you can
you can evaluate d for example as a string and you can test if it equals hello
so that's one thing you can do with strings you can still use greater than or equal to
for example if we had let h equals world and we can say if d is greater than h so we can do
that in this case it's going to compare the h with the w and because h is not greater than w
because it comes before w then this is going to be false one more interesting thing i want
to show you is the use of the exclamation mark so this one it basically flips the boolean value so
if g was g is true right if i put the exclamation mark in front of it
it's basically going to flip the boolean value so g is true i have the exclamation mark it's going
to turn it into false so it's not going to run this you could put it in front of this for example
and a doesn't the a does not equal zero because a is one as you can see up there but having this
in front of it is going to flip that to true and then now that i think of it you can test
inequality as well so not equals so i can test if a is not equal to 0 which is true
but then because i have this exclamation mark in front of it it's going to flip it to false
so lots of flexibility here and this is just an example right so it doesn't have to be this
complicated now i want to go back to our war card game and use the if statement to determine
which card is larger and then increment either the player's score or the cpu score
all right so here i have the war card game project and if you take a look at this part here where
we were updating the score we're simply incrementing the cpu and player score with
each dealing of the button now that you've learned about if statements in the xcode playground i'm
sure it's very trivial for you to implement it so that you're comparing player rand versus cpurand
seeing which number is bigger to determine which score to update now because we labeled our assets
correctly 2 being the lowest an ace being the highest having a value of 14 it's very trivial
to compare you just compare that ending number right and essentially that is the random number
so if you think you can do this pause the video right now and try it out for yourself you'll
learn a lot i promise even if you give it a shot and you don't get it the lesson is going to stick
that much more so go ahead and pause the video try it out and then unpause it and watch me do it
here
all right so welcome back let's implement this if statement to see which card is bigger so i'm
going to start with if and i'm going to first test if the player's number is bigger than the
cpu's number right i'm going to use greater than if that is the case then i am going to
increment the player score otherwise i am just going to increment the cpu score now
i don't care about ties and that's why i'm not comparing equality between the two random numbers
but you could defini tely do that in your version if you'd like actually there is a problem with
the way that i'm doing it here the cpu has an unfair advantage because in the case of a tie
the cpu does get the score right using this else statement so therefore i kind of do have to test
the other case so i'm going to test else if cpu rand is greater than player rand
then cpu score plus one otherwise if those two conditions are not true then it's a tie
and i don't want to do anything all right now let's try this out so i'm going to hit
live preview again and we'll just do it right here in the canvas i'm going to hit deal
so 14 is definitely bigger than 5 so the player gets a score jack is definitely well that's a
that's an 11 it's greater than 3 4 is greater than three so it looks to be working correctly
congratulations the war card game is complete you've learned how to build user interfaces how
to code in swift and you've completed your first app think back on day one of this 14 day challenge
how did you f eel back then were you nervous did you think you could do all of this
and now look how far you've come how do you feel about app development now now i've tried
to make this as easy as possible to understand and i hope you're able to gain some new skills
if there's one thing i could really use your help on though it's with user testimonials
you see i haven't been asking people and i don't have very many and it would help a lot
for people to hear from actual learners like yourself about how this challenge affected you
this would really help me grow my brand and in turn help many more people discover that they
too could learn how to code and make apps full transparency your testimonial might appear on my
website or on my social media so if that's okay with you simply visit codewithchris.com 14 day
and it'll bring you to a page where you can record your testimonial right from your browser
don't worry if you don't know what to say i have a question for you and you can just simply answer
it it won't take you more than two minutes thank you so much whether or not you can help me with
that i really appreciate you learning with me and having stuck through this challenge
now i know i'm making this sound like the end but really it's just the beginning of your app journey
in the next lesson i'll tell you what are the next steps and where to go from here
all right thank you so much for the testimonial and i'll see you in the next lesson
hello and welcome to lesson 13. now in this lesson it's going to be more of a hands-on and practical
challenge i want you to try to build this app on your own now you have all the skills you need
based on lessons one to twelve and this exercise is going to be a great way to reinforce what
you've learned and also to identify any gaps in your knowledge at this point so that we can go and
review it and also go and figure out what it is that you need to get up to speed before continuing
okay so let me just walk through this app you've got a title you 've got number of credits you've
got some images and when you hit this button it merely randomizes the images if they don't match
then you're going to lose credits but however if you get three matching ones which i can't seem to
do right now oh there we go then you would gain credits so this is very much like the war card
game except that now there are three things that you randomize instead of two and the image assets
are in the description in a link so you can make sure you grab those uh then you'll have everything
you need whether you think this is too easy or if it's too hard either way i highly recommend that
you try it because it's really the best way to learn even if you get stuck when you look at the
solution and you figure out how to overcome that obstacle that you're stuck on it's going to be
extra meaningful and it's going to really help commit it to memory and this belief about hands-on
learning is due to my own failure in the beginning when i tried to learn ios so this is not just you
know something i read or something i heard this is from my own personal experience that
it's there's nothing else that can replace it's the best way to learn so long story short
give this challenge a try we have a great forum that if you are viewing this on youtube or
on our website feel free to post in the app development section for hints or
you know if you want just a little guidance on the right direction so that you can complete it
post here if you are in cwc plus and you are you have access to the course students area
then post in the swift ui section in there and we'll support you there as well so that being said
good luck with the challenge and i'll see you in the next lesson
you've made it where do you go from here what do you learn next well there are still a ton of
skills to master before you can finally build any sort of app you want but i hope in at least doing
the war card game and completing this challenge it's helped you break through some mental barriers
a bout whether or not you can do this because now you should know that you can do this and
it's just a matter of time more learnings more obstacles overcome and more practice
before you finally reach your goal by the way if you've made a mental breakthrough like
i've just described i want to hear your story just visit codewithchris.com 14 day and spend
two minutes telling me about how things have changed for you i love hearing these stories
all right now back to the topic of today's lesson i'm going to share with you the next five things
you can do to make progress on your app journey and then after that i want to tell you about my
program cwc plus and how it can help you quickly and efficiently knock these five things down
now even if you don't have any interest in joining a program hear me out on these next five steps
because they are still the things that i think you should do in order to make progress next
number one more views and containers through doing the war card game you alrea dy learned about a
handful of them such as text image buttons stacks but there are a lot more views and containers that
you can learn about such as toggles pickers status bars shapes grids lists and the list just goes on
now learning how to use more views and containers is like getting a truckload of lego pieces your
options are going to expand greatly number two more types of apps why well think about it nothing
new ever comes from scratch you're always drawing upon your previous experiences what you've seen
what you've done what you've tried so if you want to build your own app the best thing you can do at
this point of your journey is to get exposed to as many different kinds of apps as possible with each
new app you're going to learn new architectures new patterns and new ways of doing things for
example how do you navigate from one screen to the next how do you download data from the internet
how do you save data to a database and how do you let users create accounts and log in th ese are
all different kinds of apps that you need to be exposed to before you can incorporate these same
elements into your app number three more xcode and swift now in this challenge we've lightly
touched on swift basics and how to navigate around in xcode but there's definitely more depth to both
as your apps get more complex and your projects get bigger you're going to encounter more problems
and more bugs to solve and you're going to need a deeper command of the swift programming language
so how do you learn more swift and xcode well it goes back to building more apps as you build each
app you're naturally going to learn more swift and xcode techniques number four mvvm now this one's
pretty important in swift ui this is the main architecture pattern and it stands for model view
view model in the war card game that you did we had the view part and we had some data properties
in it but in a larger swift ui app you would have models representing your data as well and view
models suppo rting your views this architecture pattern exists in any larger swift ui app so it's
pretty important to know do some google or youtube searching on mvvm to understand it at a conceptual
level and then next time you do a swift ui tutorial either try to spot the pattern yourself
or if you're building your own swift ui apps definitely try to put the pattern into practice
number five more apple frameworks apple has a ton of frameworks that you can tap into with your app
simply add the framework to your xcode project read the documentation and you'll be adding new
capabilities to your app such as machine learning augmented reality and so on now this is going to
take a little more experience because you need to read and understand documentation but it's a
good skill to start training because every year there's going to be new tools new platforms and
new frameworks for you to learn as an app developer the learning never stops and your
ability to learn quickly and to try things out will reall y determine your long-term success now
those are the five areas i recommend that you explore to make progress on your app journey
however i want to tell you about our program cwc plus which i believe is the best way for
you to make progress on all five areas in a step-by-step manner just like you've done with
this 14 day beginner challenge we've broken up your app journey into an acronym of three stages
apprentice performer and pro now at the very top of the app journey you have this 14 day beginner
challenge which is a huge accomplishment that you've finished because it's helped break down any
mental barriers that you've had and it's primed you with the swift ui basics that you need to hit
the ground running inside cwc plus you're going to continue on your app journey right where this
challenge leaves off inside the ios foundations course this course is going to take you through
building four apps of increasing difficulty and you're going to learn new skills with each app
by the end o f the course you'll be able to build multi-screened data-driven apps
that means you'll confidently build apps that can fetch data from a source
such as an api a data feed or your own data file and present that data to the user so apps like
weather apps statistics apps or information apps and so on following that you'll take the ios
databases course where you'll learn how to build more complex database driven apps and what does
that mean well it means that you'll be able to build apps that produce data whether that's data
from user accounts user generated content or user interaction finally you'll finish off the
apprentice stage with a design course where you're going to learn industry standard tools like figma
to design your apps now not only are these tools useful for designing apps but they're also
really useful for producing graphic assets for your marketing materials or your website
in fact many of the graphics that you see in my videos my websites and my apps they are produced
in figma which is what you're going to learn in the course honestly after these three courses
you'll be in really good shape and then it's just a matter of getting more lego pieces in
your toolbox to build things with and this goes back to what i said earlier build more apps get
exposed to more patterns architectures tools and services now this stage of the program contains
more app tutorials and many courses to drive you towards that goal but it also provides you more
opportunities to take the steering wheel yourself and that is the best way to learn there will be
less handholding and there will be opportunities for you to compare your solutions with mine as
well as with other learners on the same app journey going through this performer stage of
the program will really make sure that you refine your knowledge into hard skills at the pro stage
you'll be confident to start realizing your own goal if your goal is to work as an ios developer
i'll show you how to put together your resume how to create your online portfolio and how to start
creating opportunities on the other hand if your goal is to build apps then i'll share our process
with you and you'll get an over-the-shoulder look as we build our own app business
so that's the app journey that cwc plus will take you through if that sounds like something you want
to try just visit codewithchris.com courses i really hope to see you in there but either way
i want to thank you so much for sticking through this challenge and for learning with me
i hope you've had an awesome experience and if you had please share it with your friends and family
please help me get the word out and tell everyone about code with chris i appreciate you so much and
thank you for letting me be a part of your app journey alright i'll see you in the next lesson