微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift学习:1.常量与变量

复习Swift语言,总结一下知识点,记录下来,方便以后查阅。有哪里不对的地方,希望留言或回复指出,谢谢。


1.声明:

常量和变量必须在使用前声明,用let来声明常量,用var来声明变量。

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
你可以在一行中声明多个常量或者多个变量,用逗号隔开:

var x = 0.0,y = 0.0,z = 0.0
NOTE:
如果你的代码中有不需要改变的值,请使用 let 关键字将它声明为常量。只将需要改变的值声明为变量。

2.类型标注:

如果要添加类型标注,需要在常量或者变量名后面加上一个冒号和空格,然后加上类型名称

var welcomeMessage: String

3.输出常量和变量

var friendlyWelcome = "Hello!" NSLog("欢迎消息是:%s”,friendlyWelcome) 

Swift 用字符串插值(string interpolation)的方式把常量名或者变量名当做占位符加入到长字符串中,Swift 会用当前常量或变量的值替换这些占位符。将常量或变量名放入圆括号中,并在开括号前使用反斜杠将其转义:

!"println("The current value of friendlyWelcome is \(friendlyWelcome)")
// 输出 "The current value of friendlyWelcome is Hello

NOTE:常量必须有初始值。

示例代码

import Foundation


println("Hello,World!")


//定义常量和变量

let name = "sn"

println(name)


var newName = "邵楠"

println(newName)

var age = 30

var age2:Double = 30

println(age2)

var SNow = "hello"

println(SNow)

println("Hello\(age)"+SNow)

let lable = "The width is"

let width = 94

let widthLable = lable + "\(width)"

var tus = ("hello",23,12,"sn")

println(tus.2)

func getName() -> (String,Int)

{

return ("Hi,Sn",32)

}

var tus2 = getName()

println(tus2)

let http404Error = (404,"No Found")

let (statusCode,statusMessage) = http404Error

println(" Code is \(statusCode)")

println(" Message is \(statusMessage)")

let (juststatusCode,_) = http404Error

println("Just Code is \(juststatusCode)")

let http200status = (statusCode:200,statusMessage:"OK")

println("Code is \(http200status.statusCode)")

原文地址:https://www.jb51.cc/swift/327187.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐