Apple had released Swift for almost 2 years, and recently they openSource swift 2.0. As an iOS developer, I thought it’s necessary to get in touch with swift. After busy working, I make sometime to learn it.
First, create a playground, and according Apple document, start learn some basic syntax, here is the new feature i’ve learned.
import UIKit
var str = "Hello, World"
//************常量************
let constValue = 12
//************变量************
var variableValue = 10
variableValue = 11
variableValue
//初始值没有初始化,需要声明类型
let explictDouble : Double = 70
//practice
let myFloat : Float = 4
//************类型转换*********
let label = "The width is"
let width = 94
//转换一
let widthLabel = label + String(width)
//转换二
let widthLabelTwo = label + "\(width)"
//**************字典和数组************
var shoppingList = ["fish","rice","milk","meat"]
shoppingList[1]
var alexPersonInfo = [
"name":"alex",
"age":"24"
]
alexPersonInfo["name"]
alexPersonInfo["age"]
let emptyArray = [String]()
let emptyDictionary = Dictionary<String,Float>()
//****************控制流**************
let individualScore = [33,44,55,66,77]
var teamScore = 0
for score in individualScore{
if score > 50{
teamScore += 3
}else{
teamScore += 1
}
}
teamScore
//可选值使用 "?" 表示
var optionalString : String? = "Hello"
optionalString == nil
var optionalName : String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName{
greeting = "Hello + \(name)"
}
//*************switch 支持各种类型的比较**************
let vegetable = "red pepper"
switch vegetable{
case "celery":
let vegetableComment = "1"
case "cucumber","watermelon":
let vegetableComment = "2"
case let x where x.hasPrefix("pepper"):
let vegetableComment = "3"
default:
let vegetableComment = "default"
}
//*****************for-in*************************
let interestingNumbers = [
"Prime":[2,3,5,7,11,13],
"Fibonacci":[1,1,2,3,5,8],
"Square":[1,4,9,16,25,36],
]
var largest = 0
for (kind,numbers) in interestingNumbers{
for number in numbers{
if number > largest{
largest = number
}
}
}
largest
var firstForLoop = 0
for i in 0 ... 10{
firstForLoop = firstForLoop + i
}
firstForLoop
//********************while && repeat-while*************
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
repeat{
m = m * 2
}while m < 100
m
//*************控制转移********************************
// continue,和之前相同
// break,和之前相同
// fallthrough,由于Swift中case后没有break,此处的fallthough就相当于break
// return 和之前相同
//***********************函数和闭包**********************
func greet(name: String, day: String) -> String{
return "Hello \(name), today is \(day)"
}
greet("ALex", day: "Tuesday")
//返回多参数
func getGasPrices() -> (Double,Double,Double){
return(1,2,3)
}
getGasPrices()
//传递多参数
func sumOf(numbers:Int...) -> Int{
var sum = 0
for number in numbers{
sum = sum + number
}
return sum
}
//函数嵌套函数
func addInlineFunction() -> Int {
var y = 10
func add(){
y = y + 5
}
add()
return y
}
addInlineFunction()
//函数作为另一个函数的返回值
func makeIncrementer() -> (Int -> Int){
func addOne(number:Int)->Int{
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
//函数作为函数的参数
func hasAnyMatches(list:[Int],condition:Int -> Bool) -> Bool{
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number:Int) -> Bool{
return number < 10
}
var numbers = [20,19,7,12]
hasAnyMatches(numbers, condition: lessThanTen)
//外部形参
func join(s1:String,s2:String,joiner:String) -> String{
return s1 + joiner + s2
}
//当调用时候不够清晰
join("alex", s2: "wu", joiner: ",")
//通过添加外部形参来
func joinOut(string s1:String, toString s2:String, withString joiner:String) ->String {
return s1 + joiner + s2
}
joinOut(string: "alex", toString: "wu", withString: ",")
//更简单的版本
func joinOutSimple(stringOne stringOne:String,toString:String,withJoiner:String) -> String{
return stringOne + withJoiner + toString
}
//****************对象和类***************
class Shape {
var numberofSides = 0
func simpleDescription() -> String{
return "A Shape with \(numberofSides) sides"
}
}
var shape = Shape()
shape.numberofSides = 5
var shapeDescription = shape.simpleDescription()
class NamedShape {
var numberofSides : Int = 0
var name : String
init(name:String){
self.name = name
}
func simpleDescription() -> String{
return "A Shape with \(numberofSides) sides"
}
}
class Square:NamedShape {
var sideLength:Double
init(sideLength:Double,name:String){
self.sideLength = sideLength
super.init(name: name)
numberofSides = 4
}
func area() -> Double{
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)"
}
}
let test = Square(sideLength: 5.2, name: "alex")
test.area()
test.simpleDescription()
//练习
class Circle:NamedShape{
var radius : Double
init(radius:Double,name:String){
self.radius = radius
super.init(name: name)
numberofSides = 0
}
func area() -> Double{
return radius * radius * M_PI
}
override func simpleDescription() -> String {
return "A Circle with radius \(radius)"
}
}
let circleObj = Circle(radius: 10, name: "alex")
circleObj.area()
circleObj.simpleDescription()
class EquilateralTriangle:NamedShape {
var sideLength : Double = 0.0
init(siLenth:Double,name:String){
self.sideLength = siLenth
super.init(name: name)
numberofSides = 3
}
var perimeter : Double{
get{
return 3.0 * sideLength
}
set{
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(siLenth: 3.5, name: "triangle")
triangle.perimeter
triangle.perimeter = 9
triangle.sideLength
//************************枚举*****************************
enum Rank:Int{
case Ace = 1
case Two,Three,Four,Five,Six,Sever,Eight,Nine,Ten
case Jack, Queue, King
func simpleDescription() -> String{
switch self{
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queue:
return "queue"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
//**************************结构体*********************
struct Card {
var rank:Rank
var suit:Suit
func sipleDescription() -> String{
return "the \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank:.Three, suit:.Spades)
let des = threeOfSpades.sipleDescription()
//从服务器取日出日落时间
enum ServerResponse{
case Result(String,String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("out of range")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
//*************************接口***********************
protocol ExampleProtocol{
var simpleDescription:String{
get
}
mutating func adjust()
}
//接口实现
class simpleClass : ExampleProtocol{
var simpleDescription : String = "A simple structure"
var anotherProperty : Int = 69105
func adjust() {
simpleDescription += "(adjusted)"
}
}
var a = simpleClass()
a.adjust()
let aDes = a.simpleDescription
struct SimpleStructure : ExampleProtocol {
var simpleDescription : String = "A simple structure"
mutating func adjust() {
simpleDescription += "(adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDes = b.simpleDescription
//**************************添加扩展*************************
extension Int : ExampleProtocol{
var simpleDescription : String{
return "the number \(self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
extension Double : ExampleProtocol{
var simpleDescription : String{
return "the number \(abs(self))"
}
mutating func adjust() {
self += 0
}
}
4.5.simpleDescription
//***************************泛型************************
//在尖括号里写一个名字来创建一个泛型函数或者类型。
After overview basic syntax, I plan practice it into demo. So,Here is a simple demo about show fonts in iOS. You can download it on github
https://github.com/surrenderios/iOSFontsWithSwift