// Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
str+=",Yes I'm Good";
println("hello swift")
var myvar=23
myvar=18
let myConstant=42
var a:Double=10
let label="this width is"
let width=94
let widthlabel=label+String(width)
"I have \(width) apples."
"I have \(String(width)+String(width)) apples"
var shoppingList=["C","B","D","E"]
shoppingList[0]="A"
shoppingList
var dict=["A":"yes","B":"no"]
dict["A"]
dict["C"]="Cancel"
dict
var emptyArray=String[]()
emptyArray.append("A")
emptyArray.append("C")
emptyArray
var emptyDict=Dictionary<String,Float>()
emptyDict.values
emptyDict=["A":1,"B":2,"C":4]
let individualSocres=[1,2,45,6,2,0]
var teamScore=0
for score in individualSocres{
if(score>8){
teamScore+=3
}
else{
teamScore+=1
}
}
teamScore
var optional:String?="Hello"
optional=nil
var t="H"
if optional==nil {
t="hello \(optional)"
}else{
t="XX"
}
let vegetable="1cecery"
switch vegetable{
//Case 用法
case let x where x.hasSuffix("cery"):
let v="Is it a spicy \(x)"
case "cecery":
let v="add some";
case "cecery","":
let v="tttt"
default:
let v="tastes good"
}
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
}
var firstForLoop=0
for i in 0..10{
firstForLoop+=i
}
//多返回值参数
func greet(name:String,day:String)->(String,Double){
return ("hello \(name),today is \(day)",99.0)
}
greet("jack","2014-06-09")
//数组参数
func sumOf(numbers:Int...)->Int{
var sum=0;
for num in numbers{
sum+=num
}
return sum
}
sumOf()
sumOf(19,0,3)
//嵌套函数
func returnFifteen()->Int{
var y=10;
func add(){
y+=5;
}
//调用了才执行
add()
return y;
}
returnFifteen();
//函数可以作为另一个函数的返回值
func makIncrementer() -> (Int->Int){
func addOne(number:Int)->Int{
return 1+number;
}
return addOne;
}
var increment=makIncrementer();
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, lessThanTen)
//类定义
class Animals{
var name="";
//构造函数
init(name:String){
self.name=name;
}
//方法
func WhatsName()->String{
return "my name is \(name)!";
}
}
//注意构造函数的调用方式
var cat=Animals(name: "dog");
//cat.name="cat";
cat.WhatsName();
//类的继承
class Pig:Animals{
var age:Int{
//在设置之前可以执行某段代码,之后执行用didSet
willSet{
println("aaaa");
}
};
//Getter And Setter
var Age:Int{
get{
return age;
}
set{
age=newValue;
}
}
init(age:Int){
self.age=age;
super.init(name:"Pig");
}
func HowOld()->String{
return "pig is \(age) years old";
}
//重写
override func WhatsName()->String{
return "pig is a clever animal!";
}
}
let LittlePig=Pig(age:3);
LittlePig.HowOld();
LittlePig.WhatsName();
LittlePig.age;
LittlePig.age=4;
LittlePig.Age=8;
class Counter {
var count: Int = 0
//方法参数名,可以在为方法体内部使用单独定义一个别名,例如times
func incrementBy(amount a: Int, numberOfTimes times: Int) {
count += a * times
}
}
var counter = Counter()
counter.incrementBy(amount:2, numberOfTimes: 7)
//?之前如果为nil,则之后的会被忽略,否则执行
var os:String;//?="hello jack";
var ai:String?="BBBBB"
//枚举
enum Rank: Int {
case Ace = 1,Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.toRaw())
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
ace.simpleDescription();
//struct结构体,值类型,类为引用类型
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("36:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
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 IUser{
var simpleDesc:String{get}
mutating func addJust()
}
class SimpleClass:IUser{
var simpleDesc:String="Very well";
func addJust(){
simpleDesc+=" Now implement";
}
}
var test=SimpleClass();
test.addJust()
test.simpleDesc;
//接口是可以用来扩展类型的功能的
extension String: IUser {
var simpleDesc: String {
return "The number \(self)";
}
mutating func addJust() {
self += "S";
}
}
"OK".simpleDesc
let tx:IUser = test;
tx.simpleDesc
//范型
func repeat<T>(item: T, times: Int) -> T[] {
var result = T[]()
for i in 0..times {
result += item
}
return result
}
repeat("knock", 4)
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [4,5])