• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swift 基础

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、简单类型

println("say goodbey")    //无需添加”;“ ,也不用java,c等添加main{}函数

let strName = 1024;      //定义常亮,一次定义多次使用,#default kXXX 45类似

var strPhoneNumber = "hehe";  //定义变量,系统会自动识别你的类型

let strName :Double = 90.0;   //这里可以在初始化时定义其类型

 

//这里是转换类型

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

 

//这里实现跟上边一样,两种方式而已

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.

//创建数组,字典

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations”

 

//初始化一个空数组,字典(如果你用过java、c#那么你对泛型有一定理解咯)

 

let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

当然如果不能确定类型可以用

let emptyArray = []()
let emptyDictionary = [:]()

二、逻辑控制

使用if,switch,for in,for,while,do-while,(小括号可省略,方法体的大括号是必须的)

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores{

  if score > 50 {
    teamScore += 3
  } else {
    teamScore += 1
  }
}
teamScore

 

//下边optionalString变量的类型后有一个问号,代表Hello这个是可选值,当然也可以置为nil表明不存在

var optionalString: String? = "Hello"
optionalString == nil

//if和let一起使用可以防止值丢失

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
  greeting = "Hello, \(name)"
}

 

//switch与传统的区别在于不在对条件限制为int,而是多种类型,进入case后会跳出,所以不用在写break;这点倒很像apple风格:)

let vegetable = "red pepper"
switch vegetable{

  case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."

  case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."

  case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"

}

使用for in即foreach遍历字典

let interestingNumbers = [
  "Prime": [2, 3, 5, 7, 11, 13],
  "Fibonacci": [1, 1, 2, 3, 5, 8],
  "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
  for number in numbers {
    if number > largest {
      largest = number
    }
  }
}
largest

 

var n = 2
while n < 100 {
  n = n * 2
}
n

var m = 2
do {
  m = m * 2
} while m < 100
m

 

//..的意思是0-3,一个范围:)

var firstForLoop = 0

for i in 0..3 {
  firstForLoop += i
}
firstForLoop

var secondForLoop = 0
for var i = 0; i < 3; ++i {
  secondForLoop += 1
}
secondForLoop


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift学习之函数和简单地控件的创建发布时间:2022-07-13
下一篇:
Swift学习(一):自定义运算符operator发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap