加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 常量和变量

发布时间:2020-12-14 06:45:11 所属栏目:百科 来源:网络整理
导读:Swift 中什么是常量和变量 在Swift中规定:在定义一个标识符时必须明确说明该标识符是一个常量还是变量 使用let来定义常量,定义之后不可以修改 使用var来定义变量,定义之后可以修改 变量和常量的基本使用 import UIKitlet a = "Hello,playground"//a 为常


Swift 中什么是常量和变量

在Swift中规定:在定义一个标识符时必须明确说明该标识符是一个常量还是变量
使用let来定义常量,定义之后不可以修改
使用var来定义变量,定义之后可以修改


变量和常量的基本使用

import UIKit

let a = "Hello,playground"
//a 为常量,当一个字段定义为常量时是不可以修改的。下面的代码打开会报错
//a  = "123"

var b = 55
//b 定义为变量,是可以修改的
b = 20

常量和变量的类型注解

此处为官方原文:

You can define multiple related variables of the same type ona single line,separated by commas,with a single type annotation after the final variable name:

var white : String = "white"
//white 已经定义为 String 类型,white 的赋值只能是 String 类型
white = "white1"

//为 blue 定义类型为 String,则 red ,green 类型也为 String。推荐这种写法
var red,green,blue: String

//为 blue2 定义类型为 String,green1 定义为 Double ,则 red1 的类型也为 Double。不推荐这种写法
var red1,green1 : Double,blue1: String

//分别为 red2 ,green2 和 blue2 定义类型。这种做法很少,可读性也较差。不推荐这种写法
var red2 : Int,green2 : String,blue2: Double


常量和变量的命名

此处为官方原文:
Constant and variable names can contain almost any character,including Unicode characters:

let π = 3.14159

let 你好 = "你好世界"

注:上面的写法只是表明 swift 中支持这种写法,但不建议这么命名

常量和变量的打印

var welcome : String
welcome = "Swift"

//输出为:hello Swift World
print("hello (welcome) World")



参考资料

1,小码哥视频
2,swift 官方资料

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读