如题所述
å¨å©ç¨xcodeå建äºä¸ä¸ªå·¥ç¨ä¹åï¼å¨å
¶å¼åçé¢ä¸ï¼æ们ç¹å»âmain_swiftâ项ï¼å°±å¯ä»¥æå¼ä¸»ç¨åºç¼ç¨çé¢äºï¼ä»¥ä¸ææ代ç åå¨æ¤ç¼ç¨çé¢ä¸å®æã
åéå常éçå®ä¹ï¼
å¨swiftç¯å¢ä¸ï¼æ们éè¿âvarâå ³é®åæ¥å®ä¹åéãéè¿âletâå ³é®åæ¥å®ä¹å¸¸éã常éçå¼æ éå¨ç¼è¯æ¶æå®ï¼ä½æ¯è³å°è¦èµå¼ä¸æ¬¡ã
var myVariable = 42
myVariable = 50
let myConstant = 42
æ°ç»çå建ï¼
å©ç¨â[]âæ¥å建æ°ç»ï¼åæ¶å¯¹æ°ç»ä¸å ç´ ç访é®æ¯éè¿æ¹æ¬å·ä¸çç´¢å¼æ¥å®ç°ã
æµç¨æ§å¶è¯å¥ï¼
å¨swiftç¼ç¨ç¯å¢ä¸ï¼ä½¿ç¨ 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 { teamScores += 3}
else { teamScores += 1 }
}
å½æ°ç使ç¨ï¼
使ç¨å ³é®åfuncæ¥å建å½æ°ï¼ä½¿ç¨ â-> â符å·æ¥åéåæ°çåååè¿åå¼ç±»åã
å¨å¼ç¨å½æ°æ¶ï¼è°ç¨å½æ°ä½¿ç¨ä»çååå ä¸å°æ¬å·ä¸çåæ°å表æ¥å®ç°ã
对象çå建å使ç¨ï¼
swift使ç¨å ³é®åâclassâæ¥å®ä¹ä¸ä¸ªç±»ï¼ç±»ä¸çå±æ§ç声æåæ¯å¨ç±»éä½ä¸ºå¸¸éæåé声æçãå®ä¹æ¹æ³å¦ä¸ï¼
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
æ举åç»æï¼
使ç¨âenumâå ³é®åæ¥å®ä¹æ举åç»æã代ç å¦ä¸ï¼
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescrition() -> 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 //å¼ç¨æ举常é
8
é对æ¯æ®µå°ä»£ç ç段ï¼å¤§å®¶å¯ä»¥ç´æ¥å¤å¶ç²è´´å°ä¸»ç¨åºç¼ç¨çªå£ï¼ç¹å»âè¿è¡âæé®æ¥æµè¯è¾åºææã
åéå常éçå®ä¹ï¼
å¨swiftç¯å¢ä¸ï¼æ们éè¿âvarâå ³é®åæ¥å®ä¹åéãéè¿âletâå ³é®åæ¥å®ä¹å¸¸éã常éçå¼æ éå¨ç¼è¯æ¶æå®ï¼ä½æ¯è³å°è¦èµå¼ä¸æ¬¡ã
var myVariable = 42
myVariable = 50
let myConstant = 42
æ°ç»çå建ï¼
å©ç¨â[]âæ¥å建æ°ç»ï¼åæ¶å¯¹æ°ç»ä¸å ç´ ç访é®æ¯éè¿æ¹æ¬å·ä¸çç´¢å¼æ¥å®ç°ã
æµç¨æ§å¶è¯å¥ï¼
å¨swiftç¼ç¨ç¯å¢ä¸ï¼ä½¿ç¨ 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 { teamScores += 3}
else { teamScores += 1 }
}
å½æ°ç使ç¨ï¼
使ç¨å ³é®åfuncæ¥å建å½æ°ï¼ä½¿ç¨ â-> â符å·æ¥åéåæ°çåååè¿åå¼ç±»åã
å¨å¼ç¨å½æ°æ¶ï¼è°ç¨å½æ°ä½¿ç¨ä»çååå ä¸å°æ¬å·ä¸çåæ°å表æ¥å®ç°ã
对象çå建å使ç¨ï¼
swift使ç¨å ³é®åâclassâæ¥å®ä¹ä¸ä¸ªç±»ï¼ç±»ä¸çå±æ§ç声æåæ¯å¨ç±»éä½ä¸ºå¸¸éæåé声æçãå®ä¹æ¹æ³å¦ä¸ï¼
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
æ举åç»æï¼
使ç¨âenumâå ³é®åæ¥å®ä¹æ举åç»æã代ç å¦ä¸ï¼
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescrition() -> 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 //å¼ç¨æ举常é
8
é对æ¯æ®µå°ä»£ç ç段ï¼å¤§å®¶å¯ä»¥ç´æ¥å¤å¶ç²è´´å°ä¸»ç¨åºç¼ç¨çªå£ï¼ç¹å»âè¿è¡âæé®æ¥æµè¯è¾åºææã
温馨提示:答案为网友推荐,仅供参考