[Swift🦩] #19 νƒ€μž… μΊμŠ€νŒ… #20 μ€‘μ²©λœ νƒ€μž…

λ˜μƒΒ·2022λ…„ 4μ›” 6일
0

iOS

λͺ©λ‘ 보기
32/42
post-thumbnail

Type Casting

  • μΈμŠ€ν„΄μŠ€μ˜ νƒ€μž…μ„ ν™•μΈν•˜κ±°λ‚˜
  • ν•΄λ‹Ή μΈμŠ€ν„΄μŠ€λ₯Ό λ‹€λ₯Έ μƒμœ„ 클래슀 or ν•˜μœ„ 클래슀둜 μ·¨κΈ‰ν•˜λŠ” 방법
  • is, as μ—°μ‚°μžλ‘œ κ΅¬ν˜„λœλ‹€.
  • ν”„λ‘œν† μ½œμ„ μ€€μˆ˜ν•˜λŠ”μ§€λ„ 확인할 수 있음.



μ˜ˆμ‹œ 클래슀 μ •μ˜

class MediaItem {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Movie: MediaItem {
    var director: String
    init(name: String, director: String) {
        self.director = director
        super.init(name: name)
    }
}

class Song: MediaItem {
    var artist: String
    init(name: String, artist: String) {
        self.artist = artist
        super.init(name: name)
    }
}


// MediaType κ³Ό κ·Έκ±Έ μƒμ†ν•œ Movie, Song 으둜 이루어져 있기 λ•Œλ¬Έμ—
// [MediaType] 으둜 좔둠됨.
let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
    Movie(name: "Citizen Kane", director: "Orson Welles"),
    Song(name: "The One And Only", artist: "Chesney Hawkes"),
    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]



1. νƒ€μž… 검사

  • is 둜 ν•΄λ‹Ή μΈμŠ€ν„΄μŠ€κ°€ ν•˜μœ„ 클래슀 νƒ€μž…μ΄λ©΄ true μ•„λ‹ˆλ©΄ false
  • 정말 κ·Έ νƒ€μž…μΈμ§€ ν™•μΈλ§Œ ν•„μš”ν•  λ•Œ μ‚¬μš©.
var movieCount = 0
var songCount = 0

for item in library {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}

print("Media library contains \(movieCount) movies and \(songCount) songs")
// Prints "Media library contains 2 movies and 3 songs"



2. λ‹€μš΄μΊμŠ€νŒ…

  • νŠΉμ • 클래슀 νƒ€μž…μ˜ μƒμˆ˜/λ³€μˆ˜λŠ” ν•˜μœ„ 클래슀의 μΈμŠ€ν„΄μŠ€λ₯Ό μ°Έμ‘°ν•  수 μžˆλ‹€κ³  ν™•μ‹ λ˜λŠ” 경우,
  • as? as! λ₯Ό μ΄μš©ν•΄μ„œ ν•˜μœ„ 클래슀 νƒ€μž…μœΌλ‘œ λ‹€μš΄μΊμŠ€νŠΈ ν•  수 μžˆλ‹€.
  • μ‹€νŒ¨κ°€ κ°€λŠ₯ν•˜κΈ° λ•Œλ¬Έμ—, Optional 값을 λ°˜ν™˜ν•˜λŠ” ? κ³Ό κ°•μ œλ‘œ λ‹€μš΄μΊμŠ€νŠΈ ν•˜λŠ” !
for item in library {
    // ν•˜μœ„ νƒ€μž…μ΄μ–΄μ•Ό movie.director, song.artist 에 μ ‘κ·Όν•  수 μžˆλ‹€.
    if let movie = item as? Movie {
        print("Movie: \(movie.name), dir. \(movie.director)")
    } else if let song = item as? Song {
        print("Song: \(song.name), by \(song.artist)")
    }
}



3. Any, AnyObject 에 λŒ€ν•œ νƒ€μž…μΊμŠ€νŒ…

  • νŠΉμ •λ˜μ§€ μ•Šμ€ νƒ€μž…μ„ μœ„ν•΄μ„œ
    • Any : ν•¨μˆ˜ νƒ€μž…μ„ ν¬ν•¨ν•œ λͺ¨λ“  νƒ€μž…μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό λ‚˜νƒ€λ‚Ό 수 있음.
    • AnyObject : λͺ¨λ“  클래슀 νƒ€μž…μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό λ‚˜νƒ€λ‚Ό 수 있음.
  • 두가지 νƒ€μž…μ„ μ œκ³΅ν•œλ‹€.
  • optional 값을 Any 둜 μ‚¬μš©ν•˜λŠ” 경우 as Any 둜 μΊμŠ€νŠΈν•˜μž.
var things: [Any] = []

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })

let optionalNumber: Int? = 3
things.append(optionalNumber as Any) // optional 값을 λ„£μœΌλ €λ©΄ Any 둜 μΊμŠ€νŠΈν•˜μž.

// switch ꡬ문을 ν†΅ν•΄μ„œ 확인할 수 μžˆλ‹€.
for thing in things {
    switch thing {
    case 0 as Int:
        print("zero as an Int")
    case 0 as Double:
        print("zero as a Double")
    case let someInt as Int:
        print("an integer value of \(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("a positive double value of \(someDouble)")
    case is Double:
        print("some other double value that I don't want to print")
    case let someString as String:
        print("a string value of \"\(someString)\"")
    case let (x, y) as (Double, Double):
        print("an (x, y) point at \(x), \(y)")
    case let movie as Movie:
        print("a movie called \(movie.name), dir. \(movie.director)")
    case let stringConverter as (String) -> String:
        print(stringConverter("Michael"))
    default:
        print("something else")
    }
}



Nested Types

  • λ³΅μž‘ν•œ νƒ€μž…μ˜ μ»¨ν…μŠ€νŠΈ λ‚΄μ—μ„œ μ‚¬μš©ν•˜κΈ° μœ„ν•΄ struct, class, enum μ•ˆμ— μ€‘μ²©ν•˜μ—¬ struct, class, enum 을 μ„ μ–Έν•  수 μžˆλ‹€.
  • ν•„μš”ν•œ 만큼 쀑첩할 수 μžˆλ‹€.

1. λ™μž‘

struct BlackjackCard > enum Suit
struct BlackjackCard > enum Rank > struct Values

struct BlackjackCard {

    // nested Suit enumeration
    enum Suit: Character {
        case spades = "β™ ", hearts = "β™‘", diamonds = "β™’", clubs = "♣"
    }

    // nested Rank enumeration
    enum Rank: Int {
        case two = 2, three, four, five, six, seven, eight, nine, ten
        case jack, queen, king, ace
        struct Values {
            let first: Int, second: Int?
        }
        var values: Values {
            switch self {
            case .ace:
                return Values(first: 1, second: 11)
            case .jack, .queen, .king:
                return Values(first: 10, second: nil)
            default:
                return Values(first: self.rawValue, second: nil)
            }
        }
    }

    // BlackjackCard properties and methods
    let rank: Rank, suit: Suit
    var description: String {
        var output = "suit is \(suit.rawValue),"
        output += " value is \(rank.values.first)"
        if let second = rank.values.second {
            output += " or \(second)"
        }
        return output
    }
}

μ§€μ •λœ init이 μ—†κΈ° λ•Œλ¬Έμ— 멀버별 초기자 μ‚¬μš© κ°€λŠ₯.

let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
print("theAceOfSpades: \(theAceOfSpades.description)")
// Prints "theAceOfSpades: suit is β™ , value is 1 or 11"

2. μ°Έμ‘°

μ€‘μ²©λœ νƒ€μž…μ˜ 이름을 chaining 처럼 . 을 λΆ™μ—¬μ„œ μ°Έμ‘°ν•  수 μžˆλ‹€.

let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "β™‘"
profile
0λ…„μ°¨ iOS κ°œλ°œμžμž…λ‹ˆλ‹€.

0개의 λŒ“κΈ€