Skip to content

Commit

Permalink
Convenience subscript for ImageCache
Browse files Browse the repository at this point in the history
  • Loading branch information
kean committed Apr 28, 2018
1 parent b9528ef commit c4be9e9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 15 deletions.
4 changes: 4 additions & 0 deletions Sources/Deprecated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,10 @@ public final class Cache: Caching, ImageCaching {
self[ImageRequest.CacheKey(request: request)] = response.image
}

public func removeResponse(for request: ImageRequest) {
self[ImageRequest.CacheKey(request: request)] = nil
}

// MARK: Caching

public subscript(key: AnyHashable) -> Image? {
Expand Down
20 changes: 20 additions & 0 deletions Sources/ImageCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,26 @@ public protocol ImageCaching: class {

/// Stores the given `ImageResponse` in the cache using the given request.
func storeResponse(_ response: ImageResponse, for request: ImageRequest)

/// Remove the response for the given request.
func removeResponse(for request: ImageRequest)
}

/// Convenience subscript.
public extension ImageCaching {
/// Accesses the image associated with the given request.
public subscript(request: ImageRequest) -> Image? {
get {
return cachedResponse(for: request)?.image
}
set {
if let newValue = newValue {
storeResponse(ImageResponse(image: newValue, urlResponse: nil), for: request)
} else {
removeResponse(for: request)
}
}
}
}

/// Memory cache with LRU cleanup policy (least recently used are removed first).
Expand Down
15 changes: 0 additions & 15 deletions Tests/ImageCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,6 @@
import XCTest
@testable import Nuke

extension ImageCache {
subscript(request: ImageRequest) -> Image? {
get {
return cachedResponse(for: request)?.image
}
set {
if let newValue = newValue {
storeResponse(ImageResponse(image: newValue, urlResponse: nil), for: request)
} else {
removeResponse(for: request)
}
}
}
}

private func _request(index: Int) -> ImageRequest {
return ImageRequest(url: URL(string: "http://example.com/img\(index)")!)
}
Expand Down

0 comments on commit c4be9e9

Please sign in to comment.