변수(Variable), 상수(Constant)
import UIKit
var str: String = "Hello, playground"
str = "Happy Coding!"
print(str)
let otherStr = "홍길동"
print("안녕" + otherStr)
print("안녕\(otherStr)")
var myInt: Int = 8
print(myInt * 2)
print(myInt + 100)
myInt = myInt + 1
myInt = myInt / 5
print("최종값은 \(myInt)")
let age = 35
print("내이름은 \(otherStr) 그리고 내 나이는 \(age)")
var a: Double = 8.73
var b: Float = 8.73
var c = 7.12
print(a / c)
print(a / Double(b))
print(Double(myInt) + a)
var gameOver = false
print(gameOver)
var gameOverString = String(gameOver)
let d: Double = 5.76
let e: Int = 8
print("The product of \(d) and \(e) is \(d * Double(e))")
배열(Array), 딕셔너리(Dictionary)
import UIKit
var strArray: [Int] = [10, 45, 55]
print(strArray)
strArray.append(100)
print(strArray)
strArray.append(70)
print(strArray)
strArray.insert(60, at: 3)
print(strArray)
strArray.remove(at: 3)
print(strArray)
print("배열의 크기는 \(strArray.count)")
strArray.sort()
print(strArray)
if strArray.contains(10) {
print("값이 존재한다")
} else {
print("값이 없다")
}
var emptyArray = [String]()
print(emptyArray)
emptyArray.append("홍길동")
print(emptyArray)
emptyArray.append("임꺽정")
emptyArray.append("이순신")
print(emptyArray)
var array2 = ["Swift", 120, true] as [Any]
array2.append("23.7")
print(array2)
var myDic: [String:String] = ["a":"apple", "b":"banana", "h":"happy"]
print(myDic)
myDic["c"] = "computer"
print(myDic)
myDic["l"] = "love"
print(myDic)
myDic.removeValue(forKey: "b")
print(myDic)
var gameCharacters = [String: [Int]]()
gameCharacters["terran"]=[10, 20, 30]
gameCharacters["zerg"]=[1, 2, 3]
gameCharacters["protoss"]=[100, 200, 300]
print(gameCharacters)
for myKey in gameCharacters {
print(myKey.key)
print(myKey.value)
print(myKey)
}
if let myVal = gameCharacters["atom"] {
print(myVal)
} else {
print("nil 발생")
}
if let unWrapVal = gameCharacters["atom"] {
print(unWrapVal)
} else {
print("nil 발생")
}
import UIKit
let age = 13
if age >= 18 {
print ("You can play!")
} else {
print ("You're too young")
}
let name = "rob"
if name == "rob" {
print ("Hi " + name + "! You can play")
} else {
print ("Sorry, " + name + ", you can't play")
}
if name == "Kim" && age >= 18 {
print("you can play")
} else if name == "Lee" {
print("Sorry Lee, you need to get older")
}
if name == "Kim" || name == "Lee" {
print ("Welcome " + name)
}
let isMale = true
if isMale {
print("You're male!")
}
let username = "Amadeus"
let password = "12345"
if username == "Amadeus" && password == "12345" {
print ("You're in!")
} else if username != "Amadeus" && password != "12345" {
print ("Both username and password are wrong")
} else if username == "Amadeus" {
print ("Password is wrong")
} else {
print ("Username is wrong")
}
import UIKit
var i = 1
while i <= 10 {
print (i)
i += 1
}
i = 7
while i <= 140 {
print (i)
i += 7
}
var array = [7, 23, 98, 1, 0, 763]
i = 0
while i < array.count {
array[i] += 1
i += 1
}
print (array)
import UIKit
let array = [8, 4, 8 , 1]
for number in array {
print(number)
}
let familyMembers = ["Rob", "Kirsten", "Tommy", "Ralphie"]
for familyMember in familyMembers {
print ("Hi there " + familyMember + "!")
}
var numbers = [7, 2, 9, 4, 1]
for (index, value) in numbers.enumerated() {
numbers[index] += 1
print("index = \(index) value = \(value)")
}
var sum = 0
for i in 0 ..< 10 {
sum+=1
}
print(sum)
print (numbers)
var myArray = [Double]()
myArray = [8, 7, 19, 28]
for (index, value) in myArray.enumerated() {
myArray[index] = value / 2
}
print (myArray)
import UIKit
class Ghost {
var isAlive = true
var strength = 9
func kill() {
isAlive = false
}
func isStrong() -> Bool {
if strength > 10 {
return true
} else {
return false
}
}
}
var ghost1: Ghost = Ghost()
print (ghost1.isAlive)
ghost1.strength = 20
print (ghost1.strength)
ghost1.kill()
print (ghost1.isAlive)
print (ghost1.isStrong())
ghost1.strength = 2
print (ghost1.isStrong())
import UIKit
class Ghost {
var isAlive = true
var strength = 9
var name: String?
func setName(myName: String) -> String {
name = myName
return name!
}
func kill() {
isAlive = false
}
func isStrong() -> Bool {
if strength >= 10 {
return true
} else {
return false
}
}
}
var gh1 = Ghost()
var gh2 = Ghost()
gh1.setName(myName: "달걀귀신")
gh2.setName(myName: "팅크벨")
print(gh1.name!)
print(gh2.name!)
print("gh1의 생명상태는 : \(gh1.isAlive)")
gh1.kill()
print("gh1의 생명상태는 : \(gh1.isAlive)")
gh1.strength = 20
print("gh1은 센놈이다 : \(gh1.isStrong())")
import UIKit
var number: Int?
number = 10
print (number!)
if let myNum = number {
print(myNum)
} else {
print("nil")
}
print(number)
let userEnteredText = "Happy"
let userEnteredInteger = Int(userEnteredText)
if let catAge = userEnteredInteger {
print (catAge * 7)
} else {
print("nil occured")
}
import UIKit
func nameOfFunction() {
}
func sayHello() {
print("Hello!")
}
sayHello()
let myNmae = "홍길동"
func sayHelloToStudent(student: String) {
print("Hello, \(student)!")
}
sayHelloToStudent(student: myNmae)
func greetStudent(student: String, lateForClass: Bool) {
if lateForClass {
print("\(student).. you are late!")
} else {
print("Glad you could join us today \(student)")
}
}
func averageScore(firstScore: Double, secondScore: Double, thirdScore: Double) {
let totalScore = firstScore + secondScore + thirdScore
print(totalScore / 3)
}
greetStudent(student: "홍길동", lateForClass: false)
greetStudent(student: "임꺽정", lateForClass: true)
greetStudent(student: "이순신", lateForClass: true)
averageScore(firstScore: 70.7, secondScore: 67, thirdScore: 86.5)
func calculateTip(priceOfMeal: Double) -> Double {
return priceOfMeal * 0.15
}
func isValidLength(password: String) -> Bool {
if password.characters.count >= 8 {
return true
} else {
return false
}
}
let tip = calculateTip(priceOfMeal: 150)
print("tip = \(tip)")
print(isValidLength(password: "12345"))
func calculateMyTip(priceOfMeal: Double) -> Double {
return priceOfMeal * 0.15
}
let priceOfMeal = 43.27
let myTip = calculateMyTip(priceOfMeal: priceOfMeal)
func calculatePriceForMealWithTip(priceOfMeal: Double, tipPercentage: Double ) -> Double {
return priceOfMeal + (priceOfMeal * tipPercentage)
}
calculatePriceForMealWithTip(priceOfMeal: 43.27, tipPercentage: 0.15)
calculatePriceForMealWithTip(priceOfMeal: 100.32, tipPercentage: 0.20)
calculatePriceForMealWithTip(priceOfMeal: 65.43, tipPercentage: 0.15)
calculatePriceForMealWithTip(priceOfMeal: 22.18, tipPercentage: 0.15)
func calculateMyPriceForMealWithTip(priceOfMeal: Double, tipPercentage: Double = 0.15) -> Double {
return priceOfMeal + (priceOfMeal * tipPercentage)
}
calculateMyPriceForMealWithTip(priceOfMeal: 43.27)
calculateMyPriceForMealWithTip(priceOfMeal: 100.32, tipPercentage: 0.20)
calculateMyPriceForMealWithTip(priceOfMeal: 65.43)
calculateMyPriceForMealWithTip(priceOfMeal: 22.18)
func addExcitementToString(string: String) -> String {
return string + "!"
}
let excitedString = addExcitementToString(string: addExcitementToString(string: "yay"))
let reallyExcitedString = addExcitementToString(string: addExcitementToString(string: addExcitementToString(string: addExcitementToString(string: "wahoo"))))
import UIKit
let array = ["A", "13", "B", "5", "87", "t", "41"]
class Arithmetic {
func somOfString(inputOfStrings: [String]) -> Int {
let array = inputOfStrings
var sum = 0
for myString in array {
if Int(myString) != nil {
let intToAdd = Int(myString)!
sum += intToAdd
}
}
return sum
}
}
var calculator = Arithmetic()
calculator.somOfString(inputOfStrings: array)
코딩 실습 : 소수(prime number) 구하기
import UIKit
let number = 17
var isPrime = true
if number == 1 {
isPrime = false
}
var i = 2
while i < number {
if number % i == 0 {
isPrime = false
}
i += 1
}
print(isPrime)
import UIKit
class ViewController: UIViewController {
@IBOutlet var numberTextField: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBAction func isItPrime(_ sender: AnyObject) {
if let userEnteredString = numberTextField.text {
let userEnteredInteger = Int(userEnteredString)
if let number = userEnteredInteger {
var isPrime = true
if number == 1 {
isPrime = false
}
var i = 2
while i < number {
if number % i == 0 {
isPrime = false
}
i += 1
}
if isPrime {
resultLabel.text = "\(number) is prime!"
} else {
resultLabel.text = "\(number) is not prime"
}
} else {
resultLabel.text = "Please enter a positive whole number"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
