[swift学习之二]基本语法练习

//: Playground - noun: a place where people can play

import UIKit

/*注意点
 1:  Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始值,也就是说变量不会有默认值,所以要求使用变量之前必须要对其初始化。如果在使用变量之前不进行初始化就会报错:
 2:  String是值类型,NSString是引用类型
 3:  Bool值的比较不能用nil,false!=nil
 4:  字典和数组支持了基本的数据类型,NSNumber没啥用了~
 5:  三目的运算符要和变量间加空格,否则会吧?认为解包(自己的理解啊~)
 */
//------------------------//
/*亮点1:变量或常量的类型可以省略,会根据注意点1,判断类型*/
let label:String = "my old is"
let myOld = 33
print(label + String(myOld))
for character in label.characters {
    print("\(character)\n")
}
//------------------------//
var optionalString: String? = "Hello"
var OptionalName = optionalString?.uppercaseString
if let name = OptionalName {
    /*如果不判断,就得加!解包*/
    print(name + optionalString!)
    if let name2 = optionalString{
        print(name2 + " Hello \(name)" )
    }
}
//------------------------//
var nickName: String? = "ss"
var fullName: String? = "John Appleseed"
/*??如果可选的值丢失,用默认的值替代,只针对带?的变量或常量*/
let informalGreeting = "Hi \(fullName! ?? nickName!)"
if let a = fullName where (fullName?.hasPrefix("John A") == true),let b = nickName {
    print(a+b)
}
//------------------------//
/*亮点2:和oc的block遍历有一拼~*/
let simpleArr: Array<Int> = [20,10,30,40]
for (index: Int,value) in simpleArr.enumerate()
{
    print("\(index):\(value)")
}
//------------------------//
/*simpleArrB复制了一份,并且不可变*/
var simpleArrA:NSMutableArray = NSMutableArray(array: [20])
let simpleArrB:NSArray? = simpleArrA.copy() as? NSArray
simpleArrA.insertObject(30, atIndex: 0)
/*亮点3:if条件let+where*/
if (simpleArrB != nil) && (simpleArrB?.count == 1){
    for a in simpleArrB!{
        print(a)
    }
}
if let bufB = simpleArrB where simpleArrB?.count == 1{
    for a in bufB{
        print(a)
    }
}
//------------------------//
var Mutabledic:Dictionary = [Int:Array<Int>]()
Mutabledic[3] = [10,20]
Mutabledic[4] = [30,40]
mainFor:for(key,values) in Mutabledic{
    for key in values{
        if key > 0{
            print(key)
/*亮点4:Break还可以这么干~*/
            break mainFor
        }
    }
}
for a in Mutabledic
{
/*亮点5,Pair的值直接索引了~*/
    print(a.1)
    print(a.0)
    break
}
//------------------------//
let vegetable = "red pepper"
/*亮点6:switch居然支持字符串,而且还有个let a where 赋值*/
switch vegetable {
case let x where x.hasPrefix("red"):
    print("Is it a spicy \(vegetable)?")
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
/*没有default也报错~*/
default:
    print("Everything tastes good in soup.")
}
//------------------------//
var total: Int = 0
/*亮点7:For的开闭区间还能这样表示*/
for i in 0..<4{/*0+1+2+3*/
    total+=i
}
print(total)
total = 0
for i in 0...4{/*0+1+2+3+4*/
    total+=i
}
print(total)
//------------------------//
/*函数参数用逗号隔开,oc是空格。返回值类型写在了后面,而且还用了c++的箭头~*/
func greet(name:String,day:String)->String
{
    return "name:\(name),day:\(day)"
}
print(greet("Hello", day: "World"))
//------------------------//
/*亮点8:函数的返回值还可以这么写,这是要上天啊~*/
func CalculateStatistics(values:[Int])->(max:Int,min:Int,sum:Int)
{
    var vMax:Int=values[0]
    var vMin:Int=values[0]
    var vSum:Int = 0
    for element in values {
        if element>vMax {
            vMax = element
        }
        if element<vMin {
            vMin=element
        }
        vSum+=element
    }
    return(vMax,vMin,vSum)
}
let rValue = CalculateStatistics([10,20,50])
print("sum:\(rValue.sum)max:\(rValue.max)min:\(rValue.1)")
//------------------------//
/*亮点9:参数可以这样写,c++早支持。0个和多个都行,其实就是[Int]。但实参可以分开~*/
func CalculateSum(value1:Int...)->Int
{
    var sum = 0
    for a in value1 {
        sum+=a
    }
    return sum
}
print(CalculateSum(3,4,6))
//------------------------//
/*亮点10:函数嵌套的语法简单明了啊。比oc的block强。下面我写的block,写法不一定最优啊~
 NSInteger (^CaluelateSum)(NSInteger) = ^NSInteger(NSInteger value){
    NSInteger vValue = 0;
    NSInteger (^Square) (NSInteger) = ^NSInteger (NSInteger v){
      return v*v;
    };
    vValue = Square(value);
    return vValue + 2;
 };
 NSLog(@"%ld",CaluelateSum(8));
 */
func funcNested(value1:Int)->Int
{
    var vValue=0;
    func Square(v:Int)->Int
    {
        return v*v;
    }
    vValue = Square(value1)
    return vValue + 2;
}
print(funcNested(5))
//------------------------//
/*亮点11:函数当返回值。写法相当简单明了,比block强点儿。下面我写的block,写法不一定最优啊~
 typedef NSInteger(^funReturn)(NSInteger);
 funReturn(^CaluelateSum)(NSInteger) = ^funReturn(NSInteger value){
     NSInteger (^Square) (NSInteger) = ^NSInteger (NSInteger v){
       return v*value;
     };
 return Square;
 };
 funReturn rReturn = CaluelateSum(7);
 NSLog(@"%ld",rReturn(8));结果:56
 */
func ReturnFun(AName:String)->((aValue:String)->String)
{
    func RealFun(aValue:String)->String
    {
        return AName + " " + aValue + " ByLYQ"
    }
    return RealFun
}
let rFun = ReturnFun("Hello")
print(rFun(aValue: "World"))
//------------------------//
/*亮点12:函数当参数以及函数的匿名写法。现在脑子有点乱,先静静~~*/
func HasByConditionNumber(Source:[Int],Condition:(Int)->Bool)->Bool
{
    for a in Source {
        if Condition(a){
            return true
        }
    }
    return false
}
let haveMoreThan20 = HasByConditionNumber([1,2,30], Condition: {
    (A:Int)->Bool in
    return A>20
})
print(haveMoreThan20 ?"有": "没有")
//------------------------//
/*这个放这里不太合适,突然到泛型,泛型约束了。暂时先这样吧,以后再说。
 注意
 1:没有以前的Container协议了,这里还没弄清楚,因为以前什么样,我也不知道~
 2:_ArrayType不能用CollectionType协议替代,原因是count返回值类型
 */
func allItemsMatch<C1, C2
    where C1:_ArrayType, C2:_ArrayType,
    C1.Generator.Element:Equatable,
    C1.Generator.Element == C2.Generator.Element>
    (someContainer: C1, anotherContainer: C2) -> Bool {
    if someContainer.count != anotherContainer.count {
        return false
    }
    for i in 0..<anotherContainer.count {
        if anotherContainer[i] != someContainer[i]{
            return false
        }
    }
    return true;
}
print(allItemsMatch([1,2,3], anotherContainer: [1,2,3,5]) ?"相同" :"不同")

初次学swift,希望以后别接触别等语言了,快乱套了。

如果以后就用swift混饭吃,抱苹果大腿,该多好。

参考:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1

你可能感兴趣的:(swift,语法)