반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

welcome to my blog

[Swift] 몇가지 정리 (enum, random, optional, class, generalType) 본문

Swift

[Swift] 몇가지 정리 (enum, random, optional, class, generalType)

_annie_ 2021. 11. 12. 20:17
728x90
  • enum
enum Device : String {
    case first = "galaxy"
    case second = "iphone"
}

let DeviceDevice = Device.second
print("DeviceDevice : \(DeviceDevice)") 		//DeviceDevice : second
print("DeviceDevice : \(DeviceDevice.rawValue)") 	//DeviceDevice : iphone

enum의 값을 알고싶다면 .rawValue 로 접근

 

enum Market {
    case fish(name:String)
    case fruit(name:String)
    case smartphone(name:String)
    
    func getName() -> String {
        switch self {
        case .fish(let name):
            return name
        case let .fruit(name):
            return name
        case let .smartphone(name):
            return name
        }
    }
}

let DevicefruitMarketName = Market.smartphone(name: "iphone")
print("DevicefruitMarketName : \(DevicefruitMarketName)")		//DevicefruitMarketName : smartphone(name: "iphone")
print("DevicefruitMarketName : \(DevicefruitMarketName.getName())")	//DevicefruitMarketName : iphone

enum값을 나중에 저장하고 값을 읽어올 때 사용 할 수 있는 방법

getName 메서드를 작성한다.

 

  • Random

랜덤한 수를 생성

아래는 0부터 100까지의 정수를 랜덤하게 생성하여 출력하는 코드이다

var randomArray: [Int] = []

for _ in 0..<25 {
    let random = Int.random(in: 0...100)  //랜덤수 in: 범위지정
    randomArray.append(random)
}

print("randomArray : \(randomArray)")	//randomArray : [29, 69, 24, 29, 78, 42, 84, 45, 18, 69, 96, 75, 48, 44, 89, 28, 40, 95, 27, 22, 23, 43, 41, 72, 97]

 

  • for문 where

for문으로 반복시킬 때 where로 조건을 줄 수 있다

0부터 100까지 (조건: 2로 나눈 나머지가 0인 경우만) 출력

for i in 0...100 where i % 2 == 0{
    print(i)
}
//0
//2
//4
//6
//8
//10
//12
//14
//16
//18
//20

 

  • optional

변수의 값이 nil 일수도 있고 아닐수도 있을 때 물음표를 이용해서 표현

var firstValue : Int? = nil

optional 값은 print로 찍어보면 Optional(값) 이런식으로 표현된다.

나는 값 만 사용하고싶은데 앞에 Optional이라고 붙어버리는것이다.

이것을 해결하기 위해서는 unWrapping을 해야한다.

func printItem(fruit: String?) {

	//fruit에 값이 있으면 item 변수에 값을 넣고 없으면 else문을 탐
	guard let item = fruit else {
		print("fruit is nil")
	    return
	}

	print(item)
}

printItem("사과")		//사과
printItem("바나나")		//바나나
printItem(nil)			//fruit is nil

 

  • struct, class

struct : 얕은복사 / class : 깊은복사

class Human {
    var age : Int = 1
    var weight : Double = 3.5
    var HumanAge : Int {
        get {
            return age - 1
        }
    }
    
    init(age: Int, weight: Double){
        self.age = age
        self.weight = weight
    }
}

let man = Human(age: 20, weight: 30)
let manCopy = man
print("man.weight : \(man.weight)")		//man.weight : 30.0
print("manCopy.weight : \(manCopy.weight)")	//manCopy.weight : 30.0

manCopy.weight = 999
print("man.weight : \(man.weight)")		//man.weight : 999.0
print("manCopy.weight : \(manCopy.weight)")	//manCopy.weight : 999.0

class의 경우

man과 man의 값을 복사하여 만들어진 manCopy의 weight의 값은 똑같이 30으로 출력된다.

그 다음 manCopy의 weight 값만 999로 바꾸었지만

man의 weight와 manCopy의 weight 값이 모두 999로 바뀌어 있는 것을 확인할 수 있다.

struct의 경우에는 위와같은 상황일 때

manCopy의 값만 999로 변경되고 man의 값은 여전히 30으로 출력된다.

struct는 값 자체만 복사하기 때문에 원본데이터에게 영향을 주지 않기 때문이다.

 

어떤 타입으로든 사용 할 수 있다.

struct GenericArray<T>{
    //제네릭타입 배열선언
    var elements : [T] = [T]()
    
    //생성자
    init(_ elements: [T]){
        self.elements = elements
    }
}

T 대신에 다른 이름으로 바꾸기가능

var numberArray = GenericArray([1,2,3])
print("numberArray: \(numberArray)")	//GenericArray<Int>(elements: [1, 2, 3])

var stringArray = GenericArray(["가나다라","abcd","123123"])
print("stringArray: \(stringArray)")	//GenericArray<String>(elements: ["가나다라", "abcd", "123123"])
print("stringArray elements : \(stringArray.elements)")	//["가나다라", "abcd", "123123"]

//stringArray.elemets[0] -> 가나다라
//stringArray.elemets[1] -> abcd
//stringArray.elemets[2] -> 123123

같은 구조체를 두고 생성할 때

String타입으로도 생성할 수 있고 Int타입으로도 생성할 수 있는 등 여러가지 타입으로 사용이 가능하다 

728x90
반응형

'Swift' 카테고리의 다른 글

[Swift] 문자열 문제연습  (0) 2022.08.03
cocoapod pod install 안될때  (0) 2021.11.30