repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Guichaguri/react-native-track-player | refs/heads/dependabot/bundler/example/ios/addressable-2.8.0 | ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/AVPlayerWrapper/AVPlayerWrapper.swift | gpl-3.0 | 1 | //
// AVPlayerWrapper.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 06/03/2018.
// Copyright © 2018 Jørgen Henrichsen. All rights reserved.
//
import Foundation
import AVFoundation
import MediaPlayer
public enum PlaybackEndedReason: String {
case playedUntilEnd
case playerStopped
case skippedToNext
case skippedToPrevious
case jumpedToIndex
}
class AVPlayerWrapper: AVPlayerWrapperProtocol {
struct Constants {
static let assetPlayableKey = "playable"
}
// MARK: - Properties
var avPlayer: AVPlayer
let playerObserver: AVPlayerObserver
let playerTimeObserver: AVPlayerTimeObserver
let playerItemNotificationObserver: AVPlayerItemNotificationObserver
let playerItemObserver: AVPlayerItemObserver
/**
True if the last call to load(from:playWhenReady) had playWhenReady=true.
*/
fileprivate var _playWhenReady: Bool = true
fileprivate var _initialTime: TimeInterval?
fileprivate var _state: AVPlayerWrapperState = AVPlayerWrapperState.idle {
didSet {
if oldValue != _state {
self.delegate?.AVWrapper(didChangeState: _state)
}
}
}
public init() {
self.avPlayer = AVPlayer()
self.playerObserver = AVPlayerObserver()
self.playerObserver.player = avPlayer
self.playerTimeObserver = AVPlayerTimeObserver(periodicObserverTimeInterval: timeEventFrequency.getTime())
self.playerTimeObserver.player = avPlayer
self.playerItemNotificationObserver = AVPlayerItemNotificationObserver()
self.playerItemObserver = AVPlayerItemObserver()
self.playerObserver.delegate = self
self.playerTimeObserver.delegate = self
self.playerItemNotificationObserver.delegate = self
self.playerItemObserver.delegate = self
// disabled since we're not making use of video playback
self.avPlayer.allowsExternalPlayback = false;
playerTimeObserver.registerForPeriodicTimeEvents()
}
// MARK: - AVPlayerWrapperProtocol
var state: AVPlayerWrapperState {
return _state
}
var reasonForWaitingToPlay: AVPlayer.WaitingReason? {
return avPlayer.reasonForWaitingToPlay
}
var currentItem: AVPlayerItem? {
return avPlayer.currentItem
}
var _pendingAsset: AVAsset? = nil
var automaticallyWaitsToMinimizeStalling: Bool {
get { return avPlayer.automaticallyWaitsToMinimizeStalling }
set { avPlayer.automaticallyWaitsToMinimizeStalling = newValue }
}
var currentTime: TimeInterval {
let seconds = avPlayer.currentTime().seconds
return seconds.isNaN ? 0 : seconds
}
var duration: TimeInterval {
if let seconds = currentItem?.asset.duration.seconds, !seconds.isNaN {
return seconds
}
else if let seconds = currentItem?.duration.seconds, !seconds.isNaN {
return seconds
}
else if let seconds = currentItem?.loadedTimeRanges.first?.timeRangeValue.duration.seconds,
!seconds.isNaN {
return seconds
}
return 0.0
}
var bufferedPosition: TimeInterval {
return currentItem?.loadedTimeRanges.last?.timeRangeValue.end.seconds ?? 0
}
weak var delegate: AVPlayerWrapperDelegate? = nil
var bufferDuration: TimeInterval = 0
var timeEventFrequency: TimeEventFrequency = .everySecond {
didSet {
playerTimeObserver.periodicObserverTimeInterval = timeEventFrequency.getTime()
}
}
var rate: Float {
get { return avPlayer.rate }
set { avPlayer.rate = newValue }
}
var volume: Float {
get { return avPlayer.volume }
set { avPlayer.volume = newValue }
}
var isMuted: Bool {
get { return avPlayer.isMuted }
set { avPlayer.isMuted = newValue }
}
func play() {
_playWhenReady = true
avPlayer.play()
}
func pause() {
_playWhenReady = false
avPlayer.pause()
}
func togglePlaying() {
switch avPlayer.timeControlStatus {
case .playing, .waitingToPlayAtSpecifiedRate:
pause()
case .paused:
play()
@unknown default:
fatalError("Unknown AVPlayer.timeControlStatus")
}
}
func stop() {
pause()
reset(soft: false)
}
func seek(to seconds: TimeInterval) {
avPlayer.seek(to: CMTimeMakeWithSeconds(seconds, preferredTimescale: 1000)) { (finished) in
if let _ = self._initialTime {
self._initialTime = nil
if self._playWhenReady {
self.play()
}
}
self.delegate?.AVWrapper(seekTo: Int(seconds), didFinish: finished)
}
}
func load(from url: URL, playWhenReady: Bool, options: [String: Any]? = nil) {
reset(soft: true)
_playWhenReady = playWhenReady
if currentItem?.status == .failed {
recreateAVPlayer()
}
self._pendingAsset = AVURLAsset(url: url, options: options)
if let pendingAsset = _pendingAsset {
self._state = .loading
pendingAsset.loadValuesAsynchronously(forKeys: [Constants.assetPlayableKey], completionHandler: { [weak self] in
guard let self = self else {
return
}
var error: NSError? = nil
let status = pendingAsset.statusOfValue(forKey: Constants.assetPlayableKey, error: &error)
DispatchQueue.main.async {
let isPendingAsset = (self._pendingAsset != nil && pendingAsset.isEqual(self._pendingAsset))
switch status {
case .loaded:
if isPendingAsset {
let currentItem = AVPlayerItem(asset: pendingAsset, automaticallyLoadedAssetKeys: [Constants.assetPlayableKey])
currentItem.preferredForwardBufferDuration = self.bufferDuration
self.avPlayer.replaceCurrentItem(with: currentItem)
// Register for events
self.playerTimeObserver.registerForBoundaryTimeEvents()
self.playerObserver.startObserving()
self.playerItemNotificationObserver.startObserving(item: currentItem)
self.playerItemObserver.startObserving(item: currentItem)
for format in pendingAsset.availableMetadataFormats {
self.delegate?.AVWrapper(didReceiveMetadata: pendingAsset.metadata(forFormat: format))
}
}
break
case .failed:
if isPendingAsset {
self.delegate?.AVWrapper(failedWithError: error)
self._pendingAsset = nil
}
break
case .cancelled:
break
default:
break
}
}
})
}
}
func load(from url: URL, playWhenReady: Bool, initialTime: TimeInterval? = nil, options: [String : Any]? = nil) {
_initialTime = initialTime
self.pause()
self.load(from: url, playWhenReady: playWhenReady, options: options)
}
// MARK: - Util
private func reset(soft: Bool) {
playerItemObserver.stopObservingCurrentItem()
playerTimeObserver.unregisterForBoundaryTimeEvents()
playerItemNotificationObserver.stopObservingCurrentItem()
self._pendingAsset?.cancelLoading()
self._pendingAsset = nil
if !soft {
avPlayer.replaceCurrentItem(with: nil)
}
}
/// Will recreate the AVPlayer instance. Used when the current one fails.
private func recreateAVPlayer() {
let player = AVPlayer()
playerObserver.player = player
playerTimeObserver.player = player
playerTimeObserver.registerForPeriodicTimeEvents()
avPlayer = player
delegate?.AVWrapperDidRecreateAVPlayer()
}
}
extension AVPlayerWrapper: AVPlayerObserverDelegate {
// MARK: - AVPlayerObserverDelegate
func player(didChangeTimeControlStatus status: AVPlayer.TimeControlStatus) {
switch status {
case .paused:
if currentItem == nil {
_state = .idle
}
else {
self._state = .paused
}
case .waitingToPlayAtSpecifiedRate:
self._state = .buffering
case .playing:
self._state = .playing
@unknown default:
break
}
}
func player(statusDidChange status: AVPlayer.Status) {
switch status {
case .readyToPlay:
self._state = .ready
if _playWhenReady && (_initialTime ?? 0) == 0 {
self.play()
}
else if let initialTime = _initialTime {
self.seek(to: initialTime)
}
break
case .failed:
self.delegate?.AVWrapper(failedWithError: avPlayer.error)
break
case .unknown:
break
@unknown default:
break
}
}
}
extension AVPlayerWrapper: AVPlayerTimeObserverDelegate {
// MARK: - AVPlayerTimeObserverDelegate
func audioDidStart() {
self._state = .playing
}
func timeEvent(time: CMTime) {
self.delegate?.AVWrapper(secondsElapsed: time.seconds)
}
}
extension AVPlayerWrapper: AVPlayerItemNotificationObserverDelegate {
// MARK: - AVPlayerItemNotificationObserverDelegate
func itemDidPlayToEndTime() {
delegate?.AVWrapperItemDidPlayToEndTime()
}
}
extension AVPlayerWrapper: AVPlayerItemObserverDelegate {
// MARK: - AVPlayerItemObserverDelegate
func item(didUpdateDuration duration: Double) {
self.delegate?.AVWrapper(didUpdateDuration: duration)
}
func item(didReceiveMetadata metadata: [AVMetadataItem]) {
self.delegate?.AVWrapper(didReceiveMetadata: metadata)
}
}
| 8d6732d4c098922e3e96e64f3c199c70 | 29.651558 | 139 | 0.57902 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift | mit | 1 | //
// LocalAccountDelegate.swift
// NetNewsWire
//
// Created by Brent Simmons on 9/16/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import os.log
import RSCore
import RSParser
import Articles
import ArticlesDatabase
import RSWeb
import Secrets
public enum LocalAccountDelegateError: String, Error {
case invalidParameter = "An invalid parameter was used."
}
final class LocalAccountDelegate: AccountDelegate {
private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "LocalAccount")
weak var account: Account?
private lazy var refresher: LocalAccountRefresher? = {
let refresher = LocalAccountRefresher()
refresher.delegate = self
return refresher
}()
let behaviors: AccountBehaviors = []
let isOPMLImportInProgress = false
let server: String? = nil
var credentials: Credentials?
var accountMetadata: AccountMetadata?
let refreshProgress = DownloadProgress(numberOfTasks: 0)
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) {
completion()
}
func refreshAll(for account: Account, completion: @escaping (Result<Void, Error>) -> Void) {
guard refreshProgress.isComplete else {
completion(.success(()))
return
}
var refresherWebFeeds = Set<WebFeed>()
let webFeeds = account.flattenedWebFeeds()
refreshProgress.addToNumberOfTasksAndRemaining(webFeeds.count)
let group = DispatchGroup()
var feedProviderError: Error? = nil
for webFeed in webFeeds {
if let components = URLComponents(string: webFeed.url), let feedProvider = FeedProviderManager.shared.best(for: components) {
group.enter()
feedProvider.refresh(webFeed) { result in
switch result {
case .success(let parsedItems):
account.update(webFeed.webFeedID, with: parsedItems) { _ in
self.refreshProgress.completeTask()
group.leave()
}
case .failure(let error):
os_log(.error, log: self.log, "Feed Provider refresh error: %@.", error.localizedDescription)
feedProviderError = error
self.refreshProgress.completeTask()
group.leave()
}
}
} else {
refresherWebFeeds.insert(webFeed)
}
}
group.enter()
refresher?.refreshFeeds(refresherWebFeeds) {
group.leave()
}
group.notify(queue: DispatchQueue.main) {
self.refreshProgress.clear()
account.metadata.lastArticleFetchEndTime = Date()
if let error = feedProviderError {
completion(.failure(error))
} else {
completion(.success(()))
}
}
}
func syncArticleStatus(for account: Account, completion: ((Result<Void, Error>) -> Void)? = nil) {
completion?(.success(()))
}
func sendArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
completion(.success(()))
}
func refreshArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
completion(.success(()))
}
func importOPML(for account:Account, opmlFile: URL, completion: @escaping (Result<Void, Error>) -> Void) {
var fileData: Data?
do {
fileData = try Data(contentsOf: opmlFile)
} catch {
completion(.failure(error))
return
}
guard let opmlData = fileData else {
completion(.success(()))
return
}
let parserData = ParserData(url: opmlFile.absoluteString, data: opmlData)
var opmlDocument: RSOPMLDocument?
do {
opmlDocument = try RSOPMLParser.parseOPML(with: parserData)
} catch {
completion(.failure(error))
return
}
guard let loadDocument = opmlDocument else {
completion(.success(()))
return
}
guard let children = loadDocument.children else {
return
}
BatchUpdate.shared.perform {
account.loadOPMLItems(children)
}
completion(.success(()))
}
func createWebFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result<WebFeed, Error>) -> Void) {
guard let url = URL(string: urlString), let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
completion(.failure(LocalAccountDelegateError.invalidParameter))
return
}
// Username should be part of the URL on new feed adds
if let feedProvider = FeedProviderManager.shared.best(for: urlComponents) {
createProviderWebFeed(for: account, urlComponents: urlComponents, editedName: name, container: container, feedProvider: feedProvider, completion: completion)
} else {
createRSSWebFeed(for: account, url: url, editedName: name, container: container, completion: completion)
}
}
func renameWebFeed(for account: Account, with feed: WebFeed, to name: String, completion: @escaping (Result<Void, Error>) -> Void) {
feed.editedName = name
completion(.success(()))
}
func removeWebFeed(for account: Account, with feed: WebFeed, from container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.removeWebFeed(feed)
completion(.success(()))
}
func moveWebFeed(for account: Account, with feed: WebFeed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) {
from.removeWebFeed(feed)
to.addWebFeed(feed)
completion(.success(()))
}
func addWebFeed(for account: Account, with feed: WebFeed, to container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.addWebFeed(feed)
completion(.success(()))
}
func restoreWebFeed(for account: Account, feed: WebFeed, container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.addWebFeed(feed)
completion(.success(()))
}
func createFolder(for account: Account, name: String, completion: @escaping (Result<Folder, Error>) -> Void) {
if let folder = account.ensureFolder(with: name) {
completion(.success(folder))
} else {
completion(.failure(FeedbinAccountDelegateError.invalidParameter))
}
}
func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result<Void, Error>) -> Void) {
folder.name = name
completion(.success(()))
}
func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
account.removeFolder(folder)
completion(.success(()))
}
func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
account.addFolder(folder)
completion(.success(()))
}
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
account.update(articles, statusKey: statusKey, flag: flag) { result in
if case .failure(let error) = result {
completion(.failure(error))
} else {
completion(.success(()))
}
}
}
func accountDidInitialize(_ account: Account) {
self.account = account
}
func accountWillBeDeleted(_ account: Account) {
}
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: (Result<Credentials?, Error>) -> Void) {
return completion(.success(nil))
}
// MARK: Suspend and Resume (for iOS)
func suspendNetwork() {
refresher?.suspend()
}
func suspendDatabase() {
// Nothing to do
}
func resume() {
refresher?.resume()
}
}
extension LocalAccountDelegate: LocalAccountRefresherDelegate {
func localAccountRefresher(_ refresher: LocalAccountRefresher, requestCompletedFor: WebFeed) {
refreshProgress.completeTask()
}
func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges, completion: @escaping () -> Void) {
completion()
}
}
private extension LocalAccountDelegate {
func createProviderWebFeed(for account: Account, urlComponents: URLComponents, editedName: String?, container: Container, feedProvider: FeedProvider, completion: @escaping (Result<WebFeed, Error>) -> Void) {
refreshProgress.addToNumberOfTasksAndRemaining(2)
feedProvider.metaData(urlComponents) { result in
self.refreshProgress.completeTask()
switch result {
case .success(let metaData):
guard let urlString = urlComponents.url?.absoluteString else {
completion(.failure(AccountError.createErrorNotFound))
return
}
let feed = account.createWebFeed(with: metaData.name, url: urlString, webFeedID: urlString, homePageURL: metaData.homePageURL)
feed.editedName = editedName
container.addWebFeed(feed)
feedProvider.refresh(feed) { result in
self.refreshProgress.completeTask()
switch result {
case .success(let parsedItems):
account.update(urlString, with: parsedItems) { _ in
completion(.success(feed))
}
case .failure(let error):
self.refreshProgress.clear()
completion(.failure(error))
}
}
case .failure:
self.refreshProgress.clear()
completion(.failure(AccountError.createErrorNotFound))
}
}
}
func createRSSWebFeed(for account: Account, url: URL, editedName: String?, container: Container, completion: @escaping (Result<WebFeed, Error>) -> Void) {
// We need to use a batch update here because we need to assign add the feed to the
// container before the name has been downloaded. This will put it in the sidebar
// with an Untitled name if we don't delay it being added to the sidebar.
BatchUpdate.shared.start()
refreshProgress.addToNumberOfTasksAndRemaining(1)
FeedFinder.find(url: url) { result in
switch result {
case .success(let feedSpecifiers):
guard let bestFeedSpecifier = FeedSpecifier.bestFeed(in: feedSpecifiers),
let url = URL(string: bestFeedSpecifier.urlString) else {
self.refreshProgress.completeTask()
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorNotFound))
return
}
if account.hasWebFeed(withURL: bestFeedSpecifier.urlString) {
self.refreshProgress.completeTask()
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorAlreadySubscribed))
return
}
InitialFeedDownloader.download(url) { parsedFeed in
self.refreshProgress.completeTask()
if let parsedFeed = parsedFeed {
let feed = account.createWebFeed(with: nil, url: url.absoluteString, webFeedID: url.absoluteString, homePageURL: nil)
feed.editedName = editedName
container.addWebFeed(feed)
account.update(feed, with: parsedFeed, {_ in
BatchUpdate.shared.end()
completion(.success(feed))
})
} else {
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorNotFound))
}
}
case .failure:
BatchUpdate.shared.end()
self.refreshProgress.completeTask()
completion(.failure(AccountError.createErrorNotFound))
}
}
}
}
| 945f971969666d81a764be92d40922cf | 29.172222 | 208 | 0.711379 | false | false | false | false |
louisdh/panelkit | refs/heads/master | PanelKit/PanelManager/PanelManager+Floating.swift | mit | 1 | //
// PanelManager+Floating.swift
// PanelKit
//
// Created by Louis D'hauwe on 07/03/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import UIKit
public extension PanelManager where Self: UIViewController {
var managerViewController: UIViewController {
return self
}
}
public extension PanelManager {
func toggleFloatStatus(for panel: PanelViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
let panelNavCon = panel.panelNavigationController
if (panel.isFloating || panel.isPinned) && !panelNavCon.isPresentedAsPopover {
close(panel)
completion?()
} else if panelNavCon.isPresentedAsPopover {
let rect = panel.view.convert(panel.view.frame, to: panelContentWrapperView)
panel.dismiss(animated: false, completion: {
self.floatPanel(panel, toRect: rect, animated: animated)
completion?()
})
} else {
let rect = CGRect(origin: .zero, size: panel.preferredContentSize)
floatPanel(panel, toRect: rect, animated: animated)
}
}
internal func floatPanel(_ panel: PanelViewController, toRect rect: CGRect, animated: Bool) {
self.panelContentWrapperView.addSubview(panel.resizeCornerHandle)
self.panelContentWrapperView.addSubview(panel.view)
panel.resizeCornerHandle.bottomAnchor.constraint(equalTo: panel.view.bottomAnchor, constant: 16).isActive = true
panel.resizeCornerHandle.trailingAnchor.constraint(equalTo: panel.view.trailingAnchor, constant: 16).isActive = true
panel.didUpdateFloatingState()
self.updateFrame(for: panel, to: rect)
self.panelContentWrapperView.layoutIfNeeded()
let x = rect.origin.x
let y = rect.origin.y + panelPopYOffset
let width = panel.view.frame.size.width
let height = panel.view.frame.size.height
var newFrame = CGRect(x: x, y: y, width: width, height: height)
newFrame.center = panel.allowedCenter(for: newFrame.center)
self.updateFrame(for: panel, to: newFrame)
if animated {
UIView.animate(withDuration: panelPopDuration, delay: 0.0, options: [.allowUserInteraction, .curveEaseOut], animations: {
self.panelContentWrapperView.layoutIfNeeded()
}, completion: nil)
} else {
self.panelContentWrapperView.layoutIfNeeded()
}
if panel.view.superview == self.panelContentWrapperView {
panel.contentDelegate?.didUpdateFloatingState()
}
}
}
public extension PanelManager {
func float(_ panel: PanelViewController, at frame: CGRect) {
guard !panel.isFloating else {
return
}
guard panel.canFloat else {
return
}
toggleFloatStatus(for: panel, animated: false)
updateFrame(for: panel, to: frame)
self.panelContentWrapperView.layoutIfNeeded()
panel.viewWillAppear(false)
panel.viewDidAppear(false)
}
}
| 24f60448660578d91a49c77e3f6c4164 | 22.115702 | 124 | 0.72113 | false | false | false | false |
huynguyencong/DataCache | refs/heads/master | Sources/DataCache.swift | mit | 1 | //
// Cache.swift
// CacheDemo
//
// Created by Nguyen Cong Huy on 7/4/16.
// Copyright © 2016 Nguyen Cong Huy. All rights reserved.
//
import UIKit
public enum ImageFormat {
case unknown, png, jpeg
}
open class DataCache {
static let cacheDirectoryPrefix = "com.nch.cache."
static let ioQueuePrefix = "com.nch.queue."
static let defaultMaxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 // a week
public static let instance = DataCache(name: "default")
let cachePath: String
let memCache = NSCache<AnyObject, AnyObject>()
let ioQueue: DispatchQueue
let fileManager: FileManager
/// Name of cache
open var name: String = ""
/// Life time of disk cache, in second. Default is a week
open var maxCachePeriodInSecond = DataCache.defaultMaxCachePeriodInSecond
/// Size is allocated for disk cache, in byte. 0 mean no limit. Default is 0
open var maxDiskCacheSize: UInt = 0
/// Specify distinc name param, it represents folder name for disk cache
public init(name: String, path: String? = nil) {
self.name = name
var cachePath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
cachePath = (cachePath as NSString).appendingPathComponent(DataCache.cacheDirectoryPrefix + name)
self.cachePath = cachePath
ioQueue = DispatchQueue(label: DataCache.ioQueuePrefix + name)
self.fileManager = FileManager()
#if !os(OSX) && !os(watchOS)
NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.willTerminateNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.didEnterBackgroundNotification, object: nil)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Store data
extension DataCache {
/// Write data for key. This is an async operation.
public func write(data: Data, forKey key: String) {
memCache.setObject(data as AnyObject, forKey: key as AnyObject)
writeDataToDisk(data: data, key: key)
}
private func writeDataToDisk(data: Data, key: String) {
ioQueue.async {
if self.fileManager.fileExists(atPath: self.cachePath) == false {
do {
try self.fileManager.createDirectory(atPath: self.cachePath, withIntermediateDirectories: true, attributes: nil)
} catch {
print("DataCache: Error while creating cache folder: \(error.localizedDescription)")
}
}
self.fileManager.createFile(atPath: self.cachePath(forKey: key), contents: data, attributes: nil)
}
}
/// Read data for key
public func readData(forKey key:String) -> Data? {
var data = memCache.object(forKey: key as AnyObject) as? Data
if data == nil {
if let dataFromDisk = readDataFromDisk(forKey: key) {
data = dataFromDisk
memCache.setObject(dataFromDisk as AnyObject, forKey: key as AnyObject)
}
}
return data
}
/// Read data from disk for key
public func readDataFromDisk(forKey key: String) -> Data? {
return self.fileManager.contents(atPath: cachePath(forKey: key))
}
// MARK: - Read & write Codable types
public func write<T: Encodable>(codable: T, forKey key: String) throws {
let data = try JSONEncoder().encode(codable)
write(data: data, forKey: key)
}
public func readCodable<T: Decodable>(forKey key: String) throws -> T? {
guard let data = readData(forKey: key) else { return nil }
return try JSONDecoder().decode(T.self, from: data)
}
// MARK: - Read & write primitive types
/// Write an object for key. This object must inherit from `NSObject` and implement `NSCoding` protocol. `String`, `Array`, `Dictionary` conform to this method.
///
/// NOTE: Can't write `UIImage` with this method. Please use `writeImage(_:forKey:)` to write an image
public func write(object: NSCoding, forKey key: String) {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
write(data: data, forKey: key)
}
/// Write a string for key
public func write(string: String, forKey key: String) {
write(object: string as NSCoding, forKey: key)
}
/// Write a dictionary for key
public func write(dictionary: Dictionary<AnyHashable, Any>, forKey key: String) {
write(object: dictionary as NSCoding, forKey: key)
}
/// Write an array for key
public func write(array: Array<Any>, forKey key: String) {
write(object: array as NSCoding, forKey: key)
}
/// Read an object for key. This object must inherit from `NSObject` and implement NSCoding protocol. `String`, `Array`, `Dictionary` conform to this method
public func readObject(forKey key: String) -> NSObject? {
let data = readData(forKey: key)
if let data = data {
return NSKeyedUnarchiver.unarchiveObject(with: data) as? NSObject
}
return nil
}
/// Read a string for key
public func readString(forKey key: String) -> String? {
return readObject(forKey: key) as? String
}
/// Read an array for key
public func readArray(forKey key: String) -> Array<Any>? {
return readObject(forKey: key) as? Array<Any>
}
/// Read a dictionary for key
public func readDictionary(forKey key: String) -> Dictionary<AnyHashable, Any>? {
return readObject(forKey: key) as? Dictionary<AnyHashable, Any>
}
// MARK: - Read & write image
/// Write image for key. Please use this method to write an image instead of `writeObject(_:forKey:)`
public func write(image: UIImage, forKey key: String, format: ImageFormat? = nil) {
var data: Data? = nil
if let format = format, format == .png {
data = image.pngData()
}
else {
data = image.jpegData(compressionQuality: 0.9)
}
if let data = data {
write(data: data, forKey: key)
}
}
/// Read image for key. Please use this method to write an image instead of `readObject(forKey:)`
public func readImage(forKey key: String) -> UIImage? {
let data = readData(forKey: key)
if let data = data {
return UIImage(data: data, scale: 1.0)
}
return nil
}
@available(*, deprecated, message: "Please use `readImage(forKey:)` instead. This will be removed in the future.")
public func readImageForKey(key: String) -> UIImage? {
return readImage(forKey: key)
}
}
// MARK: - Utils
extension DataCache {
/// Check if has data for key
public func hasData(forKey key: String) -> Bool {
return hasDataOnDisk(forKey: key) || hasDataOnMem(forKey: key)
}
/// Check if has data on disk
public func hasDataOnDisk(forKey key: String) -> Bool {
return self.fileManager.fileExists(atPath: self.cachePath(forKey: key))
}
/// Check if has data on mem
public func hasDataOnMem(forKey key: String) -> Bool {
return (memCache.object(forKey: key as AnyObject) != nil)
}
}
// MARK: - Clean
extension DataCache {
/// Clean all mem cache and disk cache. This is an async operation.
public func cleanAll() {
cleanMemCache()
cleanDiskCache()
}
/// Clean cache by key. This is an async operation.
public func clean(byKey key: String) {
memCache.removeObject(forKey: key as AnyObject)
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.cachePath(forKey: key))
} catch {
print("DataCache: Error while remove file: \(error.localizedDescription)")
}
}
}
public func cleanMemCache() {
memCache.removeAllObjects()
}
public func cleanDiskCache() {
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.cachePath)
} catch {
print("DataCache: Error when clean disk: \(error.localizedDescription)")
}
}
}
/// Clean expired disk cache. This is an async operation.
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCache(completion: nil)
}
// This method is from Kingfisher
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
open func cleanExpiredDiskCache(completion handler: (()->())? = nil) {
// Do things in cocurrent io queue
ioQueue.async {
var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItem(at: fileURL)
} catch {
print("DataCache: Error while removing files \(error.localizedDescription)")
}
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
// Not valid date information. This should not happen. Just in case.
return true
}
for fileURL in sortedFiles {
do {
try self.fileManager.removeItem(at: fileURL)
} catch {
print("DataCache: Error while removing files \(error.localizedDescription)")
}
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
diskCacheSize -= UInt(fileSize)
}
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async(execute: { () -> Void in
handler?()
})
}
}
}
// MARK: - Helpers
extension DataCache {
// This method is from Kingfisher
fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
let diskCacheURL = URL(fileURLWithPath: cachePath)
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
var cachedFiles = [URL: URLResourceValues]()
var urlsToDelete = [URL]()
var diskCacheSize: UInt = 0
for fileUrl in (try? fileManager.contentsOfDirectory(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)) ?? [] {
do {
let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys)
// If it is a Directory. Continue to next file URL.
if resourceValues.isDirectory == true {
continue
}
// If this file is expired, add it to URLsToDelete
if !onlyForCacheSize,
let expiredDate = expiredDate,
let lastAccessData = resourceValues.contentAccessDate,
(lastAccessData as NSDate).laterDate(expiredDate) == expiredDate
{
urlsToDelete.append(fileUrl)
continue
}
if let fileSize = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(fileSize)
if !onlyForCacheSize {
cachedFiles[fileUrl] = resourceValues
}
}
} catch {
print("DataCache: Error while iterating files \(error.localizedDescription)")
}
}
return (urlsToDelete, diskCacheSize, cachedFiles)
}
func cachePath(forKey key: String) -> String {
let fileName = key.md5
return (cachePath as NSString).appendingPathComponent(fileName)
}
}
| 74907b38d68ecc74137d2adde988da6f | 34.873016 | 165 | 0.580015 | false | false | false | false |
tenebreux/realm-cocoa | refs/heads/master | RealmSwift-swift1.2/Tests/SwiftTestObjects.swift | apache-2.0 | 1 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import RealmSwift
class SwiftStringObject: Object {
dynamic var stringCol = ""
}
class SwiftBoolObject: Object {
dynamic var boolCol = false
}
class SwiftIntObject: Object {
dynamic var intCol = 0
}
class SwiftLongObject: Object {
dynamic var longCol: Int64 = 0
}
class SwiftObject: Object {
dynamic var boolCol = false
dynamic var intCol = 123
dynamic var floatCol = 1.23 as Float
dynamic var doubleCol = 12.3
dynamic var stringCol = "a"
dynamic var binaryCol = "a".dataUsingEncoding(NSUTF8StringEncoding)!
dynamic var dateCol = NSDate(timeIntervalSince1970: 1)
dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject()
let arrayCol = List<SwiftBoolObject>()
class func defaultValues() -> [String: AnyObject] {
return ["boolCol": false as AnyObject,
"intCol": 123 as AnyObject,
"floatCol": 1.23 as AnyObject,
"doubleCol": 12.3 as AnyObject,
"stringCol": "a" as AnyObject,
"binaryCol": "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 1) as NSDate,
"objectCol": [false],
"arrayCol": [] as NSArray]
}
}
class SwiftOptionalObject: Object {
dynamic var optNSStringCol: NSString?
dynamic var optStringCol: String?
dynamic var optBinaryCol: NSData?
dynamic var optDateCol: NSDate?
let optIntCol = RealmOptional<Int>()
let optInt16Col = RealmOptional<Int16>()
let optInt32Col = RealmOptional<Int32>()
let optInt64Col = RealmOptional<Int64>()
let optFloatCol = RealmOptional<Float>()
let optDoubleCol = RealmOptional<Double>()
let optBoolCol = RealmOptional<Bool>()
dynamic var optObjectCol: SwiftBoolObject?
// let arrayCol = List<SwiftBoolObject?>()
}
class SwiftImplicitlyUnwrappedOptionalObject: Object {
dynamic var optNSStringCol: NSString!
dynamic var optStringCol: String!
dynamic var optBinaryCol: NSData!
dynamic var optDateCol: NSDate!
dynamic var optObjectCol: SwiftBoolObject!
// let arrayCol = List<SwiftBoolObject!>()
}
class SwiftOptionalDefaultValuesObject: Object {
dynamic var optNSStringCol: NSString? = "A"
dynamic var optStringCol: String? = "B"
dynamic var optBinaryCol: NSData? = "C".dataUsingEncoding(NSUTF8StringEncoding)
dynamic var optDateCol: NSDate? = NSDate(timeIntervalSince1970: 10)
let optIntCol = RealmOptional<Int>()
let optInt16Col = RealmOptional<Int16>()
let optInt32Col = RealmOptional<Int32>()
let optInt64Col = RealmOptional<Int64>()
let optFloatCol = RealmOptional<Float>()
let optDoubleCol = RealmOptional<Double>()
let optBoolCol = RealmOptional<Bool>()
dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true])
// let arrayCol = List<SwiftBoolObject?>()
class func defaultValues() -> [String: AnyObject] {
return [
"optNSStringCol" : "A",
"optStringCol" : "B",
"optBinaryCol" : "C".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"optDateCol" : NSDate(timeIntervalSince1970: 10),
"optIntCol" : NSNull(),
"optInt16Col" : NSNull(),
"optInt32Col" : NSNull(),
"optInt64Col" : NSNull(),
"optFloatCol" : NSNull(),
"optDoubleCol" : NSNull(),
"optBoolCol" : NSNull()
]
}
}
class SwiftOptionalIgnoredPropertiesObject: Object {
dynamic var optNSStringCol: NSString? = "A"
dynamic var optStringCol: String? = "B"
dynamic var optBinaryCol: NSData? = "C".dataUsingEncoding(NSUTF8StringEncoding)
dynamic var optDateCol: NSDate? = NSDate(timeIntervalSince1970: 10)
dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true])
override class func ignoredProperties() -> [String] {
return [
"optNSStringCol",
"optStringCol",
"optBinaryCol",
"optDateCol",
"optObjectCol"
]
}
}
class SwiftDogObject: Object {
dynamic var dogName = ""
}
class SwiftOwnerObject: Object {
dynamic var name = ""
dynamic var dog: SwiftDogObject? = SwiftDogObject()
}
class SwiftAggregateObject: Object {
dynamic var intCol = 0
dynamic var floatCol = 0 as Float
dynamic var doubleCol = 0.0
dynamic var boolCol = false
dynamic var dateCol = NSDate()
dynamic var trueCol = true
dynamic var stringListCol = List<SwiftStringObject>()
}
class SwiftAllIntSizesObject: Object {
dynamic var int8 : Int8 = 0
dynamic var int16 : Int16 = 0
dynamic var int32 : Int32 = 0
dynamic var int64 : Int64 = 0
}
class SwiftEmployeeObject: Object {
dynamic var name = ""
dynamic var age = 0
dynamic var hired = false
}
class SwiftCompanyObject: Object {
dynamic var employees = List<SwiftEmployeeObject>()
}
class SwiftArrayPropertyObject: Object {
dynamic var name = ""
let array = List<SwiftStringObject>()
let intArray = List<SwiftIntObject>()
}
class SwiftDoubleListOfSwiftObject: Object {
let array = List<SwiftListOfSwiftObject>()
}
class SwiftListOfSwiftObject: Object {
let array = List<SwiftObject>()
}
class SwiftDynamicListOfSwiftObject: Object {
dynamic let array = List<SwiftObject>()
}
class SwiftArrayPropertySubclassObject: SwiftArrayPropertyObject {
let boolArray = List<SwiftBoolObject>()
}
class SwiftUTF8Object: Object {
dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
}
class SwiftIgnoredPropertiesObject: Object {
dynamic var name = ""
dynamic var age = 0
dynamic var runtimeProperty: AnyObject?
dynamic var runtimeDefaultProperty = "property"
dynamic var readOnlyProperty: Int { return 0 }
override class func ignoredProperties() -> [String] {
return ["runtimeProperty", "runtimeDefaultProperty"]
}
}
class SwiftLinkToPrimaryStringObject: Object {
dynamic var pk = ""
dynamic var object: SwiftPrimaryStringObject?
let objects = List<SwiftPrimaryStringObject>()
override class func primaryKey() -> String? {
return "pk"
}
}
class SwiftRecursiveObject: Object {
let objects = List<SwiftRecursiveObject>()
}
class SwiftPrimaryStringObject: Object {
dynamic var stringCol = ""
dynamic var intCol = 0
override class func primaryKey() -> String? {
return "stringCol"
}
}
class SwiftIndexedPropertiesObject: Object {
dynamic var stringCol = ""
dynamic var intCol = 0
override class func indexedProperties() -> [String] {
return ["stringCol"] // Add "intCol" when integer indexing is supported
}
}
| 79e8d950d5fef2d6230a71dca564115d | 29.822314 | 84 | 0.666041 | false | false | false | false |
miktap/pepe-p06 | refs/heads/master | PePeP06/PePeP06/AWS/S3Client.swift | mit | 1 | //
// S3Client.swift
// PePeP06
//
// Created by Mikko Tapaninen on 14/01/2018.
//
import Foundation
import AWSCore
import AWSS3
protocol S3ClientDelegate {
/**
* S3 client has downloaded Taso API key.
*
* - Parameter api_key: Taso API key
*/
func apiKeyReceived(api_key: String)
}
class S3Client {
// MARK: - Properties
var delegate: S3ClientDelegate?
// MARK: - Methods
func getTasoAPIKey() {
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
if let error = error {
log.error(error.localizedDescription)
}
if let data = data, let message = String(data: data, encoding: .utf8) {
log.debug("S3 client successfully downloaded Taso API key")
self.delegate?.apiKeyReceived(api_key: message)
}
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: "pepep06",
key: "taso_api_key.txt",
expression: nil,
completionHandler: completionHandler
)
}
}
| 548e73cea33ebc0be23ac644161274ec | 24.08 | 83 | 0.582137 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/SDK/XCTest/XCTest.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import XCTest // Clang module
import CoreGraphics
/// Returns the current test case, so we can use free functions instead of methods for the overlay.
@_silgen_name("_XCTCurrentTestCaseBridge") func _XCTCurrentTestCaseBridge() -> XCTestCase
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(expected: Bool, _ condition: String, @autoclosure _ message: () -> String, _ file: StaticString, _ line: UInt) -> Void {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCaseBridge()
_XCTPreformattedFailureHandler(test, expected, file.description, line, condition, message())
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArg...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
@_silgen_name("_XCTRunThrowableBlockBridge")
func _XCTRunThrowableBlockBridge(@noescape _: @convention(block) () -> Void) -> NSDictionary
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case success
case failedWithError(error: ErrorProtocol)
case failedWithException(className: String, name: String, reason: String)
case failedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception or error,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(@noescape block: () throws -> Void) -> _XCTThrowableBlockResult {
var blockErrorOptional: ErrorProtocol?
let d = _XCTRunThrowableBlockBridge({
do {
try block()
} catch {
blockErrorOptional = error
}
})
if let blockError = blockErrorOptional {
return .failedWithError(error: blockError)
} else if d.count > 0 {
let t: String = d["type"] as! String
if t == "objc" {
return .failedWithException(
className: d["className"] as! String,
name: d["name"] as! String,
reason: d["reason"] as! String)
} else {
return .failedWithUnknownException
}
} else {
return .success
}
}
// --- Supported Assertions ---
public func XCTFail(message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(@autoclosure expression: () throws -> Any?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`nil`
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotNil(@autoclosure expression: () throws -> Any?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssert(@autoclosure expression: () throws -> Boolean, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(expression, message, file: file, line: line)
}
public func XCTAssertTrue(@autoclosure expression: () throws -> Boolean, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`true`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression().boolValue
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertFalse(@autoclosure expression: () throws -> Boolean, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.`false`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression().boolValue
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () throws -> T?, @autoclosure _ expression2: () throws -> T?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional != expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () throws -> ArraySlice<T>, @autoclosure _ expression2: () throws -> ArraySlice<T>, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () throws -> ContiguousArray<T>, @autoclosure _ expression2: () throws -> ContiguousArray<T>, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(@autoclosure expression1: () throws -> [T], @autoclosure _ expression2: () throws -> [T], @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T, U : Equatable>(@autoclosure expression1: () throws -> [T: U], @autoclosure _ expression2: () throws -> [T: U], @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () throws -> T?, @autoclosure _ expression2: () throws -> T?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional == expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1Optional)"
let expressionValueStr2 = "\(expressionValue2Optional)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () throws -> ContiguousArray<T>, @autoclosure _ expression2: () throws -> ContiguousArray<T>, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () throws -> ArraySlice<T>, @autoclosure _ expression2: () throws -> ArraySlice<T>, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(@autoclosure expression1: () throws -> [T], @autoclosure _ expression2: () throws -> [T], @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T, U : Equatable>(@autoclosure expression1: () throws -> [T: U], @autoclosure _ expression2: () throws -> [T: U], @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, accuracy: T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.equalWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqualWithAccuracy")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckNotEqualWithAccuracy_Double(value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, _ accuracy: T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.notEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqualWithAccuracy")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThan<T : Comparable>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.greaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.greaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.lessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(@autoclosure expression1: () throws -> T, @autoclosure _ expression2: () throws -> T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.lessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertThrowsError<T>(@autoclosure expression: () throws -> T, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (error: ErrorProtocol) -> Void = { _ in }) -> Void {
// evaluate expression exactly once
var caughtErrorOptional: ErrorProtocol?
let result = _XCTRunThrowableBlock {
do {
_ = try expression()
} catch {
caughtErrorOptional = error
}
}
switch result {
case .success:
if let caughtError = caughtErrorOptional {
errorHandler(error: caughtError)
} else {
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message, file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(@autoclosure expression: () -> Any?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(@autoclosure expression: () -> Any?, _ exception: Any, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(@autoclosure expression: () -> Any?, _ exception: Any, _ name: String, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrow(@autoclosure expression: () -> Any?, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrow
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(@autoclosure expression: () -> Any?, _ exception: Any, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(@autoclosure expression: () -> Any?, _ exception: Any, _ name: String, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> Void {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
| 98e05278a9333d46564860526dac23e2 | 40.353831 | 265 | 0.710894 | false | false | false | false |
vigneshuvi/SwiftLoggly | refs/heads/master | SwiftLogglyOSXTests/SwiftLogglyOSXTests.swift | mit | 1 | //
// SwiftLogglyOSXTests.swift
// SwiftLogglyOSXTests
//
// Created by Vignesh on 30/01/17.
// Copyright © 2017 vigneshuvi. All rights reserved.
//
import XCTest
@testable import SwiftLogglyOSX
class SwiftLogglyOSXTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let logsDirectory = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("vignesh", isDirectory: true)
Loggly.logger.directory = logsDirectory.path
Loggly.logger.enableEmojis = true
Loggly.logger.logFormatType = LogFormatType.Normal
Loggly.logger.logEncodingType = String.Encoding.utf8;
loggly(LogType.Info, text: "Welcome to Swift Loggly")
loggly(LogType.Verbose, text: "Fun")
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogglyReportsOutput());
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogglyReportsOutput());
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogCountBasedonType(LogType.Warnings));
let dict:NSMutableDictionary = NSMutableDictionary();
dict.setValue("Vignesh", forKey: "name") ;
dict.setValue("Senior Engineer",forKey: "Position");
loggly(LogType.Info, dictionary: dict)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| d21d5d466d736cdd40d4de7035fc974a | 32.424658 | 121 | 0.627869 | false | true | false | false |
ascode/JF-Design-Patterns | refs/heads/master | JF-IOS-Swift_Design-Patterns_and_Demos/JF-IOS-Swift_Design-Patterns_and_Demos/AppDelegate.swift | artistic-2.0 | 1 | //
// AppDelegate.swift
// JF-IOS-Swift_Design-Patterns_and_Demos
//
// Created by 金飞 on 30/12/2016.
// Copyright © 2016 jl. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "JF_IOS_Swift_Design_Patterns_and_Demos")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 84e3f56b7ecde39202c977965208fe17 | 48.83871 | 285 | 0.686516 | false | false | false | false |
coodly/SlimTimerAPI | refs/heads/master | Sources/Entry.swift | apache-2.0 | 1 | /*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SWXMLHash
public struct Entry {
public let id: Int?
public let startTime: Date
public let endTime: Date?
public let taskId: Int
public let tags: [String]?
public let comments: String?
public let durationInSeconds: Int
public let inProgress: Bool
public let task: Task?
public let updatedAt: Date?
public let createdAt: Date?
}
extension Entry {
public init(id: Int?, startTime: Date, endTime: Date?, taskId: Int, tags: [String]?, comments: String?) {
self.id = id
self.startTime = startTime
self.endTime = endTime
self.taskId = taskId
self.tags = tags
self.comments = comments
self.inProgress = endTime == nil
task = nil
updatedAt = nil
createdAt = nil
let end = endTime ?? Date()
durationInSeconds = max(Int(end.timeIntervalSince(startTime)), 60)
}
}
extension Entry: RequestBody {
}
extension Entry: RemoteModel {
init?(xml: XMLIndexer) {
//TODO jaanus: figure this out
let entry: XMLIndexer
switch xml["time-entry"] {
case .xmlError(_):
entry = xml
default:
entry = xml["time-entry"]
}
guard let idString = entry["id"].element?.text, let id = Int(idString) else {
return nil
}
guard let start = entry["start-time"].element?.date else {
return nil
}
let taskData = entry["task"]
guard let task = Task(xml: taskData) else {
return nil
}
self.id = id
self.startTime = start
self.task = task
self.taskId = task.id!
tags = (entry["tags"].element?.text ?? "").components(separatedBy: ",")
comments = entry["comments"].element?.text ?? ""
inProgress = entry["in-progress"].element?.bool ?? false
endTime = entry["end-time"].element?.date ?? Date.distantPast
durationInSeconds = entry["duration-in-seconds"].element?.int ?? -1
updatedAt = entry["updated-at"].element?.date
createdAt = entry["created-at"].element?.date
}
}
| ce82ee3cb306fe33bcc1451513b68da9 | 28.041237 | 109 | 0.604189 | false | false | false | false |
elationfoundation/Reporta-iOS | refs/heads/master | IWMF/Helper/CoreDataHelper.swift | gpl-3.0 | 1 | //
// CoreDataHelper.swift
//
//
import CoreData
import UIKit
class CoreDataHelper: NSObject{
let store: CoreDataStore!
override init(){
self.store = Structures.Constant.appDelegate.cdstore
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.store.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
lazy var backgroundContext: NSManagedObjectContext? = {
let coordinator = self.store.persistentStoreCoordinator
var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
func saveContext (context: NSManagedObjectContext) {
if context.hasChanges {
do {
try context.save()
} catch _ as NSError {
abort()
}
}
}
func saveContext () {
self.saveContext( self.backgroundContext! )
}
func contextDidSaveContext(notification: NSNotification) {
let sender = notification.object as! NSManagedObjectContext
if sender === self.managedObjectContext {
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
} else if sender === self.backgroundContext {
self.managedObjectContext.performBlock {
self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
} else {
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
self.managedObjectContext.performBlock {
self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
}
| d4af9f0402b88926ee352c954fd4f15a | 32.04 | 160 | 0.658192 | false | false | false | false |
seungprk/PenguinJump | refs/heads/master | PenguinJump/PenguinJump/Coin.swift | bsd-2-clause | 1 | //
// Coin.swift
//
// Created by Matthew Tso on 6/6/16.
// Copyright © 2016 De Anza. All rights reserved.
//
import SpriteKit
/**
A collectable coin in the stage.
- parameter value: An integer value of the coin towards the persistent coin total. The default is 1.
*/
class Coin: SKSpriteNode {
let value = 1
var shadow: SKSpriteNode!
var body: SKSpriteNode!
var particles = [SKSpriteNode]()
var collected = false
init() {
/// Array of the coin's textures. The last texture is the coin image without the shine.
var coinTextures = [SKTexture]()
for i in 1...7 {
coinTextures.append(SKTexture(image: UIImage(named: "coin\(i)")!))
}
// Designated initializer for SKSpriteNode.
super.init(texture: nil, color: SKColor.clearColor(), size: coinTextures.last!.size())
name = "coin"
let coinShine = SKAction.animateWithTextures(coinTextures, timePerFrame: 1/30)
let wait = SKAction.waitForDuration(2.5)
let coinAnimation = SKAction.sequence([coinShine, wait])
body = SKSpriteNode(texture: coinTextures.last)
body.runAction(SKAction.repeatActionForever(coinAnimation))
body.zPosition = 200
body.name = "body"
shadow = SKSpriteNode(texture: SKTexture(image: UIImage(named: "coin_shadow")!))
shadow.alpha = 0.1
shadow.position.y -= size.height // 3
shadow.zPosition = -100
shadow.physicsBody = shadowPhysicsBody(shadow.texture!, category: CoinCategory)
addChild(body)
addChild(shadow)
bob()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bob() {
let bobDepth = 6.0
let bobDuration = 1.5
let down = SKAction.moveBy(CGVector(dx: 0.0, dy: -bobDepth), duration: bobDuration)
let up = SKAction.moveBy(CGVector(dx: 0.0, dy: bobDepth), duration: bobDuration)
down.timingMode = .EaseInEaseOut
up.timingMode = .EaseInEaseOut
let bobSequence = SKAction.sequence([down, up])
let bob = SKAction.repeatActionForever(bobSequence)
removeAllActions()
body.runAction(bob)
}
/**
Creates coin particles used to increment the charge bar.
- parameter camera: The target `SKCameraNode`. The particles are added as children of the camera because the particles need to move to the charge bar, which is a child of the camera.
*/
func generateCoinParticles(camera: SKCameraNode) {
let numberOfParticles = random() % 2 + 3
for _ in 1...numberOfParticles {
let particle = SKSpriteNode(color: SKColor.yellowColor(), size: CGSize(width: size.width / 5, height: size.width / 5))
// let randomX = random() % Int(size.width) - Int(size.width / 2)
let randomX = Int( arc4random_uniform( UInt32(size.width) ) ) - Int(size.width / 2)
let randomY = Int( arc4random_uniform( UInt32(size.height) ) ) - Int(size.height / 2)
let bodyPositionInScene = convertPoint(body.position, toNode: scene!)
let bodyPositionInCam = camera.convertPoint(bodyPositionInScene, fromNode: scene!)
particle.position = CGPoint(x: bodyPositionInCam.x + CGFloat(randomX), y: bodyPositionInCam.y + CGFloat(randomY))
particle.zPosition = 200000
particles.append(particle)
}
for particle in particles {
camera.addChild(particle)
}
}
}
| 87e87e7f08089f16591c90b0bf6e2d48 | 34.216981 | 187 | 0.607822 | false | false | false | false |
AlexeyTyurenkov/NBUStats | refs/heads/develop | NBUStatProject/NBUStat/ViewControllers/CurrencyViewController.swift | mit | 1 | //
// CurrencyViewController.swift
// NBUStat
//
// Created by Oleksii Tiurenkov on 7/14/17.
// Copyright © 2017 Oleksii Tiurenkov. All rights reserved.
//
import UIKit
class CurrencyViewController: UIViewController {
var presenter: DateDependedPresenterProtocol & TablePresenterProtocol = NBUCurrencyRatesManager(date: Date())
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var tomorrowButton: UIButton!
@IBOutlet weak var yesterdayButton: UIButton!
@IBOutlet weak var yesterdayLabel: UILabel!
@IBOutlet weak var tomorrowLabel: UILabel!
@IBOutlet weak var dateTextField: UITextField!
@IBOutlet weak var dropdownMarker: UIImageView!
lazy var picker: UIDatePicker = {
return self.presenter.picker
}()
lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = ThemeManager.shared.positiveColor
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: NSLocalizedString("Готово", comment: ""), style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let todayButton = UIBarButtonItem(title: "Сьогодні", style: UIBarButtonItemStyle.plain, target: self, action: #selector(todayPicker))
let cancelButton = UIBarButtonItem(title: "Відміна", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
toolBar.setItems([cancelButton, spaceButton, todayButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
return toolBar
}()
private(set) var detailedCurrency: String = ""
override func viewDidLoad() {
super.viewDidLoad()
updateDate(label: dateLabel)
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(self.handleDynamicTypeChange(notification:)), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
dateTextField.inputView = picker
dateTextField.inputAccessoryView = toolBar
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
navigationItem.leftItemsSupplementBackButton = true
}
//MARK: - date picker handling
@objc func donePicker()
{
closePicker(with: picker.date)
}
@objc func todayPicker()
{
closePicker(with: Date())
}
private func closePicker(with date: Date? = nil)
{
dropdownMarker.transform = CGAffineTransform(rotationAngle: 0)
dateTextField.resignFirstResponder()
guard let date = date else { return }
presenter.date = date
updateDate(label: dateLabel)
}
@objc func cancelPicker()
{
closePicker()
}
@objc func handleDynamicTypeChange(notification: Notification)
{
presenter.updateView()
dateLabel.font = UIFont.preferredFont(forTextStyle: .body)
yesterdayLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
tomorrowLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func changeDateButtonPressed(_ sender: Any) {
dropdownMarker.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
dateTextField.becomeFirstResponder()
}
@IBAction func previousButtonPressed(_ sender: Any) {
presenter.movePreviousDate()
updateDate(label: dateLabel)
}
@IBAction func nextButtonPressed(_ sender: Any) {
presenter.moveNextDate()
updateDate(label: dateLabel)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? NBURatesTableViewController
{
viewController.presenter = presenter
viewController.presenter.delegate = viewController
viewController.openDetail = { [weak self](cc) in
self?.detailedCurrency = cc
if cc != ""
{
self?.performSegue(withIdentifier: "ShowCurrency", sender: nil)
}
}
}
else if let viewController = segue.destination as? CurrencyDetailContainerViewController
{
viewController.currency = detailedCurrency
}
else if let viewController = segue.destination as? DataProviderInfoViewController
{
viewController.info = presenter.dataProviderInfo
}
}
func updateDate(label: UILabel)
{
label.text = presenter.currentDate
yesterdayLabel.text = presenter.prevDate
tomorrowLabel.text = presenter.nextDate
}
}
| 910302aa47b4ad8889a2b4e1ef937c43 | 33.401316 | 189 | 0.669153 | false | false | false | false |
braintree/braintree-ios-drop-in | refs/heads/master | UnitTests/FakeApplication.swift | mit | 1 | import UIKit
@objcMembers
class FakeApplication: NSObject {
var lastOpenURL: URL? = nil
var openURLWasCalled: Bool = false
var cannedOpenURLSuccess: Bool = true
var cannedCanOpenURL: Bool = true
var canOpenURLWhitelist: [URL] = []
func openURL(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any], completionHandler completion: ((Bool) -> Void)?) {
lastOpenURL = url
openURLWasCalled = true
completion?(cannedOpenURLSuccess)
}
func canOpenURL(_ url: URL) -> Bool {
for whitelistURL in canOpenURLWhitelist {
if whitelistURL.scheme == url.scheme {
return true
}
}
return cannedCanOpenURL
}
}
| e841527c778b4e1b853908bee8272eaf | 28.32 | 137 | 0.635744 | false | false | false | false |
MrWhoami/programmer_calc_ios | refs/heads/master | ProgrammerCalc/ViewController.swift | mit | 1 | //
// ViewController.swift
// ProgrammerCalc
//
// Created by LiuJiyuan on 5/24/16.
// Copyright © 2016 Joel Liu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var numberScreen: UILabel!
@IBOutlet weak var characterScreen: UILabel!
@IBOutlet weak var button8: UIButton!
@IBOutlet weak var button9: UIButton!
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBOutlet weak var buttonD: UIButton!
@IBOutlet weak var buttonE: UIButton!
@IBOutlet weak var buttonF: UIButton!
@IBOutlet weak var buttonFF: UIButton!
var printMode = 10
var characterMode = "None"
var expression = CalculationStack()
var justTouchedOperator = false
let disabledColor = UIColor.lightGrayColor()
let enabledColor = UIColor.blackColor()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
// Change the status bar color
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
button8.setTitleColor(enabledColor, forState: UIControlState.Normal)
button9.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonA.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonB.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonC.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonD.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonE.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonF.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonFF.setTitleColor(enabledColor, forState: UIControlState.Normal)
button8.setTitleColor(disabledColor, forState: UIControlState.Disabled)
button9.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonA.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonB.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonC.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonD.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonE.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonF.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonFF.setTitleColor(disabledColor, forState: UIControlState.Disabled)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
// Number pad has been touched.
@IBAction func numberPadTouched(sender: UIButton) {
if justTouchedOperator {
// If just finish one calculation, then the screen must be cleared for new input.
if sender.currentTitle! == "00" {
// Of course, in this situation, 00 will be accepted as 0.
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
} else {
// Other situations, just replace the printing number.
if printMode == 16 {
numberScreen.text = "0x" + sender.currentTitle!
} else {
numberScreen.text = sender.currentTitle!
}
}
justTouchedOperator = false
refreshCharacterScreen()
return
}
// If the screen do dot need to refresh.
if numberScreen.text! == "0" {
// If the screen is printing out 0, we need to replace the number.
if sender.currentTitle! != "00" {
// Of course, in this situation, 00 is not accepted.
numberScreen.text = sender.currentTitle!
}
}
else if numberScreen.text! == "0x0" {
// If the screen is printing out 0x0, we need to replace the number.
if sender.currentTitle! != "00" {
// Of course, in this situation, 00 is not accepted.
numberScreen.text = "0x" + sender.currentTitle!
}
}
else {
// If the screen already has something to print out, just append the new number.
var printingStr:String
if printMode == 16 {
printingStr = numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2))
} else {
printingStr = numberScreen.text!
}
printingStr += sender.currentTitle!
if UInt64(printingStr, radix: printMode) == nil {
printingStr = String(UInt64.max, radix: printMode).uppercaseString
}
if printMode == 16 {
numberScreen.text = "0x" + printingStr
} else {
numberScreen.text = printingStr
}
}
refreshCharacterScreen()
}
// C button at left-top.
@IBAction func clearTouched(sender: UIButton) {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
justTouchedOperator = false
refreshCharacterScreen()
}
// AC button
@IBAction func allClearTouched(sender: UIButton) {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
expression.clearStack()
justTouchedOperator = false
refreshCharacterScreen()
}
// "<<", ">>", "1's", "2's", "byte flip", "word flip", "RoL", "RoR"
@IBAction func instantActions(sender: UIButton) {
var printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch sender.currentTitle! {
case "<<":
printingNumber = printingNumber << 1;
case ">>":
printingNumber = printingNumber >> 1;
case "1's":
printingNumber = ~printingNumber;
case "2's":
printingNumber = ~printingNumber &+ 1;
case "byte flip":
// Get bytes
var buffer = [UInt8]()
var highest = 0
for i in 0...7 {
buffer.append(UInt8(printingNumber >> UInt64(i * 8) & 0xff))
highest = buffer[i] == 0 ? highest : i
}
// Flip bytes
for i in 0...(highest / 2) {
let tmp = buffer[i]
buffer[i] = buffer[highest - i]
buffer[highest - i] = tmp
}
// Get the result
printingNumber = 0
for i in 0...7 {
printingNumber |= UInt64(buffer[i]) << UInt64(i * 8)
}
case "word flip":
// Get words
var buffer = [UInt16]()
var highest = 0
for i in 0...3 {
buffer.append(UInt16(printingNumber >> UInt64(i * 16) & 0xffff))
highest = buffer[i] == 0 ? highest : i
}
// Flip words
for i in 0...(highest / 2) {
let tmp = buffer[i]
buffer[i] = buffer[highest - i]
buffer[highest - i] = tmp
}
// Get the result
printingNumber = 0
for i in 0...3 {
printingNumber |= UInt64(buffer[i]) << UInt64(i * 16)
}
case "RoL":
let tmp = printingNumber & (UInt64.max - UInt64.max >> 1)
printingNumber <<= 1
if tmp != 0 {
printingNumber |= 1
}
case "RoR":
let tmp = printingNumber & 1
printingNumber >>= 1
if tmp != 0 {
printingNumber |= (UInt64.max - UInt64.max >> 1)
}
default:
print("Unknown operator in instantAction: \(sender.currentTitle!).\n")
}
if printMode == 16 {
numberScreen.text = "0x" + String(printingNumber, radix: printMode)
} else {
numberScreen.text = String(printingNumber, radix: printMode)
}
justTouchedOperator = true
refreshCharacterScreen()
}
// "+", "-", "*", "/", "=", "X<<Y", "X>>Y", "AND", "OR", "NOR", "XOR"
@IBAction func normalCalculationTouched(sender: UIButton) {
var printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
do {
try printingNumber = expression.pushOperator(printingNumber, symbol: sender.currentTitle!)
if printMode == 16 {
numberScreen.text = "0x" + String(printingNumber, radix: printMode)
} else {
numberScreen.text = String(printingNumber, radix: printMode)
}
justTouchedOperator = true
} catch {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
}
refreshCharacterScreen()
}
@IBAction func printingModeControl(sender: UISegmentedControl) {
let printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch sender.selectedSegmentIndex {
case 0:
printMode = 8
numberScreen.text = String(printingNumber, radix: 8)
changeNumberPadStatus(8)
case 1:
printMode = 10
numberScreen.text = String(printingNumber, radix: 10)
changeNumberPadStatus(10)
case 2:
printMode = 16
numberScreen.text = "0x" + String(printingNumber, radix: 16)
changeNumberPadStatus(16)
default:
print("Unknown mode in printingModeControl: \(sender.selectedSegmentIndex)\n")
}
}
@IBAction func characterModeControl(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
characterMode = "ascii"
default:
characterMode = "unicode"
}
refreshCharacterScreen()
}
// MARK: tools
// Change number pad status while the printing mode changed.
private func changeNumberPadStatus(radix: Int) {
switch radix {
case 8:
button8.enabled = false
button9.enabled = false
buttonA.enabled = false
buttonB.enabled = false
buttonC.enabled = false
buttonD.enabled = false
buttonE.enabled = false
buttonF.enabled = false
buttonFF.enabled = false
case 10:
button8.enabled = true
button9.enabled = true
buttonA.enabled = false
buttonB.enabled = false
buttonC.enabled = false
buttonD.enabled = false
buttonE.enabled = false
buttonF.enabled = false
buttonFF.enabled = false
case 16:
button8.enabled = true
button9.enabled = true
buttonA.enabled = true
buttonB.enabled = true
buttonC.enabled = true
buttonD.enabled = true
buttonE.enabled = true
buttonF.enabled = true
buttonFF.enabled = true
default:
print("Error while changing number pad statusn")
}
}
// Determine what the character screen prints.
private func refreshCharacterScreen() {
let printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch characterMode {
case "ascii":
var array = [Character]()
for i in 0...7 {
let tmp = UInt8(printingNumber >> UInt64(8 * (7 - i)) & 0xff)
if (tmp >= 0x20 && tmp < 0x80) {
array.append(Character(UnicodeScalar(tmp)))
}
}
characterScreen.text = String(array)
case "unicode":
var array = [Character]()
for i in 0...3 {
let tmp = UInt16(printingNumber >> UInt64(16 * (3 - i)) & 0xffff)
if (tmp != 0) {
array.append(Character(UnicodeScalar(tmp)))
}
}
characterScreen.text = String(array)
default:
characterScreen.text = ""
}
}
}
| eb2c7f94f339362702bfc0c3d7a21016 | 37.394118 | 177 | 0.563505 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00112-swift-constraints-constraintsystem-simplifytype.swift | apache-2.0 | 11 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
o
}
class f<p : k, p : k where p.n == p> : n {
}
class f<p, p> {
}
protocol k {
typealias n
}
o: i where k.j == f> {l func k() { }
}
(f() as n).m.k()
func k<o {
enum k {
func o
var _ = o
| 7f3f6f1d5d42f6345fad6cc90bb46209 | 24.125 | 78 | 0.636816 | false | false | false | false |
iAugux/Zoom-Contacts | refs/heads/master | Phonetic/AppDelegate+3DTouch.swift | mit | 1 | //
// AppDelegate+3DTouch.swift
// Phonetic
//
// Created by Augus on 4/2/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
extension AppDelegate {
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
// react to shortcut item selections
debugPrint("A shortcut item was pressed. It was ", shortcutItem.localizedTitle)
switch shortcutItem.type {
case Type.Excute.rawValue: execute()
case Type.Rollback.rawValue: rollback()
default: return
}
}
private enum Type: String {
case Excute
case Rollback
}
// MARK: Springboard Shortcut Items (dynamic)
func createShortcutItemsWithIcons() {
let executeIcon = UIApplicationShortcutIcon(type: .Add)
let rollbackIcon = UIApplicationShortcutIcon(templateImageName: "rollback_3d")
let executeItemTitle = NSLocalizedString("Add Phonetic Keys", comment: "")
let rollbackItemTitle = NSLocalizedString("Clean Contacts Keys", comment: "")
// create dynamic shortcut items
let executeItem = UIMutableApplicationShortcutItem(type: Type.Excute.rawValue, localizedTitle: executeItemTitle, localizedSubtitle: nil, icon: executeIcon, userInfo: nil)
let rollbackItem = UIMutableApplicationShortcutItem(type: Type.Rollback.rawValue, localizedTitle: rollbackItemTitle, localizedSubtitle: nil, icon: rollbackIcon, userInfo: nil)
// add all items to an array
let items = [executeItem, rollbackItem]
UIApplication.sharedApplication().shortcutItems = items
}
// MARK: - Actions
private func execute() {
viewController?.execute()
}
private func rollback() {
viewController?.clean()
}
private var viewController: ViewController? {
// ensure root vc is presenting.
window?.rootViewController?.presentedViewController?.dismissViewControllerWithoutAnimation()
return window?.rootViewController as? ViewController
}
} | f641efd8eab4ab5ad0309acfe37cdc8b | 29.972603 | 183 | 0.653097 | false | false | false | false |
mckaskle/FlintKit | refs/heads/master | FlintKit/UIKit/UIColor+FlintKit.swift | mit | 1 | //
// MIT License
//
// UIColor+FlintKit.swift
//
// Copyright (c) 2017 Devin McKaskle
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
fileprivate enum UIColorError: Error {
case couldNotGenerateImage
}
extension UIColor {
// MARK: - Object Lifecycle
/// Supported formats are: #abc, #abcf, #aabbcc, #aabbccff where:
/// - a: red
/// - b: blue
/// - c: green
/// - f: alpha
public convenience init?(hexadecimal: String) {
var normalized = hexadecimal
if normalized.hasPrefix("#") {
normalized = String(normalized.dropFirst())
}
var characterCount = normalized.count
if characterCount == 3 || characterCount == 4 {
// Double each character.
normalized = normalized.lazy.map { "\($0)\($0)" }.joined()
// Character count has doubled.
characterCount *= 2
}
if characterCount == 6 {
// If alpha was not included, add it.
normalized.append("ff")
characterCount += 2
}
// If the string is not 8 characters at this point, it could not be normalized.
guard characterCount == 8 else { return nil }
let scanner = Scanner(string: normalized)
var value: UInt32 = 0
guard scanner.scanHexInt32(&value) else { return nil }
let red = CGFloat((value & 0xFF000000) >> 24) / 255
let green = CGFloat((value & 0xFF0000) >> 16) / 255
let blue = CGFloat((value & 0xFF00) >> 8) / 255
let alpha = CGFloat(value & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
// MARK: - Public Methods
public func image(withSize size: CGSize) throws -> UIImage {
var alpha: CGFloat = 1
if !getRed(nil, green: nil, blue: nil, alpha: &alpha) {
alpha = 1
}
UIGraphicsBeginImageContextWithOptions(size, alpha == 1, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(cgColor)
context?.fill(CGRect(origin: .zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
throw UIColorError.couldNotGenerateImage
}
return image
}
}
| 6003d75b972015c02a9d4225b831877b | 30.735294 | 83 | 0.670683 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | refs/heads/master | src/keyboardTest/KeyboardViewController.swift | mit | 1 | //
// KeyboardView.swift
// keyboardTest
//
// Created by Sean McGee on 5/26/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import UIKit
import Foundation
import RealmSwift
import SwiftyUserDefaults
var entrySoFar : String? = nil
var nameSearch = UITextField()
class KeyboardViewController: UIViewController, UITextFieldDelegate {
var buttonsArray: Array<UIButton> = []
var buttonsBlurArray = [AnyObject]()
var keyPresses: Int = 1
var deleteInput: UIButton!
var clearSearch: UIButton!
var moreOptionsForward = UIButton()
var moreOptionsBack = UIButton()
var altKeyboard = UIButton()
var optionsControl: Bool = false
var moreKeyPresses: Int = 0
var firstRowKeyStrings = ""
var secondRowKeyStrings = ""
var lastRowKeyStrings = ""
var buttonXFirst: CGFloat!
var buttonXSecond: CGFloat!
var buttonXThird: CGFloat!
var fieldXSearch: CGFloat!
var altXKeyboard: CGFloat!
var deleteX: CGFloat!
var dismissX: CGFloat!
var clearX: CGFloat!
var paddingW: CGFloat!
var moreOptionsX: CGFloat!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if GlobalVariables.sharedManager.keyboardFirst && !GlobalVariables.sharedManager.keyboardOrientChanged {
GlobalVariables.sharedManager.keyboardFirst = false
populateKeys()
} else if GlobalVariables.sharedManager.keyboardOrientChanged {
keyboardOrient()
for view in self.view.subviews {
if view.accessibilityLabel == "keyButton" || view.accessibilityLabel == "altKeys" {
view.removeFromSuperview()
} else if view.accessibilityLabel == "keyBlur" || view.accessibilityLabel == "searchBlur" {
view.removeFromSuperview()
} else if view.accessibilityLabel == "searchField" {
view.removeFromSuperview()
}
}
createKeyboard("changed")
populateKeys()
GlobalVariables.sharedManager.keyboardFirst = false
GlobalVariables.sharedManager.keyboardOrientChanged = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
keyboardOrient()
createKeyboard("default")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func keyboardOrient() {
if Defaults[.orient] == "right" {
buttonXFirst = 260
buttonXSecond = buttonXFirst
buttonXThird = buttonXSecond
fieldXSearch = 10
altXKeyboard = 0
dismissX = self.view.frame.width - 40
deleteX = dismissX - 54
paddingW = 15
moreOptionsX = self.view.frame.width - 260
} else if Defaults[.orient] == "left" {
buttonXFirst = self.view.frame.width - 10
buttonXSecond = buttonXFirst
buttonXThird = buttonXSecond
fieldXSearch = 111
altXKeyboard = self.view.frame.width - 50
dismissX = 10
deleteX = 64
paddingW = 41
moreOptionsX = 10
}
}
private class var indexFile : String {
print("index file path")
let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.kannuu.humankontact")!
let hkIndexPath = directory.path!.stringByAppendingPathComponent("HKIndex")
return hkIndexPath
}
func refreshData() {
dispatch_async(dispatch_get_main_queue()) {
self.optionsControl = false
if let indexController = Lookup.lookupController {
GlobalVariables.sharedManager.objectKeys.removeAll(keepCapacity: false)
GlobalVariables.sharedManager.objectKeys = indexController.options!
entrySoFar = indexController.entrySoFar!
nameSearch.text = entrySoFar?.capitalizedString
contactsSearchController.searchBar.text = entrySoFar?.capitalizedString
self.optionsControl = indexController.moreOptions
if (People.people.count <= 8 && indexController.branchSelectionCount != 0 && self.keyPresses > 1) {
self.view.hidden = true
}
if (self.optionsControl == true) {
if (indexController.atTop == true) {
self.moreOptionsBack.hidden = true
}
if (self.keyPresses > 1 && indexController.optionCount == 9) {
self.moreOptionsBack.hidden = true
}
if self.moreKeyPresses == 1 {
self.moreOptionsBack.hidden = false
}
self.moreOptionsForward.hidden = false
}
else if (self.optionsControl == false && indexController.complete == true) {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
}
else if (self.optionsControl == false && self.moreKeyPresses != 2) {
if self.keyPresses > 1 && self.moreKeyPresses == 1 {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = false
} else {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
}
}
else if (self.optionsControl == false && self.moreKeyPresses == 2) {
if self.keyPresses > 1 {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
} else {
self.moreOptionsForward.hidden = true
}
}
}
}
}
func backToInitialView() {
self.view.hidden = true
if contactsSearchController.searchBar.text != nil {
contactsSearchController.searchBar.text = ""
}
contactsSearchController.active = false
if nameSearch.text != nil {
nameSearch.text = ""
}
keyPresses = 1
if (Lookup.lookupController?.atTop == false) {
Lookup.lookupController?.restart()
self.refreshData()
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
GlobalVariables.sharedManager.keyboardFirst = true
}
func createKeyboard(orient: String) {
if orient == "default" {
let BlurredKeyBG = UIImage(named: "BlurredKeyBG")
let BlurredKeyBGView = UIImageView(image: BlurredKeyBG)
BlurredKeyBGView.frame = self.view.frame
BlurredKeyBGView.contentMode = UIViewContentMode.ScaleAspectFill
BlurredKeyBGView.clipsToBounds = true
self.view.addSubview(BlurredKeyBGView)
}
nameSearch = UITextField(frame: CGRectMake(fieldXSearch, 10.0, self.view.frame.width - 122, 40.0))
nameSearch.backgroundColor = UIColor.clearColor()
nameSearch.borderStyle = UITextBorderStyle.None
nameSearch.textColor = UIColor(white: 1.0, alpha: 1.0)
nameSearch.layer.cornerRadius = 12
if Defaults[.orient] == "right" {
clearX = nameSearch.frame.maxX - 36
} else if Defaults[.orient] == "left" {
clearX = nameSearch.frame.minX
}
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = nameSearch.frame
blurView.layer.cornerRadius = 12
blurView.clipsToBounds = true
blurView.accessibilityLabel = "searchBlur"
let paddingView = UIView(frame: CGRectMake(0, 0, paddingW, 40))
nameSearch.leftView = paddingView
nameSearch.leftViewMode = UITextFieldViewMode.Always
nameSearch.enabled = false
nameSearch.font = UIFont(name: "HelveticaNeue-Regular", size: 19)
nameSearch.accessibilityLabel = "searchField"
clearSearch = UIButton(frame: CGRect(x: clearX, y: 12, width: 36, height: 36))
clearSearch.setImage(UIImage(named: "Clear"), forState: UIControlState.Disabled)
clearSearch.setImage(UIImage(named: "Clear"), forState: UIControlState.Normal)
clearSearch.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
clearSearch.enabled = false
clearSearch.addTarget(self, action: "clearNameSearch", forControlEvents: UIControlEvents.TouchUpInside)
clearSearch.accessibilityLabel = "altKeys"
self.view.addSubview(blurView)
self.view.addSubview(nameSearch)
self.view.addSubview(clearSearch)
altKeyboard.frame = CGRect(x: altXKeyboard, y: 262, width: 50, height: 50)
altKeyboard.setImage(UIImage(named: "keyAlt"), forState: UIControlState.Normal)
altKeyboard.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
altKeyboard.addTarget(self, action: "useNormalKeyboard", forControlEvents: UIControlEvents.TouchUpInside)
altKeyboard.accessibilityLabel = "altKeys"
self.view.addSubview(altKeyboard)
self.dismissKeyboard(orient)
}
func dismissKeyboard(orient: String) {
let dismissKeyboard = UIButton(frame: CGRect(x: dismissX, y: 20, width: 30, height: 30))
dismissKeyboard.setImage(UIImage(named: "KeyboardReverse"), forState: UIControlState.Normal)
dismissKeyboard.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
dismissKeyboard.addTarget(self, action: "backToInitialView", forControlEvents: UIControlEvents.TouchUpInside)
dismissKeyboard.accessibilityLabel = "altKeys"
self.view.addSubview(dismissKeyboard)
self.deleteBtn(orient)
}
func useNormalKeyboard() {
self.view.hidden = true
contactsSearchController.active = false
self.view.window?.rootViewController!.presentViewController(normalSearchController, animated: true, completion: nil)
normalSearchController.active = true
}
func deleteBtn(orient: String) {
deleteInput = UIButton(frame: CGRect(x: deleteX, y: 18, width: 26, height: 26))
if Defaults[.orient] == "right" {
deleteInput.setImage(UIImage(named: "Delete"), forState: UIControlState.Disabled)
deleteInput.setImage(UIImage(named: "Delete"), forState: UIControlState.Normal)
} else {
deleteInput.setImage(UIImage(named: "DeleteAlt"), forState: UIControlState.Disabled)
deleteInput.setImage(UIImage(named: "DeleteAlt"), forState: UIControlState.Normal)
}
deleteInput.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
deleteInput.enabled = false
deleteInput.addTarget(self, action: "deleteSearchInput:", forControlEvents: .TouchUpInside)
deleteInput.accessibilityLabel = "altKeys"
self.view.addSubview(deleteInput)
self.navKeys()
}
func populateKeys() {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
if (index < 3) {
let keyButton1 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXFirst, y: 75, width: 77, height: 52))
buttonXFirst = buttonXFirst - 87
keyButton1.layer.cornerRadius = keyButton1.frame.width / 6.0
keyButton1.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton1.backgroundColor = UIColor.clearColor()
keyButton1.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
firstRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton1.setTitle(firstRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton1.setTitleColor(UIColor(white: 0.0, alpha: 1.0 ), forState: UIControlState.Highlighted)
keyButton1.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton1.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton1.titleLabel!.numberOfLines = 2
keyButton1.titleLabel!.text = firstRowKeyStrings.capitalizedString
keyButton1.tag = index
keyButton1.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView1 = UIVisualEffectView(effect: blur)
blurView1.frame = keyButton1.frame
blurView1.layer.cornerRadius = keyButton1.frame.width / 6.0
blurView1.clipsToBounds = true
blurView1.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton1)
buttonsBlurArray.append(blurView1)
keyButton1.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton1.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView1)
self.view.addSubview(keyButton1)
}
if (index < 6 && index >= 3) {
let keyButton2 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXSecond, y: 137, width: 77, height: 52))
buttonXSecond = buttonXSecond - 87
keyButton2.layer.cornerRadius = keyButton2.frame.width / 6.0
keyButton2.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton2.backgroundColor = UIColor.clearColor()
keyButton2.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
secondRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton2.setTitle(secondRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton2.setTitleColor(UIColor(white: 0.0, alpha: 1.000 ), forState: UIControlState.Highlighted)
keyButton2.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton2.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton2.titleLabel!.numberOfLines = 2
keyButton2.titleLabel!.text = secondRowKeyStrings.capitalizedString
keyButton2.tag = index
keyButton2.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView2 = UIVisualEffectView(effect: blur)
blurView2.frame = keyButton2.frame
blurView2.layer.cornerRadius = keyButton2.frame.width / 6.0
blurView2.clipsToBounds = true
blurView2.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton2)
buttonsBlurArray.append(blurView2)
keyButton2.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton2.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView2)
self.view.addSubview(keyButton2)
}
if (index < 9 && index >= 6) {
let keyButton3 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXThird, y: 199, width: 77, height: 52))
buttonXThird = buttonXThird - 87
keyButton3.layer.cornerRadius = keyButton3.frame.width / 6.0
keyButton3.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton3.backgroundColor = UIColor.clearColor()
keyButton3.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
lastRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton3.setTitle(lastRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton3.setTitleColor(UIColor(white: 0.0, alpha: 1.000 ), forState: UIControlState.Highlighted)
keyButton3.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton3.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton3.titleLabel!.numberOfLines = 2
keyButton3.titleLabel!.text = lastRowKeyStrings.capitalizedString
keyButton3.tag = index
keyButton3.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView3 = UIVisualEffectView(effect: blur)
blurView3.frame = keyButton3.frame
blurView3.layer.cornerRadius = keyButton3.frame.width / 6.0
blurView3.clipsToBounds = true
blurView3.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton3)
buttonsBlurArray.append(blurView3)
keyButton3.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton3.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView3)
self.view.addSubview(keyButton3)
}
}
}
func navKeys() {
let backTitle = NSAttributedString(string: "Back", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 17.0)!])
let moreTitle = NSAttributedString(string: "More", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 17.0)!])
moreOptionsBack.frame = CGRect(x: moreOptionsX, y: 273, width: 50, height: 26)
moreOptionsBack.setAttributedTitle(backTitle, forState: .Normal)
moreOptionsBack.tag = 998
moreOptionsBack.hidden = true
moreOptionsBack.addTarget(self, action: "respondToMore:", forControlEvents: UIControlEvents.TouchUpInside)
moreOptionsBack.accessibilityLabel = "altKeys"
self.view.addSubview(moreOptionsBack)
moreOptionsForward.frame = CGRect(x: moreOptionsX + 196, y: 273, width: 50, height: 26)
moreOptionsForward.setAttributedTitle(moreTitle, forState: .Normal)
moreOptionsForward.tag = 999
moreOptionsForward.hidden = true
moreOptionsForward.addTarget(self, action: "respondToMore:", forControlEvents: UIControlEvents.TouchUpInside)
moreOptionsForward.accessibilityLabel = "altKeys"
self.view.addSubview(moreOptionsForward)
}
func keyPressed(sender: UIButton!) {
Lookup.lookupController?.selectOption(sender.tag)
self.refreshData()
keyPresses++
moreKeyPresses = 0
}
func clearNameSearch() {
if contactsSearchController.searchBar.text != nil {
contactsSearchController.searchBar.text = ""
}
if nameSearch.text != nil {
nameSearch.text = ""
}
keyPresses = 1
optionsControl = false
moreKeyPresses = 0
Lookup.lookupController?.restart()
self.refreshData()
clearSearch.enabled = false
deleteInput.enabled = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
func deleteSearchInput(sender: UIButton!) {
keyPresses--
if (keyPresses > 1) {
Lookup.lookupController?.back()
self.refreshData()
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("combinedReset"), userInfo: nil, repeats: false)
}
else {
Lookup.lookupController?.restart()
self.refreshData()
clearSearch.enabled = false
deleteInput.enabled = false
optionsControl = false
moreKeyPresses = 0
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
}
func respondToMore(sender: UIButton!) {
if (sender.tag == 998) {
moreKeyPresses--
Lookup.lookupController?.back()
self.refreshData()
moreOptionsForward.hidden = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("respondToBackRefresh"), userInfo: nil, repeats: false)
}
if (sender.tag == 999) {
moreKeyPresses++
Lookup.lookupController?.more()
self.refreshData()
moreOptionsBack.hidden = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("respondToForwardRefresh"), userInfo: nil, repeats: false)
}
}
func respondToBackRefresh() {
let baseKey : String = nameSearch.text!.capitalizedString
if (keyPresses == 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
}
if (keyPresses > 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
}
func respondToForwardRefresh() {
let baseKey : String = nameSearch.text!.capitalizedString
if (keyPresses == 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
if (keyPresses > 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
}
func buttonNormal(sender: UIButton!) {
sender.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
sender.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let baseKey = sender.titleLabel!.text!
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
clearSearch.enabled = true
deleteInput.enabled = true
sender.backgroundColor = UIColor.clearColor()
sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
func combinedReset() {
let base = nameSearch.text!.capitalizedString
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(base)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
func singleReset() {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
}
}
| 1caa94ee21e411bd0c9187c32487d4f9 | 48.012281 | 196 | 0.620002 | false | false | false | false |
viWiD/Persist | refs/heads/master | Pods/Evergreen/Sources/Evergreen/Formatter.swift | mit | 1 | //
// Formatter.swift
// Evergreen
//
// Created by Nils Fischer on 12.10.14.
// Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved.
//
import Foundation
public class Formatter {
public let components: [Component]
public init(components: [Component]) {
self.components = components
}
public enum Style {
case Default, Simple, Full
}
/// Creates a formatter from any of the predefined styles.
public convenience init(style: Style) {
let components: [Component]
switch style {
case .Default:
components = [ .Text("["), .Logger, .Text("|"), .LogLevel, .Text("] "), .Message ]
case .Simple:
components = [ .Message ]
case .Full:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
components = [ .Date(formatter: dateFormatter), .Text(" ["), .Logger, .Text("|"), .LogLevel, .Text("] "), .Message ]
}
self.init(components: components)
}
public enum Component {
case Text(String), Date(formatter: NSDateFormatter), Logger, LogLevel, Message, Function, File, Line//, Any(stringForEvent: (event: Event<M>) -> String)
public func stringForEvent<M>(event: Event<M>) -> String {
switch self {
case .Text(let text):
return text
case .Date(let formatter):
return formatter.stringFromDate(event.date)
case .Logger:
return event.logger.description
case .LogLevel:
return (event.logLevel?.description ?? "Unspecified").uppercaseString
case .Message:
switch event.message() {
case let error as NSError:
return error.localizedDescription
case let message:
return String(message)
}
case .Function:
return event.function
case .File:
return event.file
case .Line:
return String(event.line)
}
}
}
/// Produces a record from a given event. The record can be subsequently emitted by a handler.
public final func recordFromEvent<M>(event: Event<M>) -> Record {
return Record(date: event.date, description: self.stringFromEvent(event))
}
public func stringFromEvent<M>(event: Event<M>) -> String
{
var string = components.map({ $0.stringForEvent(event) }).joinWithSeparator("")
if let elapsedTime = event.elapsedTime {
string += " [ELAPSED TIME: \(elapsedTime)s]"
}
if let error = event.error {
let errorMessage: String
switch error {
case let error as CustomDebugStringConvertible:
errorMessage = error.debugDescription
case let error as CustomStringConvertible:
errorMessage = error.description
default:
errorMessage = String(error)
}
string += " [ERROR: \(errorMessage)]"
}
if event.once {
string += " [ONLY LOGGED ONCE]"
}
return string
}
}
| 2370b6af118e7d10ceabe485176a926a | 31.592233 | 160 | 0.545427 | false | false | false | false |
leexiaosi/swift | refs/heads/master | L06Enum.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import UIKit
enum Rank : Int{
case Ace = 1
case Two, Three, Four, Five, Six, Sevem, Eight, Night, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace :
return "ace"
case .Jack :
return "jack"
case .Queen :
return "queen"
default :
return String(self.toRaw())
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
if let convertedRank = Rank.fromRaw(3){
let threeDescription = convertedRank.simpleDescription()
}
enum ServerResponse{
case Result(String, String)
case Error(String)
}
| 9f16822cb2c4d7ee4ac8d2d2a017b52d | 18.184211 | 62 | 0.567901 | false | false | false | false |
WeHUD/app | refs/heads/master | weHub-ios/Gzone_App/Gzone_App/WBComment.swift | bsd-3-clause | 1 | //
// WBComment.swift
// Gzone_App
//
// Created by Lyes Atek on 19/06/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import Foundation
class WBComment: NSObject {
func addComment(userId : String,postId : String,text : String,accessToken : String,_ completion: @escaping (_ result: Bool) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments?access_token="+accessToken
let url: NSURL = NSURL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue("application/json", forHTTPHeaderField: "Content-type")
let params = ["userId":userId,"postId" : postId,"text" : text]
let options : JSONSerialization.WritingOptions = JSONSerialization.WritingOptions();
do{
let requestBody = try JSONSerialization.data(withJSONObject: params, options: options)
request.httpBody = requestBody
let session = URLSession.shared
_ = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
completion( false)
}
completion(true)
}).resume()
}
catch{
print("error")
completion(false)
}
}
func deleteComment(commentId : String,accessToken : String, _ completion: @escaping (_ result: Void) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "DELETE"
let session = URLSession.shared
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
})
task.resume()
}
func getCommentByUserId(userId : String,accessToken : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/user/"+userId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentByPostId(postId : String,accessToken : String ,offset : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/post/"+postId+"?access_token="+accessToken+"&offset="+offset
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentById(commentId : String,accessToken : String,_ completion: @escaping (_ result: Comment) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"&access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let comment : Comment = self.JSONToComment(json: jsonResult)!
completion(comment)
}
catch{
print("error")
}
})
task.resume()
}
func JSONToCommentArray(_ jsonEvents : NSArray) -> [Comment]{
print (jsonEvents)
var commentsTab : [Comment] = []
for object in jsonEvents{
let _id = (object as AnyObject).object(forKey: "_id") as! String
let userId = (object as AnyObject).object(forKey: "userId") as! String
let text = (object as AnyObject).object(forKey: "text") as! String
var video : String
if((object as AnyObject).object(forKey: "videos") != nil){
video = (object as AnyObject).object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = (object as AnyObject).object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
commentsTab.append(comment);
}
return commentsTab;
}
func JSONToComment(json : NSDictionary) ->Comment?{
let _id = json.object(forKey: "_id") as! String
let userId = json.object(forKey: "userId") as! String
let text = json.object(forKey: "text") as! String
var video : String
if(json.object(forKey: "videos") != nil){
video = json.object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = json.object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
return comment
}
}
| f1976166db4ad8c6cbc54ad1b452fde2 | 37.550505 | 156 | 0.555221 | false | false | false | false |
kylef/Mockingdrive | refs/heads/master | Pods/Representor/Representor/HTTP/HTTPTransition.swift | bsd-2-clause | 4 | //
// HTTPTransition.swift
// Representor
//
// Created by Kyle Fuller on 23/01/2015.
// Copyright (c) 2015 Apiary. All rights reserved.
//
import Foundation
/** An implementation of the Transition protocol for HTTP. */
public struct HTTPTransition : TransitionType {
public typealias Builder = HTTPTransitionBuilder
public let uri:String
/// The HTTP Method that should be used to make the request
public let method:String
/// The suggested contentType that should be used to make the request
public let suggestedContentTypes:[String]
public let attributes:InputProperties
public let parameters:InputProperties
public init(uri:String, attributes:InputProperties? = nil, parameters:InputProperties? = nil) {
self.uri = uri
self.attributes = attributes ?? [:]
self.parameters = parameters ?? [:]
self.method = "GET"
self.suggestedContentTypes = [String]()
}
public init(uri:String, _ block:((builder:Builder) -> ())) {
let builder = Builder()
block(builder: builder)
self.uri = uri
self.attributes = builder.attributes
self.parameters = builder.parameters
self.method = builder.method
self.suggestedContentTypes = builder.suggestedContentTypes
}
public var hashValue:Int {
return uri.hashValue
}
}
public func ==(lhs:HTTPTransition, rhs:HTTPTransition) -> Bool {
return (
lhs.uri == rhs.uri &&
lhs.attributes == rhs.attributes &&
lhs.parameters == rhs.parameters &&
lhs.method == rhs.method &&
lhs.suggestedContentTypes == rhs.suggestedContentTypes
)
}
| b78f0dc3cf1e717a62535859ec294a68 | 27.87931 | 99 | 0.660299 | false | false | false | false |
schrockblock/gtfs-stations-paris | refs/heads/master | GTFSStationsParis/Classes/PARRouteColorManager.swift | mit | 1 | //
// PARRouteColorManager.swift
// GTFSStationsParis
//
// Created by Elliot Schrock on 7/1/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SubwayStations
open class PARRouteColorManager: NSObject, RouteColorManager {
@objc open func colorForRouteId(_ routeId: String!) -> UIColor {
var color: UIColor = UIColor.darkGray
if ["1"].contains(routeId) {color = UIColor(rgba: "#ffcd01")}
if ["2"].contains(routeId) {color = UIColor(rgba: "#006cb8")}
if ["3"].contains(routeId) {color = UIColor(rgba: "#9b993b")}
if ["3bis"].contains(routeId) {color = UIColor(rgba: "#6dc5e0")}
if ["4"].contains(routeId) {color = UIColor(rgba: "#bb4b9c")}
if ["5"].contains(routeId) {color = UIColor(rgba: "#f68f4b")}
if ["6"].contains(routeId) {color = UIColor(rgba: "#77c696")}
if ["7"].contains(routeId) {color = UIColor(rgba: "#f59fb3")}
if ["7bis"].contains(routeId) {color = UIColor(rgba: "#77c696")}
if ["8"].contains(routeId) {color = UIColor(rgba: "#c5a3cd")}
if ["9"].contains(routeId) {color = UIColor(rgba: "#cec92b")}
if ["10"].contains(routeId) {color = UIColor(rgba: "#e0b03b")}
if ["11"].contains(routeId) {color = UIColor(rgba: "#906030")}
if ["12"].contains(routeId) {color = UIColor(rgba: "#008b5a")}
if ["13"].contains(routeId) {color = UIColor(rgba: "#87d3df")}
if ["14"].contains(routeId) {color = UIColor(rgba: "#652c90")}
if ["15"].contains(routeId) {color = UIColor(rgba: "#a90f32")}
if ["16"].contains(routeId) {color = UIColor(rgba: "#ec7cae")}
if ["17"].contains(routeId) {color = UIColor(rgba: "#ec7cae")}
if ["18"].contains(routeId) {color = UIColor(rgba: "#95bf32")}
return color
}
}
extension UIColor {
@objc public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.characters.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| 6616fdfa2384f798513119222b94f501 | 45.682353 | 125 | 0.519657 | false | false | false | false |
y-hryk/MVVM_Demo | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample/Services/ActivityIndicator.swift | mit | 2 | //
// ActivityIndicator.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> ()) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator : DriverConvertibleType {
public typealias E = Bool
private let _lock = NSRecursiveLock()
private let _variable = Variable(0)
private let _loading: Driver<Bool>
public init() {
_loading = _variable.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> {
return Observable.using({ () -> ActivityToken<O.E> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
private func increment() {
_lock.lock()
_variable.value = _variable.value + 1
_lock.unlock()
}
private func decrement() {
_lock.lock()
_variable.value = _variable.value - 1
_lock.unlock()
}
public func asDriver() -> Driver<E> {
return _loading
}
}
public extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> {
return activityIndicator.trackActivityOfObservable(self)
}
}
| 6b526065f9557a97448992bf5b7cf64c | 24.609756 | 110 | 0.640476 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures | refs/heads/master | Algorithms/AddTwoIntLinkedLists.playground/Contents.swift | mit | 1 | //Add two
class Node{
var value:Int
init(_ value:Int){
self.value = value
}
var next:Node?
var prev:Node?
}
func addTwoNumbers(_ h1: inout Node, h2: inout Node) -> Node{
var h1Val = h1.value
var h2Val = h2.value
var multiplier = 10
while let h1Next = h1.next{
h1Val = h1Val + (h1Next.value * multiplier)
h1 = h1Next
print(h1Val)
multiplier = multiplier * 10
}
multiplier = 10
while let h2Next = h2.next{
h2Val = h2Val + (h2Next.value * multiplier)
h2 = h2Next
print(h2Val)
multiplier = multiplier * 10
}
var finalValue = h1Val + h2Val
let temp = finalValue % 10
finalValue = finalValue/10
let returnNode = Node(temp)
var connector = returnNode
while finalValue > 0{
let val = finalValue%10
finalValue = finalValue/10
let node = Node(val)
connector.next = node
connector = node
}
return returnNode
}
var a = Node(3)
var b = Node(1)
var c = Node(5)
var d = Node(5)
var e = Node(9)
var f = Node(2)
a.next = b
b.next = c
d.next = e
e.next = f
var node = addTwoNumbers(&a, h2: &d)
node.value
node.next?.value
node.next?.next?.value
| cc00999feefc1cba324aa310d437d280 | 18.029851 | 61 | 0.564706 | false | false | false | false |
a1exb1/ABToolKit-pod | refs/heads/master | Pod/Classes/ImageLoader/ImageLoader.swift | mit | 1 | //
// ImageLoader.swift
// Pods
//
// Created by Alex Bechmann on 02/06/2015.
//
//
import UIKit
private let kImageLoaderSharedInstance = ImageLoader()
public class ImageLoader {
var cache = NSCache()
public class func sharedLoader() -> ImageLoader {
return kImageLoaderSharedInstance
}
public func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
var data: NSData? = self.cache.objectForKey(urlString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
var downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data)
self.cache.setObject(data, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
} | 90e41c0e49abdb1cf9876209f86f65b4 | 29.492063 | 214 | 0.476563 | false | false | false | false |
material-components/material-components-ios | refs/heads/develop | catalog/MDCCatalog/MDCMenuViewController.swift | apache-2.0 | 2 | // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialLibraryInfo
import MaterialComponents.MaterialIcons
import MaterialComponents.MaterialIcons_ic_color_lens
import MaterialComponents.MaterialIcons_ic_help_outline
import MaterialComponents.MaterialIcons_ic_settings
class MDCMenuViewController: UITableViewController {
private struct MDCMenuItem {
let title: String!
let icon: UIImage?
let accessibilityLabel: String?
let accessibilityHint: String?
init(
_ title: String, _ icon: UIImage?, _ accessibilityLabel: String?,
_ accessibilityHint: String?
) {
self.title = title
self.icon = icon
self.accessibilityLabel = accessibilityLabel
self.accessibilityHint = accessibilityHint
}
}
private lazy var tableData: [MDCMenuItem] = {
var data = [
MDCMenuItem(
"Settings", MDCIcons.imageFor_ic_settings()?.withRenderingMode(.alwaysTemplate),
nil, "Opens debugging menu."),
MDCMenuItem(
"Themes", MDCIcons.imageFor_ic_color_lens()?.withRenderingMode(.alwaysTemplate),
nil, "Opens color theme chooser."),
MDCMenuItem(
"v\(MDCLibraryInfo.versionString)",
MDCIcons.imageFor_ic_help_outline()?.withRenderingMode(.alwaysTemplate),
"Version \(MDCLibraryInfo.versionString)", "Closes this menu."),
]
return data
}()
let cellIdentifier = "MenuCell"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
self.tableView.separatorStyle = .none
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let iconColor = AppTheme.containerScheme.colorScheme.onSurfaceColor.withAlphaComponent(0.61)
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let cellData = tableData[indexPath.item]
cell.textLabel?.text = cellData.title
cell.textLabel?.textColor = iconColor
cell.imageView?.image = cellData.icon
cell.imageView?.tintColor = iconColor
cell.accessibilityLabel = cellData.accessibilityLabel
cell.accessibilityHint = cellData.accessibilityHint
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let navController = self.presentingViewController as? UINavigationController else {
return
}
switch indexPath.item {
case 0:
self.dismiss(
animated: true,
completion: {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let window = appDelegate.window as? MDCCatalogWindow
{
window.showDebugSettings()
}
})
case 1:
self.dismiss(
animated: true,
completion: {
navController.pushViewController(MDCThemePickerViewController(), animated: true)
})
default:
self.dismiss(animated: true, completion: nil)
}
}
}
| afb2bb1de5e94627dd7ec814b9c8c2ff | 33.596491 | 96 | 0.711207 | false | false | false | false |
AlexRamey/mbird-iOS | refs/heads/master | Example/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift | apache-2.0 | 13 | import Foundation
#if !COCOAPODS
import PromiseKit
#endif
/**
- Returns: A promise that resolves when the provided object deallocates
- Important: The promise is not guarenteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing.
*/
public func after(life object: NSObject) -> Promise<Void> {
var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper
if reaper == nil {
reaper = GrimReaper()
objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return reaper!.promise
}
private var handle: UInt8 = 0
private class GrimReaper: NSObject {
deinit {
fulfill(())
}
let (promise, fulfill, _) = Promise<Void>.pending()
}
| 71271143bf1f0b8014480925dae0542c | 29.192308 | 162 | 0.70828 | false | false | false | false |
delbert06/DYZB | refs/heads/master | DYZB/DYZB/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// DYZB
//
// Created by 胡迪 on 2016/10/24.
// Copyright © 2016年 D.Huhu. All rights reserved.
//
import UIKit
protocol PageCollectViewDelegate : class {
func pageContentView(contentView:PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//MARK: - 定义属性
var chinldVCs:[UIViewController]
weak var parentVC:UIViewController?
var currentIndex : Int = 0
var startOffsetX : CGFloat = 0
var isForbidScrollDelege : Bool = false
weak var delegate : PageCollectViewDelegate?
//MARK: - 懒加载属性
lazy var collectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame:CGRect.zero,collectionViewLayout:layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
collectionView.delegate = self
return collectionView
}()
//MARK: - 构造函数
init(frame: CGRect,childVCs:[UIViewController],parentVC:UIViewController?) {
self.chinldVCs = childVCs
self.parentVC = parentVC
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI
extension PageContentView {
func setupUI() {
for childVC in chinldVCs {
parentVC?.addChildViewController(childVC)
}
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chinldVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = chinldVCs[(indexPath as NSIndexPath).item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - 对外暴露的方法
extension PageContentView{
func setCurrentIndex(currnetIndex: Int ){
// 记录需要进制需要进行代理方法
isForbidScrollDelege = true
let offsetX = CGFloat(currnetIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x : offsetX, y : 0), animated: true)
}
}
//MARK: - 遵守collectionViewDelegate
extension PageContentView:UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelege = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView:UIScrollView){
// 0. 判断是否是点击事件
if isForbidScrollDelege{return}
// 1. 定义需要获取的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2. 判断向左或者向右滑动
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1. 计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2. 计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算targeIndex
targetIndex = sourceIndex + 1
if targetIndex >= chinldVCs.count{
targetIndex = chinldVCs.count - 1
}
// 4. 如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1. 计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2. 计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= chinldVCs.count {
sourceIndex = chinldVCs.count - 1
}
}
// 3. 把progress sourceIndex targerIndex 传递给titleView
// print("progress:\(progress)","sourceIndex:\(sourceIndex)","targetIndex:\(targetIndex)")
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| 3d759cb61e3755d6ed253c1b24e885a6 | 30.746988 | 124 | 0.633207 | false | false | false | false |
AlexRamey/mbird-iOS | refs/heads/master | iOS Client/DevotionsController/DevotionsCoordinator.swift | mit | 1 | //
// DevotionsCoordinator.swift
// iOS Client
//
// Created by Jonathan Witten on 10/30/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
class DevotionsCoordinator: NSObject, Coordinator, UNUserNotificationCenterDelegate, DevotionTableViewDelegate {
var childCoordinators: [Coordinator] = []
var devotionsStore = MBDevotionsStore()
let scheduler: DevotionScheduler = Scheduler()
var rootViewController: UIViewController {
return self.navigationController
}
private lazy var navigationController: UINavigationController = {
return UINavigationController()
}()
func start() {
let devotionsController = MBDevotionsViewController.instantiateFromStoryboard()
devotionsController.delegate = self
navigationController.pushViewController(devotionsController, animated: true)
UNUserNotificationCenter.current().delegate = self
let devotions = devotionsStore.getDevotions()
self.scheduleDevotionsIfNecessary(devotions: devotions)
}
private func scheduleDevotionsIfNecessary(devotions: [LoadedDevotion]) {
guard let min = UserDefaults.standard.value(forKey: MBConstants.DEFAULTS_DAILY_DEVOTION_TIME_KEY) as? Int else {
return // user hasn't set up daily reminders
}
self.scheduler.promptForNotifications(withDevotions: devotions, atHour: min/60, minute: min%60) { permission in
DispatchQueue.main.async {
switch permission {
case .allowed:
print("success!")
default:
print("unable to schedule notifications")
}
}
}
}
private func showDevotionDetail(devotion: LoadedDevotion) {
let detailVC = DevotionDetailViewController.instantiateFromStoryboard(devotion: devotion)
self.navigationController.pushViewController(detailVC, animated: true)
}
// MARK: - DevotionTableViewDelegate
func selectedDevotion(_ devotion: LoadedDevotion) {
self.showDevotionDetail(devotion: devotion)
}
// MARK: - UNNotificationDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
selectTodaysDevotion()
} else {
// user dismissed notification
}
// notify the system that we're done
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNNotificationPresentationOptions.alert)
}
private func selectTodaysDevotion() {
let devotions = devotionsStore.getDevotions()
if let devotion = devotions.first(where: {$0.dateAsMMdd == Date().toMMddString()}) {
self.navigationController.tabBarController?.selectedIndex = 2
self.showDevotionDetail(devotion: devotion)
}
}
}
| 4fd9c9dbf467e29440be663515a6d52d | 38.2 | 207 | 0.684874 | false | false | false | false |
andela-jejezie/FlutterwavePaymentManager | refs/heads/master | Rave/Rave/FWHelperAndConstant/CreditCardFormatter.swift | mit | 1 | //
// CreditCardFormatter.swift
// flutterwave
//
// Created by Johnson Ejezie on 23/12/2016.
// Copyright © 2016 johnsonejezie. All rights reserved.
//
import UIKit
var creditCardFormatter : CreditCardFormatter
{
return CreditCardFormatter.sharedInstance
}
internal class CreditCardFormatter : NSObject
{
static let sharedInstance : CreditCardFormatter = CreditCardFormatter()
internal func formatToCreditCardNumber(textField : UITextField, withPreviousTextContent previousTextContent : String?, andPreviousCursorPosition previousCursorSelection : UITextRange?) {
var selectedRangeStart = textField.endOfDocument
if textField.selectedTextRange?.start != nil {
selectedRangeStart = (textField.selectedTextRange?.start)!
}
if let textFieldText = textField.text
{
var targetCursorPosition : UInt = UInt(textField.offset(from:textField.beginningOfDocument, to: selectedRangeStart))
let cardNumberWithoutSpaces : String = removeNonDigitsFromString(string: textFieldText, andPreserveCursorPosition: &targetCursorPosition)
if cardNumberWithoutSpaces.characters.count > 19
{
textField.text = previousTextContent
textField.selectedTextRange = previousCursorSelection
return
}
var cardNumberWithSpaces = ""
cardNumberWithSpaces = insertSpacesIntoEvery4DigitsIntoString(string: cardNumberWithoutSpaces, andPreserveCursorPosition: &targetCursorPosition)
textField.text = cardNumberWithSpaces
if let finalCursorPosition = textField.position(from:textField.beginningOfDocument, offset: Int(targetCursorPosition))
{
textField.selectedTextRange = textField.textRange(from: finalCursorPosition, to: finalCursorPosition)
}
}
}
private func removeNonDigitsFromString(string : String, andPreserveCursorPosition cursorPosition : inout UInt) -> String {
var digitsOnlyString : String = ""
for index in stride(from: 0, to: string.characters.count, by: 1)
{
let charToAdd : Character = Array(string.characters)[index]
if isDigit(character: charToAdd)
{
digitsOnlyString.append(charToAdd)
}
else
{
if index < Int(cursorPosition)
{
cursorPosition -= 1
}
}
}
return digitsOnlyString
}
private func isDigit(character : Character) -> Bool
{
return "\(character)".containsOnlyDigits()
}
private func insertSpacesIntoEvery4DigitsIntoString(string : String, andPreserveCursorPosition cursorPosition : inout UInt) -> String {
var stringWithAddedSpaces : String = ""
for index in stride(from: 0, to: string.characters.count, by: 1)
{
if index != 0 && index % 4 == 0 && index < 16
{
stringWithAddedSpaces += " "
if index < Int(cursorPosition)
{
cursorPosition += 1
}
}
if index < 16 {
let characterToAdd : Character = Array(string.characters)[index]
stringWithAddedSpaces.append(characterToAdd)
}
}
return stringWithAddedSpaces
}
}
| 8f32cb224ccfcb630a52c95e07f758b2 | 36.698925 | 190 | 0.618939 | false | false | false | false |
konstantinpavlikhin/RowsView | refs/heads/master | Sources/AnyRowsViewDelegate.swift | mit | 1 | //
// AnyRowsViewDelegate.swift
// RowsView
//
// Created by Konstantin Pavlikhin on 30.09.16.
// Copyright © 2016 Konstantin Pavlikhin. All rights reserved.
//
import Foundation
// MARK: - Box base.
class AnyRowsViewDelegateBoxBase<A: AnyObject>: RowsViewDelegate {
// MARK: RowsViewDelegate Implementation
func cellForItemInRowsView(rowsView: RowsView<A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
abstract()
}
}
// * * *.
// MARK: - Box.
class AnyRowsViewDelegateBox<A: RowsViewDelegate>: AnyRowsViewDelegateBoxBase<A.A> {
private weak var base: A?
// MARK: Initialization
init(_ base: A) {
self.base = base
}
// MARK: RowsViewDelegate Implementation
override func cellForItemInRowsView(rowsView: RowsView<A.A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
if let b = base {
return b.cellForItemInRowsView(rowsView: rowsView, atCoordinate: coordinate)
} else {
return RowsViewCell(frame: NSZeroRect)
}
}
}
// * * *.
// MARK: - Type-erased RowsViewDelegate.
public final class AnyRowsViewDelegate<A: AnyObject> : RowsViewDelegate {
private let _box: AnyRowsViewDelegateBoxBase<A>
// MARK: Initialization
// This class can be initialized with any RowsViewDelegate.
init<S: RowsViewDelegate>(_ base: S) where S.A == A {
_box = AnyRowsViewDelegateBox(base)
}
// MARK: RowsViewDelegate Implementation
public func cellForItemInRowsView(rowsView: RowsView<A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
return _box.cellForItemInRowsView(rowsView: rowsView, atCoordinate: coordinate)
}
}
| 0a7852b50c2ace6244321a80ee63920d | 24.25 | 117 | 0.719059 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/TableviewCells/CustomizationHeaderView.swift | gpl-3.0 | 1 | //
// CustomizationHeaderView.swift
// Habitica
//
// Created by Phillip Thelen on 24.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class CustomizationHeaderView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var currencyView: HRPGCurrencyCountView!
@IBOutlet weak var purchaseButton: UIView!
@IBOutlet weak var buyAllLabel: UILabel!
var purchaseButtonTapped: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
currencyView.currency = .gem
purchaseButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonTapped)))
buyAllLabel.text = L10n.buyAll
}
func configure(customizationSet: CustomizationSetProtocol, isBackground: Bool) {
if isBackground {
if customizationSet.key?.contains("incentive") == true {
label.text = L10n.plainBackgrounds
} else if customizationSet.key?.contains("timeTravel") == true {
label.text = L10n.timeTravelBackgrounds
} else if let key = customizationSet.key?.replacingOccurrences(of: "backgrounds", with: "") {
let index = key.index(key.startIndex, offsetBy: 2)
let month = Int(key[..<index]) ?? 0
let year = Int(key[index...]) ?? 0
let dateFormatter = DateFormatter()
let monthName = month > 0 ? dateFormatter.monthSymbols[month-1] : ""
label.text = "\(monthName) \(year)"
}
} else {
label.text = customizationSet.text
}
label.textColor = ThemeService.shared.theme.primaryTextColor
currencyView.amount = Int(customizationSet.setPrice)
purchaseButton.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
purchaseButton.borderColor = ThemeService.shared.theme.tintColor
}
@objc
private func buttonTapped() {
if let action = purchaseButtonTapped {
action()
}
}
}
| 8c00afb52d8603b341b2bc4f23cce175 | 34.311475 | 114 | 0.627205 | false | false | false | false |
noremac/Futures | refs/heads/master | Futures/Deref.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2016 Cameron Pulsford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
/**
An enum representing the current state of the Promise or Future.
- Incomplete: The Deref is still running.
- Complete: The Deref has been delivered a value.
- Invalid: The Deref has been delivered an error.
*/
public enum DerefState {
/// The Deref is still running.
case incomplete
/// The Deref has been delivered a value.
case complete
/// The Deref has been delivered an error.
case invalid
}
public enum DerefValue<T> {
case success(T)
case error(NSError)
public var successValue: T? {
if case .success(let val) = self {
return val
} else {
return nil
}
}
public var error: NSError? {
if case .error(let error) = self {
return error
} else {
return nil
}
}
}
public let FutureErrorDomain = "com.smd.Futures.FuturesErrorDomain"
public enum FutureError: Int {
case canceled = -1
case timeout = -2
}
public class Deref<T> {
public typealias DerefSuccessHandler = (value: T) -> ()
public typealias DerefErrorHandler = (error: NSError) -> ()
/// Returns the delivered value, blocking indefinitely.
public var value: DerefValue<T> {
if stateLock.condition != LockState.complete.rawValue {
valueIsBeingRequested()
stateLock.lock(whenCondition: LockState.complete.rawValue)
stateLock.unlock()
}
return valueStorage!
}
/**
Returns the delivered value, blocking for up to the specified timeout. If the timeout passes without a value deing delivered, `nil` is returned.
- parameter timeout: The maximum amount of time to wait for a value to be delivered.
- returns: The delivered value or `nil` if nothing was delivered in the given timeout.
*/
public func value(withTimeout timeout: TimeInterval) -> DerefValue<T>? {
if stateLock.condition != LockState.complete.rawValue {
valueIsBeingRequested()
if self.stateLock.lock(whenCondition: LockState.complete.rawValue, before: Date(timeIntervalSinceNow: timeout)) {
self.stateLock.unlock()
}
}
return valueStorage
}
/// Returns the delivered successValue, or `nil`.
public var successValue: T? {
return value.successValue
}
/// Returns the delivered error, or `nil`.
public var error: NSError? {
return value.error
}
/// The current state of the Deref.
public var state: DerefState {
lockSync()
let s = stateStorage
unlockSync()
return s
}
/// `false` if the Deref has been invalidated; otherwise, `true`.
public var valid: Bool {
return state != .invalid
}
/* You may not publicly initialize a Deref. */
internal init() {}
/// Specify the queue on which to call the completion handler. Defaults to the main queue.
public var completionQueue: DispatchQueue {
set {
sync {
completionQueueStorage = newValue
}
}
get {
lockSync()
let cq = completionQueueStorage
unlockSync()
return cq
}
}
/**
Associates a success handler with the Deref.
- parameter handler: The success handler.
- returns: The receiver to allow for further chaining.
*/
@discardableResult
public func onSuccess(_ handler: (value: T) -> ()) -> Self {
sync {
successHandler = handler
}
return self
}
/**
Associates an error handler with the Deref.
- parameter handler: The error handler.
- returns: The receiver to allow for further chaining.
*/
@discardableResult
public func onError(_ handler: (error: NSError) -> ()) -> Self {
sync {
errorHandler = handler
}
return self
}
/// Set the desired timeout. If no error or value is delivered within the specified window, a "timeout" error will be delivered. This value may only be set once, and it must be non-nil.
public var timeout: TimeInterval? {
didSet {
precondition(timeout != nil)
sync {
precondition(timeoutTimer == nil)
if stateStorage == .incomplete {
timeoutTimer = TimerThread.sharedInstance.timer(timeInterval: timeout!, target: self, selector: #selector(Deref.deliverTimeoutError))
}
}
}
}
private var timeoutTimer: Timer?
@discardableResult
@objc internal func deliverTimeoutError() {
invalidate(NSError(domain: FutureErrorDomain, code: FutureError.timeout.rawValue, userInfo: nil))
}
// MARK: - Delivering a value
@discardableResult
internal func deliver(derefValue value: DerefValue<T>) -> Bool {
guard stateLock.tryLock(whenCondition: LockState.waiting.rawValue) else {
return false
}
sync {
if let timer = timeoutTimer {
TimerThread.sharedInstance.invalidate(timer: timer)
}
valueStorage = value
if value.successValue == nil {
stateStorage = .invalid
} else {
stateStorage = .complete
}
}
stateLock.unlock(withCondition: LockState.complete.rawValue)
if let v = value.successValue {
sync {
if let sh = successHandler {
completionQueue.async {
sh(value: v)
}
}
}
} else if let error = value.error {
sync {
if let eh = errorHandler {
completionQueue.async {
eh(error: error)
}
}
}
}
return true
}
/**
Delivers a value to the Deref.
- parameter value: The value to deliver.
- returns: true if the value was delivered successfully; otherwise, false if a value has already been delivered or invalidated.
*/
@discardableResult
public func deliver(_ value: T) -> Bool {
return deliver(derefValue: .success(value))
}
/**
Invalidates the Deref with the given error. Fails if the Promise was previously delivered, or invalidated.
- parameter error: The error to invalidate the Promise with.
- returns: true if the Promise was invalidated successfully; otherwise, false if it was previously delivered or invalidated.
*/
@discardableResult
public func invalidate(_ error: NSError) -> Bool {
return deliver(derefValue: .error(error))
}
// MARK: - Internal utils
internal func valueIsBeingRequested() {
}
// MARK: - Managing the internal lock
private func lockSync() {
syncLock.lock()
}
private func unlockSync() {
syncLock.unlock()
}
private func sync(_ work: @noescape () -> ()) {
lockSync()
work()
unlockSync()
}
// MARK: - Privat vars
private let stateLock = ConditionLock(condition: LockState.waiting.rawValue)
private var syncLock = RecursiveLock()
private var valueStorage: DerefValue<T>?
private var successHandler: DerefSuccessHandler?
private var errorHandler: DerefErrorHandler?
private var stateStorage = DerefState.incomplete
private var completionQueueStorage = DispatchQueue.main
}
| 7f9e216a1c6aad6ae2a7cc9a68b41ea7 | 27.788079 | 189 | 0.619623 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/Views/RestoreStatusView.swift | gpl-2.0 | 2 | import Foundation
import Gridicons
import WordPressUI
class RestoreStatusView: UIView, NibLoadable {
// MARK: - Properties
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var progressTitleLabel: UILabel!
@IBOutlet private weak var progressValueLabel: UILabel!
@IBOutlet private weak var progressView: UIProgressView!
@IBOutlet private weak var progressDescriptionLabel: UILabel!
@IBOutlet private weak var hintLabel: UILabel!
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
// MARK: - Styling
private func applyStyles() {
backgroundColor = .basicBackground
icon.tintColor = .success
titleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
titleLabel.textColor = .text
titleLabel.numberOfLines = 0
descriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
descriptionLabel.textColor = .textSubtle
descriptionLabel.numberOfLines = 0
progressValueLabel.font = WPStyleGuide.fontForTextStyle(.body)
progressValueLabel.textColor = .text
progressTitleLabel.font = WPStyleGuide.fontForTextStyle(.body)
progressTitleLabel.textColor = .text
if effectiveUserInterfaceLayoutDirection == .leftToRight {
// swiftlint:disable:next inverse_text_alignment
progressTitleLabel.textAlignment = .right
} else {
// swiftlint:disable:next natural_text_alignment
progressTitleLabel.textAlignment = .left
}
progressView.layer.cornerRadius = Constants.progressViewCornerRadius
progressView.clipsToBounds = true
progressDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.subheadline)
progressDescriptionLabel.textColor = .textSubtle
hintLabel.font = WPStyleGuide.fontForTextStyle(.subheadline)
hintLabel.textColor = .textSubtle
hintLabel.numberOfLines = 0
}
// MARK: - Configuration
func configure(iconImage: UIImage, title: String, description: String, hint: String) {
icon.image = iconImage
titleLabel.text = title
descriptionLabel.text = description
hintLabel.text = hint
}
func update(progress: Int, progressTitle: String? = nil, progressDescription: String? = nil) {
progressValueLabel.text = "\(progress)%"
progressView.progress = Float(progress) / 100
if let progressTitle = progressTitle {
progressTitleLabel.text = progressTitle
progressTitleLabel.isHidden = false
} else {
progressTitleLabel.isHidden = true
}
if let progressDescription = progressDescription {
progressDescriptionLabel.text = progressDescription
progressDescriptionLabel.isHidden = false
} else {
progressDescriptionLabel.isHidden = true
}
}
// MARK: - IBAction
private enum Constants {
static let progressViewCornerRadius: CGFloat = 4
}
}
| 8ac0bd388d23d2183f02356c7f9a0852 | 32.195876 | 98 | 0.681366 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/LayoutExampleSceneViewController+CollectionView.swift | mit | 1 | import Cocoa
extension LayoutExampleSceneViewController: NSCollectionViewDataSource {
func numberOfSections(in collectionView: NSCollectionView) -> Int {
return (exampleDataSource?.count) ?? (0)
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return (exampleDataSource?[section].contents?.count) ?? (0)
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
return layoutExampleItem(itemForRepresentedObjectAt: indexPath)
}
func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
switch kind {
case NSCollectionView.elementKindSectionHeader:
return headerTitleCollectionViewElement(forItemAt: indexPath)
case NSCollectionView.elementKindSectionFooter:
return footerTitleCollectionViewElement(forItemAt: indexPath)
default:
return NSView()
}
}
// TODO: - Update this once we have implemented dynamic heights.
/*func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
return headerTitleCollectionReusableView(forItemAt: indexPath)
case UICollectionView.elementKindSectionFooter:
return footerTitleCollectionReusableView(forItemAt: indexPath)
default:
return UICollectionReusableView()
}
}*/
}
extension LayoutExampleSceneViewController: NSCollectionViewDelegateFlowLayout {
// TODO: - Update this value once we have implemented dynamic heights.
/*func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
guard let cachedCellSize = dynamicCellSizeCache[safe: indexPath.section]?[safe: indexPath.item] else {
let insertedCellSize = addCellSizeToCache(forItemAt: indexPath)
return insertedCellSize
}
return cachedCellSize
}*/
}
extension LayoutExampleSceneViewController {
private func headerTitleCollectionViewElement(forItemAt indexPath: IndexPath) -> TitleCollectionViewElement {
let titleViewElementIdentifier = Constants
.CollectionViewItemIdentifiers
.titleViewElement
.rawValue
guard let titleViewElementView = layoutExampleCollectionView.makeSupplementaryView(
ofKind: NSCollectionView.elementKindSectionHeader,
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: titleViewElementIdentifier),
for: indexPath) as? TitleCollectionViewElement else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
let title = "\((exampleDataSource?[indexPath.section].title) ?? ("Section")) Header"
titleViewElementView.configure(withTitle: title)
return titleViewElementView
}
private func footerTitleCollectionViewElement(forItemAt indexPath: IndexPath) -> TitleCollectionViewElement {
let titleViewElementIdentifier = Constants
.CollectionViewItemIdentifiers
.titleViewElement
.rawValue
guard let titleViewElementView = layoutExampleCollectionView.makeSupplementaryView(
ofKind: NSCollectionView.elementKindSectionFooter,
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: titleViewElementIdentifier),
for: indexPath) as? TitleCollectionViewElement else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
let title = "\((exampleDataSource?[indexPath.section].title) ?? ("Section")) Footer"
titleViewElementView.configure(withTitle: title)
return titleViewElementView
}
private func layoutExampleItem(itemForRepresentedObjectAt indexPath: IndexPath) -> LayoutExampleCollectionViewItem {
let layoutExampleCellIdentifier = Constants
.CollectionViewItemIdentifiers
.layoutExampleItem
.rawValue
guard let layoutExampleCollectionViewItem = layoutExampleCollectionView.makeItem(
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: layoutExampleCellIdentifier),
for: indexPath) as? LayoutExampleCollectionViewItem else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
layoutExampleCollectionViewItem.configure(forExampleContent: exampleDataSource?[indexPath.section].contents?[indexPath.item])
return layoutExampleCollectionViewItem
}
// TODO: - Update this value once we have implemented dynamic heights.
/*func addCellSizeToCache(forItemAt indexPath: IndexPath) -> CGSize {
let cellSize = layoutExampleCellCalculatedSize(forItemAt: indexPath)
guard dynamicCellSizeCache[safe: indexPath.section] != nil else {
dynamicCellSizeCache.append([cellSize])
return cellSize
}
dynamicCellSizeCache[indexPath.section].insert(cellSize, at: indexPath.item)
return cellSize
}
// TODO: - Research into how the implementation differs from iOS as we need to load a dummy cell with the content to get the size.
// - Cant use makeItem as the collectionView has not been finalised at this time.
func layoutExampleCellCalculatedSize(forItemAt indexPath: IndexPath) -> CGSize {
let layoutExampleCellIdentifier = Constants
.CollectionViewItemIdentifiers
.layoutExampleItem
.rawValue
guard let layoutExampleCollectionViewItem = layoutExampleCollectionView.makeItem(
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: layoutExampleCellIdentifier),
for: indexPath) as? LayoutExampleCollectionViewItem else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
layoutExampleCollectionViewItem.configure(forExampleContent: exampleDataSource?[indexPath.section].contents?[indexPath.item])
return layoutExampleCollectionViewItem.view.fittingSize
}
func widthForCellInCurrentLayout() -> CGFloat {
var cellWidth = layoutExampleCollectionView.frame.size.width - (sectionInsets.left + sectionInsets.right)
if itemsPerRow > 1 {
cellWidth -= minimumInteritemSpacing * (itemsPerRow - 1)
}
return floor(cellWidth / itemsPerRow)
}*/
func scrollLayoutExampleCollectionViewToTopItem() {
let initalIndexPath = IndexPath(item: 0, section: 0)
if let sectionHeader = layoutExampleCollectionView.supplementaryView(
forElementKind: NSCollectionView.elementKindSectionHeader,
at: initalIndexPath) {
layoutExampleCollectionView.scrollToVisible(
NSRect(x: sectionHeader.bounds.origin.x,
y: sectionHeader.bounds.origin.y,
width: sectionHeader.bounds.width,
height: sectionHeader.bounds.height))
} else if layoutExampleCollectionView.item(at: initalIndexPath) != nil {
layoutExampleCollectionView.scrollToItems(
at: [initalIndexPath],
scrollPosition: NSCollectionView.ScrollPosition.top)
}
}
}
| da8db99402345bb868fabfa67eb8f331 | 48.875 | 179 | 0.711384 | false | false | false | false |
mrdepth/EVEOnlineAPI | refs/heads/master | EVEAPI/EVEAPI/EVEPlanetaryPins.swift | mit | 1 | //
// EVEPlanetaryPins.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEPlanetaryPinsItem: EVEObject {
public var pinID: Int64 = 0
public var typeID: Int = 0
public var typeName: String = ""
public var schematicID: Int = 0
public var lastLaunchTime: Date = Date.distantPast
public var cycleTime: Int = 0
public var quantityPerCycle: Int = 0
public var installTime: Date = Date.distantPast
public var expiryTime: Date = Date.distantPast
public var contentTypeID: Int = 0
public var contentTypeName: String = ""
public var contentQuantity: Int = 0
public var longitude: Double = 0
public var latitude: Double = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"pinID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"typeName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"schematicID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"lastLaunchTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"cycleTime":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"quantityPerCycle":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"installTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"expiryTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"contentTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"contentTypeName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"contentQuantity":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"longitude":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"latitude":EVESchemeElementType.Double(elementName:nil, transformer:nil),
]
}
}
public class EVEPlanetaryPins: EVEResult {
public var pins: [EVEPlanetaryPinsItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"pins":EVESchemeElementType.Rowset(elementName: nil, type: EVEPlanetaryPinsItem.self, transformer: nil),
]
}
}
| 9df08221ee91fee0bf062654ccb5cd78 | 33.821918 | 107 | 0.763965 | false | false | false | false |
Dwarven/ShadowsocksX-NG | refs/heads/develop | MoyaRefreshToken/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift | apache-2.0 | 4 | //
// AsMaybe.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
fileprivate final class AsMaybeSink<O: ObserverType> : Sink<O>, ObserverType {
typealias ElementType = O.E
typealias E = ElementType
private var _element: Event<E>?
func on(_ event: Event<E>) {
switch event {
case .next:
if self._element != nil {
self.forwardOn(.error(RxError.moreThanOneElement))
self.dispose()
}
self._element = event
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
if let element = self._element {
self.forwardOn(element)
}
self.forwardOn(.completed)
self.dispose()
}
}
}
final class AsMaybe<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AsMaybeSink(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| 88f12286a5c260e55f4c0f5f49287db5 | 27.22449 | 145 | 0.588576 | false | false | false | false |
InkAnimator/SKInkAnimator | refs/heads/master | SKInkAnimator/Classes/ActionFactory.swift | mit | 1 | //
// AnimationFactory.swift
// Pods
//
// Created by Rafael Moura on 16/03/17.
//
//
import Foundation
import AEXML
import SpriteKit
class ActionFactory: NSObject {
static func action(for keyframe: Keyframe, previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction {
var group = [SKAction]()
if let moveAction = moveAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(moveAction)
}
if let rotateAction = rotateAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(rotateAction)
}
if let resizeAction = resizeAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(resizeAction)
}
if let scaleAction = scaleAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(scaleAction)
}
return group.count > 0 ? SKAction.group(group) : SKAction.wait(forDuration: duration)
}
static private func rotateAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.rotation == previousKeyframe.rotation {
return nil
}
let action: SKAction
action = SKAction.rotate(toAngle: keyframe.rotation, duration: duration, shortestUnitArc: false)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func resizeAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.size == previousKeyframe.size {
return nil
}
let action: SKAction
action = SKAction.resize(toWidth: keyframe.size.width, height: keyframe.size.height, duration: duration)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func scaleAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.scale == previousKeyframe.scale {
return nil
}
let action: SKAction
action = SKAction.scaleX(to: keyframe.scale.x, y: keyframe.scale.y, duration: duration)
return action
}
static private func moveAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.position == previousKeyframe.position {
return nil
}
let action: SKAction
action = SKAction.move(to: keyframe.position, duration: duration)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func actionTimingMode(for timingMode: Keyframe.TimingMode) -> SKActionTimingMode {
switch timingMode {
case .linear:
return .linear
case .easeIn:
return .easeIn
case .easeOut:
return .easeOut
case .easeInEaseOut:
return .easeInEaseOut
}
}
}
| bf629e6cc05ef83b367f41194b01c990 | 33.626263 | 133 | 0.635648 | false | false | false | false |
ktmswzw/FeelClient | refs/heads/master | FeelingClient/common/utils/MapHelper.swift | mit | 1 | //
// MapHelper.swift
// FeelingClient
//
// Created by Vincent on 16/3/25.
// Copyright © 2016年 xecoder. All rights reserved.
//
import Foundation
import MapKit
let a = 6378245.0
let ee = 0.00669342162296594323
// World Geodetic System ==> Mars Geodetic System
func outOfChina(coordinate: CLLocationCoordinate2D) -> Bool {
if coordinate.longitude < 72.004 || coordinate.longitude > 137.8347 {
return true
}
if coordinate.latitude < 0.8293 || coordinate.latitude > 55.8271 {
return true
}
return false
}
func transformLat(x: Double, y: Double) -> Double {
var ret = -100.0 + 2.0 * x + 3.0 * y
ret += 0.2 * y * y + 0.1 * x * y
ret += 0.2 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0
ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0
return ret;
}
func transformLon(x: Double, y: Double) -> Double {
var ret = 300.0 + x + 2.0 * y
ret += 0.1 * x * x + 0.1 * x * y
ret += 0.1 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0
ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0
return ret;
}
// 地球坐标系 (WGS-84) -> 火星坐标系 (GCJ-02)
func wgs2gcj(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
if outOfChina(coordinate) == true {
return coordinate
}
let wgLat = coordinate.latitude
let wgLon = coordinate.longitude
var dLat = transformLat(wgLon - 105.0, y: wgLat - 35.0)
var dLon = transformLon(wgLon - 105.0, y: wgLat - 35.0)
let radLat = wgLat / 180.0 * M_PI
var magic = sin(radLat)
magic = 1 - ee * magic * magic
let sqrtMagic = sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI)
dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI)
return CLLocationCoordinate2DMake(wgLat + dLat, wgLon + dLon)
}
// 地球坐标系 (WGS-84) <- 火星坐标系 (GCJ-02)
func gcj2wgs(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
if outOfChina(coordinate) == true {
return coordinate
}
let c2 = wgs2gcj(coordinate)
return CLLocationCoordinate2DMake(2 * coordinate.latitude - c2.latitude, 2 * coordinate.longitude - c2.longitude)
}
// 计算两点距离
func getDistinct(currentLocation:CLLocation,targetLocation:CLLocation) -> Double
{
let distance:CLLocationDistance = currentLocation.distanceFromLocation(targetLocation)
return distance
}
extension CLLocationCoordinate2D {
func toMars() -> CLLocationCoordinate2D {
return wgs2gcj(self)
}
}
| 1f4bc455f62a9495f066418d6585ad7f | 30.873563 | 117 | 0.601154 | false | false | false | false |
IBM-Swift/Kitura | refs/heads/master | Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift | apache-2.0 | 1 | /*
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import LoggerAPI
import KituraNet
import KituraContracts
// Type-safe middleware Codable router
extension Router {
// MARK: Codable Routing with TypeSafeMiddleware
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns a single Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and an Identifier, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: ([(Int, User)]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, and returns an array of (Identifier, Codable) tuples or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
respondWith(userArray, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, middle3: Middle3, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
*/
public func delete<T: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query?,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, middle3, Middle3, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns an Identifier and a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.put("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func put<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, r id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.patch("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func patch<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
// Function to call the static handle function of a TypeSafeMiddleware and on success return
// an instance of the middleware or on failing set the response error and return nil.
private func handleMiddleware<T: TypeSafeMiddleware>(
_ middlewareType: T.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T?) -> Void
) {
T.handle(request: request, response: response) { (typeSafeMiddleware: T?, error: RequestError?) in
guard let typeSafeMiddleware = typeSafeMiddleware else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil)
}
completion(typeSafeMiddleware)
}
}
// Function to call the static handle function of two TypeSafeMiddleware in sequence and on success return
// both instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2)
}
}
}
// Function to call the static handle function of three TypeSafeMiddleware in sequence and on success return
// all instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
_ middlewareThreeType: T3.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?, T3?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil, nil)
}
T3.handle(request: request, response: response) { (typeSafeMiddleware3: T3?, error: RequestError?) in
guard let typeSafeMiddleware3 = typeSafeMiddleware3 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, typeSafeMiddleware2, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3)
}
}
}
}
}
| a04ffaccf355dd54c34c35b25bb6d866 | 55.379864 | 210 | 0.654494 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie | refs/heads/master | Example/Pods/HandyJSON/HandyJSON/OtherExtension.swift | mit | 13 | /*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// OtherExtension.swift
// HandyJSON
//
// Created by zhouzhuo on 08/01/2017.
//
protocol UTF8Initializable {
init?(validatingUTF8: UnsafePointer<CChar>)
}
extension String : UTF8Initializable {}
extension Array where Element : UTF8Initializable {
init(utf8Strings: UnsafePointer<CChar>) {
var strings = [Element]()
var pointer = utf8Strings
while let string = Element(validatingUTF8: pointer) {
strings.append(string)
while pointer.pointee != 0 {
pointer.advance()
}
pointer.advance()
guard pointer.pointee != 0 else {
break
}
}
self = strings
}
}
extension Strideable {
mutating func advance() {
self = advanced(by: 1)
}
}
extension UnsafePointer {
init<T>(_ pointer: UnsafePointer<T>) {
self = UnsafeRawPointer(pointer).assumingMemoryBound(to: Pointee.self)
}
}
func relativePointer<T, U, V>(base: UnsafePointer<T>, offset: U) -> UnsafePointer<V> where U : Integer {
return UnsafeRawPointer(base).advanced(by: Int(integer: offset)).assumingMemoryBound(to: V.self)
}
extension Int {
fileprivate init<T : Integer>(integer: T) {
switch integer {
case let value as Int: self = value
case let value as Int32: self = Int(value)
case let value as Int16: self = Int(value)
case let value as Int8: self = Int(value)
default: self = 0
}
}
}
| 0e8e0f93272e85c9a4def16e291ee58e | 26.763158 | 104 | 0.641706 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Extensions/S3/S3RequestMiddleware.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import NIO
import SotoCore
import SotoCrypto
import SotoXML
public struct S3RequestMiddleware: AWSServiceMiddleware {
public init() {}
/// edit request before sending to S3
public func chain(request: AWSRequest, context: AWSMiddlewareContext) throws -> AWSRequest {
var request = request
self.virtualAddressFixup(request: &request, context: context)
self.createBucketFixup(request: &request)
self.calculateMD5(request: &request)
return request
}
/// Edit responses coming back from S3
public func chain(response: AWSResponse, context: AWSMiddlewareContext) throws -> AWSResponse {
var response = response
self.metadataFixup(response: &response)
self.getLocationResponseFixup(response: &response)
return response
}
func virtualAddressFixup(request: inout AWSRequest, context: AWSMiddlewareContext) {
/// process URL into form ${bucket}.s3.amazon.com
let paths = request.url.path.split(separator: "/", omittingEmptySubsequences: true)
if paths.count > 0 {
guard var host = request.url.host else { return }
if let port = request.url.port {
host = "\(host):\(port)"
}
let bucket = paths[0]
var urlPath: String
var urlHost: String
// if host name contains amazonaws.com and bucket name doesn't contain a period do virtual address look up
if host.contains("amazonaws.com") || context.options.contains(.s3ForceVirtualHost), !bucket.contains(".") {
let pathsWithoutBucket = paths.dropFirst() // bucket
urlPath = pathsWithoutBucket.joined(separator: "/")
if let firstHostComponent = host.split(separator: ".").first, bucket == firstHostComponent {
// Bucket name is part of host. No need to append bucket
urlHost = host
} else {
urlHost = "\(bucket).\(host)"
}
} else {
urlPath = paths.joined(separator: "/")
urlHost = host
}
// add percent encoding back into path as converting from URL to String has removed it
let percentEncodedUrlPath = Self.urlEncodePath(urlPath)
var urlString = "\(request.url.scheme ?? "https")://\(urlHost)/\(percentEncodedUrlPath)"
if let query = request.url.query {
urlString += "?\(query)"
}
request.url = URL(string: urlString)!
}
}
static let pathAllowedCharacters = CharacterSet.urlPathAllowed.subtracting(.init(charactersIn: "+"))
/// percent encode path value.
private static func urlEncodePath(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: Self.pathAllowedCharacters) ?? value
}
func createBucketFixup(request: inout AWSRequest) {
switch request.operation {
// fixup CreateBucket to include location
case "CreateBucket":
var xml = ""
if request.region != .useast1 {
xml += "<CreateBucketConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
xml += "<LocationConstraint>"
xml += request.region.rawValue
xml += "</LocationConstraint>"
xml += "</CreateBucketConfiguration>"
}
request.body = .text(xml)
default:
break
}
}
func calculateMD5(request: inout AWSRequest) {
guard let byteBuffer = request.body.asByteBuffer(byteBufferAllocator: ByteBufferAllocator()) else { return }
guard request.httpHeaders["Content-MD5"].first == nil else { return }
// if request has a body, calculate the MD5 for that body
let byteBufferView = byteBuffer.readableBytesView
if let encoded = byteBufferView.withContiguousStorageIfAvailable({ bytes in
return Data(Insecure.MD5.hash(data: bytes)).base64EncodedString()
}) {
request.httpHeaders.replaceOrAdd(name: "Content-MD5", value: encoded)
}
}
func getLocationResponseFixup(response: inout AWSResponse) {
if case .xml(let element) = response.body {
// GetBucketLocation comes back without a containing xml element
if element.name == "LocationConstraint" {
if element.stringValue == "" {
element.addChild(.text(stringValue: "us-east-1"))
}
let parentElement = XML.Element(name: "BucketLocation")
parentElement.addChild(element)
response.body = .xml(parentElement)
}
}
}
func metadataFixup(response: inout AWSResponse) {
// convert x-amz-meta-* header values into a dictionary, which we add as a "x-amz-meta-" header. This is processed by AWSClient to fill metadata values in GetObject and HeadObject
switch response.body {
case .raw(_), .empty:
var metadata: [String: String] = [:]
for (key, value) in response.headers {
if key.hasPrefix("x-amz-meta-"), let value = value as? String {
let keyWithoutPrefix = key.dropFirst("x-amz-meta-".count)
metadata[String(keyWithoutPrefix)] = value
}
}
if !metadata.isEmpty {
response.headers["x-amz-meta-"] = metadata
}
default:
break
}
}
}
| 68e9495cee7d7c165aeef4519e511149 | 39.673333 | 187 | 0.586297 | false | false | false | false |
ming1016/smck | refs/heads/master | smck/Parser/H5Parser.swift | apache-2.0 | 1 | //
// H5Parser.swift
// smck
//
// Created by DaiMing on 2017/4/17.
// Copyright © 2017年 Starming. All rights reserved.
//
import Foundation
enum H5ParseError: Swift.Error {
case unexpectedToken(String)
case unexpectedEOF
}
class H5Parser {
let tokens: [String]
var index = 0
init(tokens:[String]) {
self.tokens = tokens
}
func parseFile() throws -> H5File {
let file = H5File()
while currentToken != nil {
let tag = try parseTag()
file.addTag(tag)
// consumeToken()
}
return file
}
func parseTag() throws -> H5Tag {
guard currentToken != nil else {
throw H5ParseError.unexpectedEOF
}
var name = ""
var subs = [H5Tag]()
var attributes = [String:String]()
var value = ""
var currentAttribuiteName = ""
var psStep = 0 //0:初始,1:标签名,2:标签名取完,3:获取属性值,4:斜线完结,5:标签完结,6:整个标签完成
while let tk = currentToken {
if psStep == 6 {
break
}
if psStep == 5 {
if tk == "<" {
let nextIndex = index + 1
let nextTk = nextIndex < tokens.count ? tokens[nextIndex] : nil
if nextTk == "/" {
while let tok = currentToken {
if tok == ">" {
consumeToken()
break
}
consumeToken()
}
break
}
}
subs.append(try parseTag())
}
if psStep == 4 {
if tk == ">" {
psStep = 6
consumeToken()
continue
}
}
if psStep == 3 {
if tk == "\"" || tk == "'" {
consumeToken()
var str = ""
while let tok = currentToken {
if tok == "\"" {
consumeToken()
break
}
consumeToken()
str.append(tok)
}
attributes[currentAttribuiteName] = str
psStep = 2
continue
}
}
if psStep == 2 {
if tk == "=" {
psStep = 3
consumeToken()
continue
}
if tk == "/" {
psStep = 4
consumeToken()
continue
}
if tk == ">" {
psStep = 5
consumeToken()
continue
}
currentAttribuiteName = tk
consumeToken()
continue
}
if psStep == 1 {
name = tk
psStep = 2
consumeToken()
continue
}
if psStep == 0 {
//
if tk == "<" {
psStep = 1
consumeToken()
continue
} else {
consumeToken()
value = tk
break
}
}
}
return H5Tag(name: name, subs: subs, attributes: attributes, value: value)
}
/*------------------*/
var currentToken: String? {
return index < tokens.count ? tokens[index] : nil
}
func consumeToken(n: Int = 1) {
index += n
}
}
| 6acea83fea3142383a15cba12e3a8c1c | 25.051948 | 83 | 0.332752 | false | false | false | false |
Epaus/SimpleParseTimelineAndMenu | refs/heads/master | SimpleParseTimelineAndMenu/MenuCell.swift | gpl-3.0 | 1 | //
// MenuCell.swift
//
// Created by Estelle Paus on 12/1/14.
// Copyright (c) 2014 Estelle Paus. All rights reserved.
//
import Foundation
import UIKit
class MenuCell: UITableViewCell {
var leftMargin : CGFloat!
var topMargin : CGFloat!
var rightMargin : CGFloat!
var width : CGFloat!
var iconImageView: UIImageView!
var menuDividerView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var countContainer: UIView!
override func awakeFromNib() {
self.leftMargin = self.contentView.layer.frame.width * 0.10
self.topMargin = self.contentView.layer.frame.height * 0.70
self.rightMargin = self.contentView.layer.frame.width * 0.95
self.width = self.contentView.layer.frame.width
titleLabel.font = UIFont(name: "Avenir-Black", size: 18)
titleLabel.textColor = UIColor.whiteColor()
// countLabel.font = UIFont(name: "Avenir-Black", size: 13)
// countLabel.textColor = UIColor.whiteColor()
// countContainer.layer.cornerRadius = 15
setupIconImageView()
}
override func setSelected(selected: Bool, animated: Bool) {
// count of items after query, not yet applicable
// let countNotAvailable = countLabel.text == nil
// countContainer.hidden = countNotAvailable
// countLabel.hidden = countNotAvailable
}
func setupIconImageView()
{
self.iconImageView = UIImageView()
var iconImageViewX = self.leftMargin
var iconImageViewSideLen = self.contentView.frame.width * 0.07
self.iconImageView.frame = CGRectMake(iconImageViewX, self.topMargin, iconImageViewSideLen, iconImageViewSideLen)
self.iconImageView.layer.cornerRadius = 5.0
self.iconImageView.clipsToBounds = true
self.contentView.addSubview(self.iconImageView)
}
}
| 7caf8cafe08c27bee32964511b24bbb5 | 27.257143 | 121 | 0.647118 | false | false | false | false |
society2012/PGDBK | refs/heads/master | PGDBK/Pods/DrawerController/DrawerController/DrawerVisualState.swift | mit | 1 | // Copyright (c) 2014 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import QuartzCore
public struct DrawerVisualState {
/**
Creates a slide and scale visual state block that gives an experience similar to Mailbox.app. It scales from 90% to 100%, and translates 50 pixels in the x direction. In addition, it also sets alpha from 0.0 to 1.0.
- returns: The visual state block.
*/
public static var slideAndScaleVisualStateBlock: DrawerControllerDrawerVisualStateBlock {
let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in
let minScale: CGFloat = 0.9
let scale: CGFloat = minScale + (percentVisible * (1.0-minScale))
let scaleTransform = CATransform3DMakeScale(scale, scale, scale)
let maxDistance: CGFloat = 50
let distance: CGFloat = maxDistance * percentVisible
var translateTransform = CATransform3DIdentity
var sideDrawerViewController: UIViewController?
if drawerSide == DrawerSide.left {
sideDrawerViewController = drawerController.leftDrawerViewController
translateTransform = CATransform3DMakeTranslation((maxDistance - distance), 0, 0)
} else if drawerSide == DrawerSide.right {
sideDrawerViewController = drawerController.rightDrawerViewController
translateTransform = CATransform3DMakeTranslation(-(maxDistance-distance), 0.0, 0.0)
}
sideDrawerViewController?.view.layer.transform = CATransform3DConcat(scaleTransform, translateTransform)
sideDrawerViewController?.view.alpha = percentVisible
}
return visualStateBlock
}
/**
Creates a slide visual state block that gives the user an experience that slides at the same speed of the center view controller during animation. This is equal to calling `parallaxVisualStateBlockWithParallaxFactor:` with a parallax factor of 1.0.
- returns: The visual state block.
*/
public static var slideVisualStateBlock: DrawerControllerDrawerVisualStateBlock {
return self.parallaxVisualStateBlock(parallaxFactor: 1.0)
}
/**
Creates a swinging door visual state block that gives the user an experience that animates the drawer in along the hinge.
- returns: The visual state block.
*/
public static var swingingDoorVisualStateBlock: DrawerControllerDrawerVisualStateBlock {
let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in
var sideDrawerViewController: UIViewController?
var anchorPoint: CGPoint
var maxDrawerWidth: CGFloat = 0.0
var xOffset: CGFloat
var angle: CGFloat = 0.0
if drawerSide == .left {
sideDrawerViewController = drawerController.leftDrawerViewController
anchorPoint = CGPoint(x: 1.0, y: 0.5)
maxDrawerWidth = max(drawerController.maximumLeftDrawerWidth, drawerController.visibleLeftDrawerWidth)
xOffset = -(maxDrawerWidth / 2) + maxDrawerWidth * percentVisible
angle = -CGFloat(M_PI_2) + percentVisible * CGFloat(M_PI_2)
} else {
sideDrawerViewController = drawerController.rightDrawerViewController
anchorPoint = CGPoint(x: 0.0, y: 0.5)
maxDrawerWidth = max(drawerController.maximumRightDrawerWidth, drawerController.visibleRightDrawerWidth)
xOffset = (maxDrawerWidth / 2) - maxDrawerWidth * percentVisible
angle = CGFloat(M_PI_2) - percentVisible * CGFloat(M_PI_2)
}
sideDrawerViewController?.view.layer.anchorPoint = anchorPoint
sideDrawerViewController?.view.layer.shouldRasterize = true
sideDrawerViewController?.view.layer.rasterizationScale = UIScreen.main.scale
var swingingDoorTransform: CATransform3D = CATransform3DIdentity
if percentVisible <= 1.0 {
var identity: CATransform3D = CATransform3DIdentity
identity.m34 = -1.0 / 1000.0
let rotateTransform: CATransform3D = CATransform3DRotate(identity, angle,
0.0, 1.0, 0.0)
let translateTransform: CATransform3D = CATransform3DMakeTranslation(xOffset, 0.0, 0.0)
let concatTransform = CATransform3DConcat(rotateTransform, translateTransform)
swingingDoorTransform = concatTransform
} else {
var overshootTransform = CATransform3DMakeScale(percentVisible, 1.0, 1.0)
var scalingModifier: CGFloat = 1.0
if (drawerSide == .right) {
scalingModifier = -1.0
}
overshootTransform = CATransform3DTranslate(overshootTransform, scalingModifier * maxDrawerWidth / 2, 0.0, 0.0)
swingingDoorTransform = overshootTransform
}
sideDrawerViewController?.view.layer.transform = swingingDoorTransform
}
return visualStateBlock
}
/**
Creates a parallax experience that slides the side drawer view controller at a different rate than the center view controller during animation. For every parallaxFactor of points moved by the center view controller, the side drawer view controller will move 1 point. Passing in 1.0 is the equivalent of a applying a sliding animation, while passing in MAX_FLOAT is the equivalent of having no animation at all.
- parameter parallaxFactor: The amount of parallax applied to the side drawer conroller. This value must be greater than 1.0. The closer the value is to 1.0, the faster the side drawer view controller will be parallaxing.
- returns: The visual state block.
*/
public static func parallaxVisualStateBlock(parallaxFactor: CGFloat) -> DrawerControllerDrawerVisualStateBlock {
let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in
assert({ () -> Bool in
return parallaxFactor >= 1.0
}(), "parallaxFactor must be >= 1.0")
var transform: CATransform3D = CATransform3DIdentity
var sideDrawerViewController: UIViewController?
if (drawerSide == .left) {
sideDrawerViewController = drawerController.leftDrawerViewController
let distance: CGFloat = max(drawerController.maximumLeftDrawerWidth, drawerController.visibleLeftDrawerWidth)
if (percentVisible <= 1.0) {
transform = CATransform3DMakeTranslation((-distance) / parallaxFactor + (distance * percentVisible / parallaxFactor), 0.0, 0.0)
} else {
transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0)
transform = CATransform3DTranslate(transform, drawerController.maximumLeftDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0)
}
} else if (drawerSide == .right) {
sideDrawerViewController = drawerController.rightDrawerViewController
let distance: CGFloat = max(drawerController.maximumRightDrawerWidth, drawerController.visibleRightDrawerWidth)
if (percentVisible <= 1.0) {
transform = CATransform3DMakeTranslation((distance) / parallaxFactor - (distance * percentVisible / parallaxFactor), 0.0, 0.0)
} else {
transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0)
transform = CATransform3DTranslate(transform, -drawerController.maximumRightDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0)
}
}
sideDrawerViewController?.view.layer.transform = transform
}
return visualStateBlock
}
public static var animatedHamburgerButtonVisualStateBlock: DrawerControllerDrawerVisualStateBlock {
let visualStateBlock: DrawerControllerDrawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) -> Void in
var hamburgerItem: DrawerBarButtonItem?
if let navController = drawerController.centerViewController as? UINavigationController {
if (drawerSide == .left) {
if let item = navController.topViewController!.navigationItem.leftBarButtonItem as? DrawerBarButtonItem {
hamburgerItem = item
}
} else if (drawerSide == .right) {
if let item = navController.topViewController!.navigationItem.rightBarButtonItem as? DrawerBarButtonItem {
hamburgerItem = item
}
}
}
hamburgerItem?.animate(withPercentVisible: percentVisible, drawerSide: drawerSide)
}
return visualStateBlock
}
}
| 89c8249df2b95dc60b0ce5ba63386c90 | 53.062176 | 415 | 0.654591 | false | false | false | false |
aquarchitect/MyKit | refs/heads/master | Sources/Shared/Extensions/CloudKit/CKDatabase+.swift | mit | 1 | //
// CKDatabase+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
import CloudKit
public extension CKDatabase {
func fetchCurrentUser() -> Promise<CKRecord> {
return Promise { callback in
let operation = CKFetchRecordsOperation.fetchCurrentUserRecordOperation()
operation.perRecordCompletionBlock = { callback(Result($0, $2)) }
self.add(operation)
}
}
}
public extension CKDatabase {
func save(_ record: CKRecord) -> Promise<CKRecord> {
return Promise { (callback: @escaping Result<CKRecord>.Callback) in
let handler = Result.init >>> callback
self.save(record, completionHandler: handler)
}
}
func delete(withRecordID recordID: CKRecordID) -> Promise<CKRecordID> {
return Promise { (callback: @escaping Result<CKRecordID>.Callback) in
let handler = Result.init >>> callback
self.delete(withRecordID: recordID, completionHandler: handler)
}
}
func fetch(withRecordID recordID: CKRecordID) -> Promise<CKRecord> {
return Promise { (callback: @escaping Result<CKRecord>.Callback) in
let handler = Result.init >>> callback
self.fetch(withRecordID: recordID, completionHandler: handler)
}
}
func perform(_ query: CKQuery, inZoneWith zoneID: CKRecordZoneID? = nil) -> Promise<[CKRecord]> {
return Promise { (callback: @escaping Result<[CKRecord]>.Callback) in
let handler = Result.init >>> callback
self.perform(query, inZoneWith: zoneID, completionHandler: handler)
}
}
}
| 83bcb222e4c781b3b9f33c2c1f27fba5 | 31.607843 | 101 | 0.637402 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB/MGDYZB/Class/Home/扫一扫/Source/LBXScanWrapper.swift | mit | 1 | //
// LBXScanWrapper.swift
// swiftScan https://github.com/MxABC/swiftScan
//
// Created by lbxia on 15/12/10.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
import AVFoundation
public struct LBXScanResult {
//码内容
public var strScanned:String? = ""
//扫描图像
public var imgScanned:UIImage?
//码的类型
public var strBarCodeType:String? = ""
//码在图像中的位置
public var arrayCorner:[AnyObject]?
public init(str:String?,img:UIImage?,barCodeType:String?,corner:[AnyObject]?)
{
self.strScanned = str
self.imgScanned = img
self.strBarCodeType = barCodeType
self.arrayCorner = corner
}
}
open class LBXScanWrapper: NSObject,AVCaptureMetadataOutputObjectsDelegate {
let device:AVCaptureDevice? = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo);
var input:AVCaptureDeviceInput?
var output:AVCaptureMetadataOutput
let session = AVCaptureSession()
var previewLayer:AVCaptureVideoPreviewLayer?
var stillImageOutput:AVCaptureStillImageOutput?
//存储返回结果
var arrayResult:[LBXScanResult] = [];
//扫码结果返回block
var successBlock:([LBXScanResult]) -> Void
//是否需要拍照
var isNeedCaptureImage:Bool
//当前扫码结果是否处理
var isNeedScanResult:Bool = true
/**
初始化设备
- parameter videoPreView: 视频显示UIView
- parameter objType: 识别码的类型,缺省值 QR二维码
- parameter isCaptureImg: 识别后是否采集当前照片
- parameter cropRect: 识别区域
- parameter success: 返回识别信息
- returns:
*/
init( videoPreView:UIView,objType:[String] = [AVMetadataObjectTypeQRCode],isCaptureImg:Bool,cropRect:CGRect=CGRect.zero,success:@escaping ( ([LBXScanResult]) -> Void) )
{
do{
input = try AVCaptureDeviceInput(device: device)
}
catch let error as NSError {
print("AVCaptureDeviceInput(): \(error)")
}
successBlock = success
// Output
output = AVCaptureMetadataOutput()
isNeedCaptureImage = isCaptureImg
stillImageOutput = AVCaptureStillImageOutput();
super.init()
if device == nil
{
return
}
if session.canAddInput(input)
{
session.addInput(input)
}
if session.canAddOutput(output)
{
session.addOutput(output)
}
if session.canAddOutput(stillImageOutput)
{
session.addOutput(stillImageOutput)
}
let outputSettings:Dictionary = [AVVideoCodecJPEG:AVVideoCodecKey]
stillImageOutput?.outputSettings = outputSettings
session.sessionPreset = AVCaptureSessionPresetHigh
//参数设置
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = objType
// output.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]
if !cropRect.equalTo(CGRect.zero)
{
//启动相机后,直接修改该参数无效
output.rectOfInterest = cropRect
}
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
var frame:CGRect = videoPreView.frame
frame.origin = CGPoint.zero
previewLayer?.frame = frame
videoPreView.layer .insertSublayer(previewLayer!, at: 0)
if ( device!.isFocusPointOfInterestSupported && device!.isFocusModeSupported(AVCaptureFocusMode.continuousAutoFocus) )
{
do
{
try input?.device.lockForConfiguration()
input?.device.focusMode = AVCaptureFocusMode.continuousAutoFocus
input?.device.unlockForConfiguration()
}
catch let error as NSError {
print("device.lockForConfiguration(): \(error)")
}
}
}
func start()
{
if !session.isRunning
{
isNeedScanResult = true
session.startRunning()
}
}
func stop()
{
if session.isRunning
{
isNeedScanResult = false
session.stopRunning()
}
}
open func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if !isNeedScanResult
{
//上一帧处理中
return
}
isNeedScanResult = false
arrayResult.removeAll()
//识别扫码类型
for current:Any in metadataObjects
{
if (current as AnyObject).isKind(of: AVMetadataMachineReadableCodeObject.self)
{
let code = current as! AVMetadataMachineReadableCodeObject
//码类型
let codeType = code.type
print("code type:%@",codeType)
//码内容
let codeContent = code.stringValue
print("code string:%@",codeContent)
//4个字典,分别 左上角-右上角-右下角-左下角的 坐标百分百,可以使用这个比例抠出码的图像
// let arrayRatio = code.corners
arrayResult.append(LBXScanResult(str: codeContent, img: UIImage(), barCodeType: codeType,corner: code.corners as [AnyObject]?))
}
}
if arrayResult.count > 0
{
if isNeedCaptureImage
{
captureImage()
}
else
{
stop()
successBlock(arrayResult)
}
}
else
{
isNeedScanResult = true
}
}
//MARK: ----拍照
open func captureImage()
{
let stillImageConnection:AVCaptureConnection? = connectionWithMediaType(mediaType: AVMediaTypeVideo, connections: (stillImageOutput?.connections)! as [AnyObject])
stillImageOutput?.captureStillImageAsynchronously(from: stillImageConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in
self.stop()
if imageDataSampleBuffer != nil
{
let imageData: Data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) as Data
let scanImg:UIImage? = UIImage(data: imageData)
for idx in 0...self.arrayResult.count-1
{
self.arrayResult[idx].imgScanned = scanImg
}
}
self.successBlock(self.arrayResult)
})
}
open func connectionWithMediaType(mediaType:String,connections:[AnyObject]) -> AVCaptureConnection?
{
for connection:AnyObject in connections
{
let connectionTmp:AVCaptureConnection = connection as! AVCaptureConnection
for port:Any in connectionTmp.inputPorts
{
if (port as AnyObject).isKind(of: AVCaptureInputPort.self)
{
let portTmp:AVCaptureInputPort = port as! AVCaptureInputPort
if portTmp.mediaType == mediaType
{
return connectionTmp
}
}
}
}
return nil
}
//MARK:切换识别区域
open func changeScanRect(cropRect:CGRect)
{
//待测试,不知道是否有效
stop()
output.rectOfInterest = cropRect
start()
}
//MARK: 切换识别码的类型
open func changeScanType(objType:[String])
{
//待测试中途修改是否有效
output.metadataObjectTypes = objType
}
open func isGetFlash()->Bool
{
if (device != nil && device!.hasFlash && device!.hasTorch)
{
return true
}
return false
}
/**
打开或关闭闪关灯
- parameter torch: true:打开闪关灯 false:关闭闪光灯
*/
open func setTorch(torch:Bool)
{
if isGetFlash()
{
do
{
try input?.device.lockForConfiguration()
input?.device.torchMode = torch ? AVCaptureTorchMode.on : AVCaptureTorchMode.off
input?.device.unlockForConfiguration()
}
catch let error as NSError {
print("device.lockForConfiguration(): \(error)")
}
}
}
/**
------闪光灯打开或关闭
*/
open func changeTorch()
{
if isGetFlash()
{
do
{
try input?.device.lockForConfiguration()
var torch = false
if input?.device.torchMode == AVCaptureTorchMode.on
{
torch = false
}
else if input?.device.torchMode == AVCaptureTorchMode.off
{
torch = true
}
input?.device.torchMode = torch ? AVCaptureTorchMode.on : AVCaptureTorchMode.off
input?.device.unlockForConfiguration()
}
catch let error as NSError {
print("device.lockForConfiguration(): \(error)")
}
}
}
//MARK: ------获取系统默认支持的码的类型
static func defaultMetaDataObjectTypes() ->[String]
{
var types =
[AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeAztecCode,
];
//if #available(iOS 8.0, *)
types.append(AVMetadataObjectTypeInterleaved2of5Code)
types.append(AVMetadataObjectTypeITF14Code)
types.append(AVMetadataObjectTypeDataMatrixCode)
types.append(AVMetadataObjectTypeInterleaved2of5Code)
types.append(AVMetadataObjectTypeITF14Code)
types.append(AVMetadataObjectTypeDataMatrixCode)
return types;
}
static func isSysIos8Later()->Bool
{
// return Float(UIDevice.currentDevice().systemVersion) >= 8.0 ? true:false
return floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_0
}
/**
识别二维码码图像
- parameter image: 二维码图像
- returns: 返回识别结果
*/
static open func recognizeQRImage(image:UIImage) ->[LBXScanResult]
{
var returnResult:[LBXScanResult]=[]
if LBXScanWrapper.isSysIos8Later()
{
//if #available(iOS 8.0, *)
let detector:CIDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])!
let img = CIImage(cgImage: (image.cgImage)!)
let features:[CIFeature]? = detector.features(in: img, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
if( features != nil && (features?.count)! > 0)
{
let feature = features![0]
if feature.isKind(of: CIQRCodeFeature.self)
{
let featureTmp:CIQRCodeFeature = feature as! CIQRCodeFeature
let scanResult = featureTmp.messageString
let result = LBXScanResult(str: scanResult, img: image, barCodeType: AVMetadataObjectTypeQRCode,corner: nil)
returnResult.append(result)
}
}
}
return returnResult
}
//MARK: -- - 生成二维码,背景色及二维码颜色设置
static open func createCode( codeType:String, codeString:String, size:CGSize,qrColor:UIColor,bkColor:UIColor )->UIImage?
{
//if #available(iOS 8.0, *)
let stringData = codeString.data(using: String.Encoding.utf8)
//系统自带能生成的码
// CIAztecCodeGenerator
// CICode128BarcodeGenerator
// CIPDF417BarcodeGenerator
// CIQRCodeGenerator
let qrFilter = CIFilter(name: codeType)
qrFilter?.setValue(stringData, forKey: "inputMessage")
qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
//上色
let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage":qrFilter!.outputImage!,"inputColor0":CIColor(cgColor: qrColor.cgColor),"inputColor1":CIColor(cgColor: bkColor.cgColor)])
let qrImage = colorFilter!.outputImage!;
//绘制
let cgImage = CIContext().createCGImage(qrImage, from: qrImage.extent)!
UIGraphicsBeginImageContext(size);
let context = UIGraphicsGetCurrentContext()!;
context.interpolationQuality = CGInterpolationQuality.none;
context.scaleBy(x: 1.0, y: -1.0);
context.draw(cgImage, in: context.boundingBoxOfClipPath)
let codeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return codeImage
}
static open func createCode128( codeString:String, size:CGSize,qrColor:UIColor,bkColor:UIColor )->UIImage?
{
let stringData = codeString.data(using: String.Encoding.utf8)
//系统自带能生成的码
// CIAztecCodeGenerator 二维码
// CICode128BarcodeGenerator 条形码
// CIPDF417BarcodeGenerator
// CIQRCodeGenerator 二维码
let qrFilter = CIFilter(name: "CICode128BarcodeGenerator")
qrFilter?.setDefaults()
qrFilter?.setValue(stringData, forKey: "inputMessage")
let outputImage:CIImage? = qrFilter?.outputImage
let context = CIContext()
let cgImage = context.createCGImage(outputImage!, from: outputImage!.extent)
let image = UIImage(cgImage: cgImage!, scale: 1.0, orientation: UIImageOrientation.up)
// Resize without interpolating
let scaleRate:CGFloat = 20.0
let resized = resizeImage(image: image, quality: CGInterpolationQuality.none, rate: scaleRate)
return resized;
}
//MARK:根据扫描结果,获取图像中得二维码区域图像(如果相机拍摄角度故意很倾斜,获取的图像效果很差)
static func getConcreteCodeImage(srcCodeImage:UIImage,codeResult:LBXScanResult)->UIImage?
{
let rect:CGRect = getConcreteCodeRectFromImage(srcCodeImage: srcCodeImage, codeResult: codeResult)
if rect.isEmpty
{
return nil
}
let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect)
if img != nil
{
let imgRotation = imageRotation(image: img!, orientation: UIImageOrientation.right)
return imgRotation
}
return nil
}
//根据二维码的区域截取二维码区域图像
static open func getConcreteCodeImage(srcCodeImage:UIImage,rect:CGRect)->UIImage?
{
if rect.isEmpty
{
return nil
}
let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect)
if img != nil
{
let imgRotation = imageRotation(image: img!, orientation: UIImageOrientation.right)
return imgRotation
}
return nil
}
//获取二维码的图像区域
static open func getConcreteCodeRectFromImage(srcCodeImage:UIImage,codeResult:LBXScanResult)->CGRect
{
if (codeResult.arrayCorner == nil || (codeResult.arrayCorner?.count)! < 4 )
{
return CGRect.zero
}
let corner:[[String:Float]] = codeResult.arrayCorner as! [[String:Float]]
let dicTopLeft = corner[0]
let dicTopRight = corner[1]
let dicBottomRight = corner[2]
let dicBottomLeft = corner[3]
let xLeftTopRatio:Float = dicTopLeft["X"]!
let yLeftTopRatio:Float = dicTopLeft["Y"]!
let xRightTopRatio:Float = dicTopRight["X"]!
let yRightTopRatio:Float = dicTopRight["Y"]!
let xBottomRightRatio:Float = dicBottomRight["X"]!
let yBottomRightRatio:Float = dicBottomRight["Y"]!
let xLeftBottomRatio:Float = dicBottomLeft["X"]!
let yLeftBottomRatio:Float = dicBottomLeft["Y"]!
//由于截图只能矩形,所以截图不规则四边形的最大外围
let xMinLeft = CGFloat( min(xLeftTopRatio, xLeftBottomRatio) )
let xMaxRight = CGFloat( max(xRightTopRatio, xBottomRightRatio) )
let yMinTop = CGFloat( min(yLeftTopRatio, yRightTopRatio) )
let yMaxBottom = CGFloat ( max(yLeftBottomRatio, yBottomRightRatio) )
let imgW = srcCodeImage.size.width
let imgH = srcCodeImage.size.height
//宽高反过来计算
let rect = CGRect(x: xMinLeft * imgH, y: yMinTop*imgW, width: (xMaxRight-xMinLeft)*imgH, height: (yMaxBottom-yMinTop)*imgW)
return rect
}
//MARK: ----图像处理
/**
@brief 图像中间加logo图片
@param srcImg 原图像
@param LogoImage logo图像
@param logoSize logo图像尺寸
@return 加Logo的图像
*/
static open func addImageLogo(srcImg:UIImage,logoImg:UIImage,logoSize:CGSize )->UIImage
{
UIGraphicsBeginImageContext(srcImg.size);
srcImg.draw(in: CGRect(x: 0, y: 0, width: srcImg.size.width, height: srcImg.size.height))
let rect = CGRect(x: srcImg.size.width/2 - logoSize.width/2, y: srcImg.size.height/2-logoSize.height/2, width:logoSize.width, height: logoSize.height);
logoImg.draw(in: rect)
let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage!;
}
//图像缩放
static func resizeImage(image:UIImage,quality:CGInterpolationQuality,rate:CGFloat)->UIImage?
{
var resized:UIImage?;
let width = image.size.width * rate;
let height = image.size.height * rate;
UIGraphicsBeginImageContext(CGSize(width: width, height: height));
let context = UIGraphicsGetCurrentContext();
context!.interpolationQuality = quality;
image.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
resized = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resized;
}
//图像裁剪
static func imageByCroppingWithStyle(srcImg:UIImage,rect:CGRect)->UIImage?
{
let imageRef = srcImg.cgImage
let imagePartRef = imageRef!.cropping(to: rect)
let cropImage = UIImage(cgImage: imagePartRef!)
return cropImage
}
//图像旋转
static func imageRotation(image:UIImage,orientation:UIImageOrientation)->UIImage
{
var rotate:Double = 0.0;
var rect:CGRect;
var translateX:CGFloat = 0.0;
var translateY:CGFloat = 0.0;
var scaleX:CGFloat = 1.0;
var scaleY:CGFloat = 1.0;
switch (orientation) {
case UIImageOrientation.left:
rotate = M_PI_2;
rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width);
translateX = 0;
translateY = -rect.size.width;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientation.right:
rotate = 3 * M_PI_2;
rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width);
translateX = -rect.size.height;
translateY = 0;
scaleY = rect.size.width/rect.size.height;
scaleX = rect.size.height/rect.size.width;
break;
case UIImageOrientation.down:
rotate = M_PI;
rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height);
translateX = -rect.size.width;
translateY = -rect.size.height;
break;
default:
rotate = 0.0;
rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height);
translateX = 0;
translateY = 0;
break;
}
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext()!;
//做CTM变换
context.translateBy(x: 0.0, y: rect.size.height);
context.scaleBy(x: 1.0, y: -1.0);
context.rotate(by: CGFloat(rotate));
context.translateBy(x: translateX, y: translateY);
context.scaleBy(x: scaleX, y: scaleY);
//绘制图片
context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))
let newPic = UIGraphicsGetImageFromCurrentImageContext();
return newPic!;
}
deinit
{
print("LBXScanWrapper deinit")
}
}
| cc37e3eca68c851742dac3a8e4e7810f | 30.183381 | 212 | 0.567031 | false | false | false | false |
soapyigu/Swift30Projects | refs/heads/master | Project 04 - TodoTDD/ToDo/Models/ToDoItem.swift | apache-2.0 | 1 | //
// ToDOItem.swift
// ToDo
//
// Created by gu, yi on 9/6/18.
// Copyright © 2018 gu, yi. All rights reserved.
//
import Foundation
struct ToDoItem {
let title: String
let itemDescription: String?
let timestamp: Double?
let location: Location?
// plist related
private let titleKey = "titleKey"
private let itemDescriptionKey = "itemDescriptionKey"
private let timestampKey = "timestampKey"
private let locationKey = "locationKey"
var plistDict: [String:Any] {
var dict = [String:Any]()
dict[titleKey] = title
if let itemDescription = itemDescription {
dict[itemDescriptionKey] = itemDescription
}
if let timestamp = timestamp {
dict[timestampKey] = timestamp
}
if let location = location {
let locationDict = location.plistDict
dict[locationKey] = locationDict
}
return dict
}
init(title: String, itemDescription: String? = nil, timeStamp: Double? = nil, location: Location? = nil) {
self.title = title
self.itemDescription = itemDescription
self.timestamp = timeStamp
self.location = location
}
init?(dict: [String: Any]) {
guard let title = dict[titleKey] as? String else {
return nil
}
self.title = title
self.itemDescription = dict[itemDescriptionKey] as? String
self.timestamp = dict[timestampKey] as? Double
if let locationDict = dict[locationKey] as? [String: Any] {
self.location = Location(dict: locationDict)
} else {
self.location = nil
}
}
}
extension ToDoItem: Equatable {
static func ==(lhs: ToDoItem, rhs: ToDoItem) -> Bool {
return lhs.title == rhs.title && lhs.location?.name == rhs.location?.name
}
}
| 82450b0b651b6a1fcce79eeeec2fe3fc | 24.597015 | 108 | 0.658892 | false | false | false | false |
skarppi/cavok | refs/heads/master | CAVOK/Extensions/UIColor+Additions.swift | mit | 1 | //
// UIColor+Additions.swift
// CAV-OK
//
// Created by Juho Kolehmainen on 18.7.2021.
//
import Foundation
import SwiftUI
extension UIColor {
func lighter(by saturation: CGFloat) -> UIColor {
var hue: CGFloat = 0, sat: CGFloat = 0
var brt: CGFloat = 0, alpha: CGFloat = 0
guard getHue(&hue, saturation: &sat, brightness: &brt, alpha: &alpha)
else {return self}
return UIColor(hue: hue,
saturation: max(sat - saturation, 0.0),
brightness: brt,
alpha: alpha)
}
}
extension Color {
public func lighter(by amount: CGFloat = 0.2) -> Self { Self(UIColor(self).lighter(by: amount)) }
}
| bb8a5ad102795caf4ccd2ec5c8ca27bf | 23.655172 | 101 | 0.572028 | false | false | false | false |
DenHeadless/DTTableViewManager | refs/heads/master | Sources/DTTableViewManager/DTTableViewDropDelegate.swift | mit | 1 | //
// DTTableViewDropDelegate.swift
// DTTableViewManager
//
// Created by Denys Telezhkin on 20.08.17.
// Copyright © 2017 Denys Telezhkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
#if os(iOS)
/// Object, that implements `UITableViewDropDelegate` for `DTTableViewManager`.
open class DTTableViewDropDelegate: DTTableViewDelegateWrapper, UITableViewDropDelegate {
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
_ = performNonCellReaction(.performDropWithCoordinator, argument: coordinator)
(delegate as? UITableViewDropDelegate)?.tableView(tableView, performDropWith: coordinator)
}
override func delegateWasReset() {
tableView?.dropDelegate = nil
tableView?.dropDelegate = self
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
if let canHandle = performNonCellReaction(.canHandleDropSession, argument: session) as? Bool {
return canHandle
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView, canHandle: session) ?? true
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidEnter session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidEnter, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnter: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if let proposal = performNonCellReaction(.dropSessionDidUpdateWithDestinationIndexPath,
argumentOne: session,
argumentTwo: destinationIndexPath) as? UITableViewDropProposal {
return proposal
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView,
dropSessionDidUpdate: session,
withDestinationIndexPath: destinationIndexPath) ?? UITableViewDropProposal(operation: .cancel)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidExit session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidExit, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidExit: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidEnd, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnd: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? {
if let reaction = unmappedReactions.first(where: { $0.methodSignature == EventMethodSignature.dropPreviewParametersForRowAtIndexPath.rawValue }) {
return reaction.performWithArguments((indexPath, 0, 0)) as? UIDragPreviewParameters
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView,
dropPreviewParametersForRowAt: indexPath)
}
}
#endif
| 43312389f044afdd8e5ae62bd283de7a | 53.32967 | 182 | 0.707524 | false | false | false | false |
jsonkuan/SMILe | refs/heads/master | SMILe/ScoreboardTableViewController.swift | gpl-3.0 | 1 | //
// LeaderboardTableViewController.swift
// SMILe
//
// Created by Jason Kuan on 16/03/16.
// Copyright © 2016 jsonkuan. All rights reserved.
//
import UIKit
class ScoreboardTableViewController: UITableViewController {
var people: [Player] = PlayerData().getPlayerFromData()
var gameScore = 0
override func viewDidLoad() {
super.viewDidLoad()
}
// TODO: - Get values for people[i].playerName && people[i].score
// MARK: - TableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return people.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people[section].gameType.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return people[section].playerName
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
cell.gameType.text = people[indexPath.section].gameType[indexPath.row]
cell.scoreButton.tag = indexPath.row
cell.scoreButton.addTarget(self, action: "pressedButton", forControlEvents: .TouchUpInside)
// TODO: - Button Not working (try "isFirstResponder")
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCell
cell.scoreTextField.becomeFirstResponder()
}
// MARK: - IBActions
@IBAction func pressedButton(sender: UIButton) {
// TODO: - Increment the scoreLabel when the button is pressed
gameScore++
}
// MARK: - My Functions
func calculateLeader() {
// TODO: - Try using myArray.sort on the scores
}
}
| 40f6e38a0d4908fd5fbc3002748d6335 | 28.842857 | 118 | 0.663475 | false | false | false | false |
SemenovAlexander/snapshot | refs/heads/master | SnapshotHelper.swift | mit | 2 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
@available(*, deprecated, message="use setupSnapshot: instead")
func setLanguage(app: XCUIApplication) {
setupSnapshot(app)
}
func setupSnapshot(app: XCUIApplication) {
Snapshot.setupSnapshot(app)
}
func snapshot(name: String, waitForLoadingIndicator: Bool = true) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
class Snapshot: NSObject {
class func setupSnapshot(app: XCUIApplication) {
setLanguage(app)
setLaunchArguments(app)
}
class func setLanguage(app: XCUIApplication) {
let path = "/tmp/language.txt"
do {
locale = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
deviceLanguage = locale.substringToIndex(locale.startIndex.advancedBy(2, limit:locale.endIndex))
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-ui_testing"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLaunchArguments(app: XCUIApplication) {
let path = "/tmp/snapshot-launch_arguments.txt"
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES"]
do {
let launchArguments = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matchesInString(launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substringWithRange(result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
class func snapshot(name: String, waitForLoadingIndicator: Bool = true) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/snapshot
sleep(1) // Waiting for the animation to be finished (kind of)
XCUIDevice.sharedDevice().orientation = .Unknown
}
class func waitForLoadingIndicatorToDisappear() {
let query = XCUIApplication().statusBars.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other)
while (0..<query.count).map({ query.elementBoundByIndex($0) }).contains({ $0.isLoadingIndicator }) {
sleep(1)
print("Waiting for loading indicator to disappear...")
}
}
}
extension XCUIElement {
var isLoadingIndicator: Bool {
return self.frame.size == CGSize(width: 10, height: 20)
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [[1.0]]
| 80023fc7a5b2f64ad15c46621916c655 | 32.648936 | 146 | 0.657604 | false | false | false | false |
khizkhiz/swift | refs/heads/master | stdlib/public/SDK/Foundation/NSStringAPI.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
@warn_unused_result
func _toNSArray<T, U : AnyObject>(a: [T], @noescape f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
@warn_unused_result
func _toNSRange(r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.startIndex._utf16Index,
length: r.endIndex._utf16Index - r.startIndex._utf16Index)
}
@warn_unused_result
func _countFormatSpecifiers(a: String) -> Int {
// The implementation takes advantage of the fact that internal
// representation of String is UTF-16. Because we only care about the ASCII
// percent character, we don't need to decode UTF-16.
let percentUTF16 = UTF16.CodeUnit(("%" as UnicodeScalar).value)
let notPercentUTF16: UTF16.CodeUnit = 0
var lastChar = notPercentUTF16 // anything other than % would work here
var count = 0
for c in a.utf16 {
if lastChar == percentUTF16 {
if c == percentUTF16 {
// a "%" following this one should not be taken as literal
lastChar = notPercentUTF16
}
else {
count += 1
lastChar = c
}
} else {
lastChar = c
}
}
return count
}
extension String {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
var _ns: NSString {
return self as NSString
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
@warn_unused_result
func _index(utf16Index: Int) -> Index {
return Index(_base: String.UnicodeScalarView.Index(utf16Index, _core))
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
@warn_unused_result
func _range(r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
@warn_unused_result
func _optionalRange(r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
index: UnsafeMutablePointer<Index>,
@noescape body: (UnsafeMutablePointer<Int>) -> Result
) -> Result {
var utf16Index: Int = 0
let result = index._withBridgeValue(&utf16Index) {
body($0)
}
index._setIfNonNil { self._index(utf16Index) }
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
range: UnsafeMutablePointer<Range<Index>>,
@noescape body: (UnsafeMutablePointer<NSRange>) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = range._withBridgeValue(&nsRange) {
body($0)
}
range._setIfNonNil { self._range(nsRange) }
return result
}
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// + (const NSStringEncoding *)availableStringEncodings
/// Returns an Array of the encodings string objects support
/// in the application's environment.
@warn_unused_result
public static func availableStringEncodings() -> [NSStringEncoding] {
var result = [NSStringEncoding]()
var p = NSString.availableStringEncodings()
while p.pointee != 0 {
result.append(p.pointee)
p += 1
}
return result
}
// + (NSStringEncoding)defaultCStringEncoding
/// Returns the C-string encoding assumed for any method accepting
/// a C string as an argument.
@warn_unused_result
public static func defaultCStringEncoding() -> NSStringEncoding {
return NSString.defaultCStringEncoding()
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of a given encoding.
@warn_unused_result
public static func localizedName(
ofStringEncoding encoding: NSStringEncoding
) -> String {
return NSString.localizedName(ofStringEncoding: encoding)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
@warn_unused_result
public static func localizedStringWithFormat(
format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: NSLocale.current(),
arguments: arguments)
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message="Use fileURL(withPathComponents:) on NSURL instead.")
public static func path(withComponents components: [String]) -> String {
return NSString.path(withComponents: components)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Produces a string created by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = ns as String
} else {
return nil
}
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the
/// `String` can be converted to a given encoding without loss of
/// information.
@warn_unused_result
public func canBeConverted(toEncoding encoding: NSStringEncoding) -> Bool {
return _ns.canBeConverted(toEncoding: encoding)
}
// @property NSString* capitalizedString
/// Produce a string with the first character from each word changed
/// to the corresponding uppercase value.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the `String` that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(NSLocale *)locale
/// Returns a capitalized representation of the `String`
/// using the specified locale.
@warn_unused_result
public func capitalizedString(with locale: NSLocale?) -> String {
return _ns.capitalizedString(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
@warn_unused_result
public func caseInsensitiveCompare(aString: String) -> NSComparisonResult {
return _ns.caseInsensitiveCompare(aString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(NSStringCompareOptions)mask
/// Returns a string containing characters the `String` and a
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
@warn_unused_result
public func commonPrefix(
with aString: String, options: NSStringCompareOptions = []) -> String {
return _ns.commonPrefix(with: aString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
@warn_unused_result
public func compare(
aString: String,
options mask: NSStringCompareOptions = [],
range: Range<Index>? = nil,
locale: NSLocale? = nil
) -> NSComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
return locale != nil ? _ns.compare(
aString, options: mask,
range: _toNSRange(range ?? self.characters.indices),
locale: locale)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(range ?? self.characters.indices))
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the `String` as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the `String`.
/// Returns the actual number of matching paths.
@warn_unused_result
public func completePath(
into outputName: UnsafeMutablePointer<String> = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]> = nil,
filterTypes: [String]? = nil
) -> Int {
var nsMatches: NSArray?
var nsOutputName: NSString?
let result = outputName._withBridgeObject(&nsOutputName) {
outputName in matchesIntoArray._withBridgeObject(&nsMatches) {
matchesIntoArray in
self._ns.completePath(
into: outputName, caseSensitive: caseSensitive,
matchesInto: matchesIntoArray, filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
matchesIntoArray._setIfNonNil { _convertNSArrayToArray(matches) }
}
if let n = nsOutputName {
outputName._setIfNonNil { n as String }
}
return result
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by characters in a given set.
@warn_unused_result
public func componentsSeparatedByCharacters(
in separator: NSCharacterSet
) -> [String] {
// FIXME: two steps due to <rdar://16971181>
let nsa = _ns.componentsSeparatedByCharacters(in: separator) as NSArray
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
return _convertNSArrayToArray(nsa)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by a given separator.
public func componentsSeparated(by separator: String) -> [String] {
let nsa = _ns.componentsSeparated(by: separator) as NSArray
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
return _convertNSArrayToArray(nsa)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` as a C string
/// using a given encoding.
@warn_unused_result
public func cString(usingEncoding encoding: NSStringEncoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(usingEncoding: encoding))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns an `NSData` object containing a representation of
/// the `String` encoded using a given encoding.
@warn_unused_result
public func data(
usingEncoding encoding: NSStringEncoding,
allowLossyConversion: Bool = false
) -> NSData? {
return _ns.data(
usingEncoding: encoding,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(body: (line: String, stop: inout Bool) -> ()) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line: line, stop: &stop_)
if stop_ {
UnsafeMutablePointer<ObjCBool>(stop).pointee = true
}
}
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(NSLinguisticTaggerOptions)opts
// orthography:(NSOrthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags(
in range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions = [],
orthography: NSOrthography? = nil,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> ()
) {
_ns.enumerateLinguisticTags(
in: _toNSRange(range),
scheme: tagScheme,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the
/// specified range of the string.
public func enumerateSubstrings(
in range: Range<Index>,
options opts:NSStringEnumerationOptions = [],
_ body: (
substring: String?, substringRange: Range<Index>,
enclosingRange: Range<Index>, inout Bool
) -> ()
) {
_ns.enumerateSubstrings(in: _toNSRange(range), options: opts) {
var stop_ = false
body(substring: $0,
substringRange: self._range($1),
enclosingRange: self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// Returns the fastest encoding to which the `String` may be
/// converted without loss of information.
public var fastestEncoding: NSStringEncoding {
return _ns.fastestEncoding
}
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.")
public var fileSystemRepresentation: [CChar] {
return _persistCString(_ns.fileSystemRepresentation)!
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(NSStringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes(
buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: NSStringEncoding,
options: NSStringEncodingConversionOptions = [],
range: Range<Index>,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding,
options: options,
range: _toNSRange(range),
remaining: $0)
}
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
buffer: inout [CChar], maxLength: Int, encoding: NSStringEncoding
) -> Bool {
return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength),
encoding: encoding)
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.")
public func getFileSystemRepresentation(
buffer: inout [CChar], maxLength: Int) -> Bool {
return _ns.getFileSystemRepresentation(
&buffer, maxLength: min(buffer.count, maxLength))
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Produces an initialized `NSString` object equivalent to the given
/// `bytes` interpreted in the given `encoding`.
public init? <
S: Sequence where S.Iterator.Element == UInt8
>(
bytes: S, encoding: NSStringEncoding
) {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Produces an initialized `String` object that contains a
/// given number of bytes from a given buffer of bytes interpreted
/// in a given encoding, and optionally frees the buffer. WARNING:
/// this initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int,
encoding: NSStringEncoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding,
freeWhenDone: flag) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Returns an initialized `String` object that contains a
/// given number of characters from a given array of Unicode
/// characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = NSString(characters: utf16CodeUnits, length: count) as String
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Returns an initialized `String` object that contains a given
/// number of characters from a given array of UTF-16 Code Units
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = NSString(
charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag) as String
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: NSStringEncoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc)
self = ns as String
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: UnsafeMutablePointer<NSStringEncoding> = nil
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: usedEncoding)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: NSURL,
encoding enc: NSStringEncoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: NSURL,
usedEncoding enc: UnsafeMutablePointer<NSStringEncoding> = nil
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: enc)
self = ns as String
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: NSStringEncoding
) {
if let ns = NSString(cString: cString, encoding: enc) {
self = ns as String
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: NSData, encoding: NSStringEncoding) {
guard let s = NSString(data: data, encoding: encoding) else { return nil }
self = s as String
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: NSLocale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: NSLocale?, arguments: [CVarArg]) {
_precondition(
_countFormatSpecifiers(format) <= arguments.count,
"Too many format specifiers (%<letter>) provided for the argument list"
)
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message="Use lastPathComponent on NSURL instead.")
public var lastPathComponent: String {
return _ns.lastPathComponent
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message="Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
return _ns.length
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
@warn_unused_result
public func lengthOfBytes(usingEncoding encoding: NSStringEncoding) -> Int {
return _ns.lengthOfBytes(usingEncoding: encoding)
}
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
@warn_unused_result
public func lineRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.lineRange(for: _toNSRange(aRange)))
}
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(NSLinguisticTaggerOptions)opts
// orthography:(NSOrthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
@warn_unused_result
public func linguisticTags(
in range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]> = nil // FIXME:Can this be nil?
) -> [String] {
var nsTokenRanges: NSArray? = nil
let result = tokenRanges._withBridgeObject(&nsTokenRanges) {
self._ns.linguisticTags(
in: _toNSRange(range), scheme: tagScheme, options: opts,
orthography: orthography != nil ? orthography! : nil, tokenRanges: $0) as NSArray
}
if nsTokenRanges != nil {
tokenRanges._setIfNonNil {
(nsTokenRanges! as [AnyObject]).map {
self._range($0.rangeValue)
}
}
}
return _convertNSArrayToArray(result)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and a given string using a
/// case-insensitive, localized, comparison.
@warn_unused_result
public
func localizedCaseInsensitiveCompare(aString: String) -> NSComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and a given string using a localized
/// comparison.
@warn_unused_result
public func localizedCompare(aString: String) -> NSComparisonResult {
return _ns.localizedCompare(aString)
}
/// Compares strings as sorted by the Finder.
@warn_unused_result
public func localizedStandardCompare(string: String) -> NSComparisonResult {
return _ns.localizedStandardCompare(string)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(NSLocale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
@warn_unused_result
public func lowercaseString(with locale: NSLocale?) -> String {
return _ns.lowercaseString(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
@warn_unused_result
public
func maximumLengthOfBytes(usingEncoding encoding: NSStringEncoding) -> Int {
return _ns.maximumLengthOfBytes(usingEncoding: encoding)
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
@warn_unused_result
public func paragraphRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.paragraphRange(for: _toNSRange(aRange)))
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message="Use pathComponents on NSURL instead.")
public var pathComponents: [String] {
return _ns.pathComponents
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message="Use pathExtension on NSURL instead.")
public var pathExtension: String {
return _ns.pathExtension
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
@warn_unused_result
public func propertyList() -> AnyObject {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
@warn_unused_result
public
func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]
}
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(NSStringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(NSStringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
@warn_unused_result
public func rangeOfCharacter(
from aSet: NSCharacterSet,
options mask:NSStringCompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet, options: mask,
range: _toNSRange(aRange ?? self.characters.indices)))
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
@warn_unused_result
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex._utf16Index))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
@warn_unused_result
public func rangeOfComposedCharacterSequences(
for range: Range<Index>
) -> Range<Index> {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(for: _toNSRange(range)))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(NSStringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(NSStringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(NSLocale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
@warn_unused_result
public func range(
of aString: String,
options mask: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: NSLocale? = nil
) -> Range<Index>? {
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toNSRange(searchRange ?? self.characters.indices),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns `true` if `self` contains `string`, taking the current locale
/// into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContains(string: String) -> Bool {
return _ns.localizedStandardContains(string)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRange(of string: String) -> Range<Index>? {
return _optionalRange(_ns.localizedStandardRange(of: string))
}
// @property NSStringEncoding smallestEncoding;
/// Returns the smallest encoding to which the `String` can
/// be converted without loss of information.
public var smallestEncoding: NSStringEncoding {
return _ns.smallestEncoding
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message="Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
return _ns.abbreviatingWithTildeInPath
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string made from the `String` by replacing
/// all characters not in the specified set with percent encoded
/// characters.
@warn_unused_result
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: NSCharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(*, deprecated, message="Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
usingEncoding encoding: NSStringEncoding
) -> String? {
return _ns.addingPercentEscapes(usingEncoding: encoding)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string made by appending to the `String` a
/// string constructed from a given format string and the following
/// arguments.
@warn_unused_result
public func stringByAppendingFormat(
format: String, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format, arguments: arguments))
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message="Use appendingPathComponent on NSURL instead.")
public func appendingPathComponent(aString: String) -> String {
return _ns.appendingPathComponent(aString)
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message="Use appendingPathExtension on NSURL instead.")
public func appendingPathExtension(ext: String) -> String? {
// FIXME: This method can return nil in practice, for example when self is
// an empty string. OTOH, this is not documented, documentation says that
// it always returns a string.
//
// <rdar://problem/17902469> -[NSString stringByAppendingPathExtension] can
// return nil
return _ns.appendingPathExtension(ext)
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string made by appending a given string to
/// the `String`.
@warn_unused_result
public func appending(aString: String) -> String {
return _ns.appending(aString)
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message="Use deletingLastPathComponent on NSURL instead.")
public var deletingLastPathComponent: String {
return _ns.deletingLastPathComponent
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message="Use deletingPathExtension on NSURL instead.")
public var deletingPathExtension: String {
return _ns.deletingPathExtension
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message="Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
return _ns.expandingTildeInPath
}
// - (NSString *)
// stringByFoldingWithOptions:(NSStringCompareOptions)options
// locale:(NSLocale *)locale
/// Returns a string with the given character folding options
/// applied.
@warn_unused_result
public func folding(
options: NSStringCompareOptions = [], locale: NSLocale?
) -> String {
return _ns.folding(options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
@warn_unused_result
public func padding(
toLength newLength: Int,
with padString: String,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength, with: padString, startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// Returns a new string made from the `String` by replacing
/// all percent encoded sequences with the matching UTF-8
/// characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
@warn_unused_result
public func replacingCharacters(
in range: Range<Index>, with replacement: String
) -> String {
return _ns.replacingCharacters(in: _toNSRange(range), with: replacement)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(NSStringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the `String` are replaced by
/// another given string.
@warn_unused_result
public func replacingOccurrences(
of target: String,
with replacement: String,
options: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toNSRange(searchRange ?? self.characters.indices)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(*, deprecated, message="Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
usingEncoding encoding: NSStringEncoding
) -> String? {
return _ns.replacingPercentEscapes(usingEncoding: encoding)
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message="Use resolvingSymlinksInPath on NSURL instead.")
public var resolvingSymlinksInPath: String {
return _ns.resolvingSymlinksInPath
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message="Use standardizingPath on NSURL instead.")
public var standardizingPath: String {
return _ns.standardizingPath
}
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
@warn_unused_result
public func trimmingCharacters(in set: NSCharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message="Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("This function is not available")
}
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@warn_unused_result
public func substring(from index: Index) -> String {
return _ns.substring(from: index._utf16Index)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@warn_unused_result
public func substring(to index: Index) -> String {
return _ns.substring(to: index._utf16Index)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@warn_unused_result
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toNSRange(aRange))
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(NSLocale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
@warn_unused_result
public func uppercaseString(with locale: NSLocale?) -> String {
return _ns.uppercaseString(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write(
toFile path: String, atomically useAuxiliaryFile:Bool,
encoding enc: NSStringEncoding
) throws {
try self._ns.write(
toFile: path, atomically: useAuxiliaryFile, encoding: enc)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: NSURL, atomically useAuxiliaryFile: Bool,
encoding enc: NSStringEncoding
) throws {
try self._ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
/// Perform string transliteration.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func applyingTransform(
transform: String, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
@warn_unused_result
public func contains(other: String) -> Bool {
let r = self.range(of: other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.contains(other))
}
return r
}
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-insensitive, non-literal search, taking into
/// account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs,
/// can be achieved by calling
/// `rangeOfString(_:options:_,range:_locale:_)`.
///
/// Equivalent to
///
/// self.rangeOf(
/// other, options: .CaseInsensitiveSearch,
/// locale: NSLocale.current()) != nil
@warn_unused_result
public func localizedCaseInsensitiveContains(other: String) -> Bool {
let r = self.range(
of: other, options: .caseInsensitiveSearch, locale: NSLocale.current()
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.localizedCaseInsensitiveContains(other))
}
return r
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed="localizedName(ofStringEncoding:)")
public static func localizedNameOfStringEncoding(
encoding: NSStringEncoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="Use fileURL(withPathComponents:) on NSURL instead.")
public static func pathWithComponents(components: [String]) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="canBeConverted(toEncoding:)")
public func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="capitalizedString(with:)")
public func capitalizedStringWith(locale: NSLocale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="commonPrefix(with:options:)")
public func commonPrefixWith(
aString: String, options: NSStringCompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
outputName: UnsafeMutablePointer<String> = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]> = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="componentsSeparatedByCharacters(in:)")
public func componentsSeparatedByCharactersIn(
separator: NSCharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="componentsSeparated(by:)")
public func componentsSeparatedBy(separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="cString(usingEncoding:)")
public func cStringUsingEncoding(encoding: NSStringEncoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
encoding: NSStringEncoding,
allowLossyConversion: Bool = false
) -> NSData? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> ()
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
range: Range<Index>,
options opts:NSStringEnumerationOptions = [],
_ body: (
substring: String?, substringRange: Range<Index>,
enclosingRange: Range<Index>, inout Bool
) -> ()
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: NSStringEncoding,
options: NSStringEncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="lengthOfBytes(usingEncoding:)")
public func lengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="lineRange(for:)")
public func lineRangeFor(aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]> = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="lowercaseString(with:)")
public func lowercaseStringWith(locale: NSLocale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="maximumLengthOfBytes(usingEncoding:)")
public
func maximumLengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="paragraphRange(for:)")
public func paragraphRangeFor(aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
aSet: NSCharacterSet,
options mask:NSStringCompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="range(of:options:range:locale:)")
public func rangeOf(
aString: String,
options mask: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: NSLocale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="localizedStandardRange(of:)")
public func localizedStandardRangeOf(string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="addingPercentEncoding(withAllowedCharacters:")
public func addingPercentEncodingWithAllowedCharacters(
allowedCharacters: NSCharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="addingPercentEscapes(usingEncoding:)")
public func addingPercentEscapesUsingEncoding(
encoding: NSStringEncoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="stringByAppendingFormat")
public func appendingFormat(
format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="folding(_:locale:)")
public func folding(
options options: NSStringCompareOptions = [], locale: NSLocale?
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="padding(toLength:with:startingAt:)")
public func byPaddingToLength(
newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="replacingCharacters(in:with:)")
public func replacingCharactersIn(
range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
target: String,
withString replacement: String,
options: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
encoding: NSStringEncoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="trimmingCharacters(in:)")
public func byTrimmingCharactersIn(set: NSCharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="strings(byAppendingPaths:)")
public func stringsByAppendingPaths(paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="substring(from:)")
public func substringFrom(index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="substring(to:)")
public func substringTo(index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="substring(with:)")
public func substringWith(aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="uppercaseString(with:)")
public func uppercaseStringWith(locale: NSLocale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="write(toFile:atomically:encoding:)")
public func writeToFile(
path: String, atomically useAuxiliaryFile:Bool,
encoding enc: NSStringEncoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="write(to:atomically:encoding:)")
public func writeToURL(
url: NSURL, atomically useAuxiliaryFile: Bool,
encoding enc: NSStringEncoding
) throws {
fatalError("unavailable function can't be called")
}
}
| 335834c659af2c888a76e85c26d3df03 | 33.657431 | 302 | 0.680369 | false | false | false | false |
ggu/2D-RPG-Boilerplate | refs/heads/master | Borba/UI/SKButton.swift | mit | 2 | //
// SKButton.swift
// Borba
//
// Created by Gabriel Uribe on 6/5/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
import SpriteKit
protocol SKButtonDelegate {
func buttonTapped(type: SKButton.Tag)
}
class SKButton : SKSpriteNode {
enum Tag {// need to make MainMenu a type of ButtonType
case mainMenuPlay
case mainMenuSettings
}
static let padding: CGFloat = 50
private var button: SKButtonContents
var tag: Tag
var delegate: SKButtonDelegate?
init(color: UIColor, text: String, tag: SKButton.Tag) {
self.tag = tag
self.button = SKButtonContents(color: color, text: text)
let buttonWidth = self.button.frame.size.width + SKButton.padding
let buttonHeight = self.button.frame.size.height + SKButton.padding
super.init(texture: nil, color: UIColor.clearColor(), size: CGSize(width: buttonWidth, height: buttonHeight))
setup()
}
private func setup() {
userInteractionEnabled = true
addChild(button)
}
private func setMargins(horizontal: Int, vertical: Int) {
}
func changeText(text: String) {
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
delegate?.buttonTapped(tag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 0c66270e8032278335e904d74e8a37fc | 22.327586 | 113 | 0.686622 | false | false | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemReciprocal.swift | mit | 1 | import UIKit
class MCalculatorFunctionsItemReciprocal:MCalculatorFunctionsItem
{
private let kExponent:Double = -1
init()
{
let icon:UIImage = #imageLiteral(resourceName: "assetFunctionReciprocal")
let title:String = NSLocalizedString("MCalculatorFunctionsItemReciprocal_title", comment:"")
super.init(
icon:icon,
title:title)
}
override func processFunction(
currentValue:Double,
currentString:String,
modelKeyboard:MKeyboard,
view:UITextView)
{
let inversedValue:Double = pow(currentValue, kExponent)
let inversedString:String = modelKeyboard.numberAsString(scalar:inversedValue)
let descr:String = "reciprocal (\(currentString)) = \(inversedString)"
applyUpdate(
modelKeyboard:modelKeyboard,
view:view,
newEditing:inversedString,
descr:descr)
}
}
| 1b4cbb56f92fadbbcc4c9ecb88acc45c | 28.30303 | 100 | 0.634953 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/Evolution/Inputs/protocol_add_requirements.swift | apache-2.0 | 40 |
public func getVersion() -> Int {
#if BEFORE
return 0
#else
return 1
#endif
}
public protocol ElementProtocol : Equatable {
func increment() -> Self
}
public protocol AddMethodsProtocol {
associatedtype Element : ElementProtocol
func importantOperation() -> Element
func unimportantOperation() -> Element
#if AFTER
func uselessOperation() -> Element
#endif
}
extension AddMethodsProtocol {
public func unimportantOperation() -> Element {
return importantOperation().increment()
}
#if AFTER
public func uselessOperation() -> Element {
return unimportantOperation().increment()
}
#endif
}
public func doSomething<T : AddMethodsProtocol>(_ t: T) -> [T.Element] {
#if BEFORE
return [
t.importantOperation(),
t.unimportantOperation(),
t.unimportantOperation().increment(),
]
#else
return [
t.importantOperation(),
t.unimportantOperation(),
t.uselessOperation(),
]
#endif
}
public protocol AddConstructorsProtocol {
init(name: String)
#if AFTER
init?(nickname: String)
#endif
}
extension AddConstructorsProtocol {
public init?(nickname: String) {
if nickname == "" {
return nil
}
self.init(name: nickname + "ster")
}
}
public func testConstructorProtocol<T : AddConstructorsProtocol>(_ t: T.Type) -> [T?] {
#if BEFORE
return [t.init(name: "Puff")]
#else
return [t.init(name: "Meow meow"),
t.init(nickname: ""),
t.init(nickname: "Robster the Lob")]
#endif
}
public protocol AddPropertiesProtocol {
var topSpeed: Int { get nonmutating set }
var maxRPM: Int { get set }
#if AFTER
var maxSafeSpeed: Int { get set }
var minSafeSpeed: Int { get nonmutating set }
var redLine: Int { mutating get set }
#endif
}
extension AddPropertiesProtocol {
#if AFTER
public var maxSafeSpeed: Int {
get {
return topSpeed / 2
}
set {
topSpeed = newValue * 2
}
}
public var minSafeSpeed: Int {
get {
return topSpeed / 4
}
nonmutating set {
topSpeed = newValue * 4
}
}
public var redLine: Int {
get {
return maxRPM - 2000
}
set {
maxRPM = newValue + 2000
}
}
#endif
}
public func getProperties<T : AddPropertiesProtocol>(_ t: inout T) -> [Int] {
#if BEFORE
return [t.topSpeed, t.maxRPM]
#else
return [t.topSpeed, t.maxRPM, t.maxSafeSpeed, t.minSafeSpeed, t.redLine]
#endif
}
func increment(_ x: inout Int, by: Int) {
x += by
}
public func setProperties<T : AddPropertiesProtocol>(_ t: inout T) {
#if AFTER
t.minSafeSpeed = t.maxSafeSpeed
increment(&t.redLine, by: 7000)
#else
increment(&t.topSpeed, by: t.topSpeed)
increment(&t.maxRPM, by: 7000)
#endif
}
public protocol AddSubscriptProtocol {
associatedtype Key
associatedtype Value
func get(key key: Key) -> Value
mutating func set(key key: Key, value: Value)
#if AFTER
subscript(key: Key) -> Value { get set }
#endif
}
extension AddSubscriptProtocol {
public subscript(key: Key) -> Value {
get {
return get(key: key)
}
set {
set(key: key, value: newValue)
}
}
}
public func doSomething<T : AddSubscriptProtocol>(_ t: inout T, k1: T.Key, k2: T.Key) {
#if BEFORE
t.set(key: k1, value: t.get(key: k2))
#else
t[k1] = t[k2]
#endif
}
| 727805c572910c4521d7d1d6003d93de | 17.480226 | 87 | 0.652706 | false | false | false | false |
SeriousChoice/SCSwift | refs/heads/master | Example/scswift-example/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// SCSwift
//
// Created by Nicola Innocenti on 08/01/2022.
// Copyright © 2022 Nicola Innocenti. All rights reserved.
//
import UIKit
import SCSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if #available(iOS 15, *) {
let navAppearance = UINavigationBarAppearance()
navAppearance.backgroundColor = .white
UINavigationBar.appearance().standardAppearance = navAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navAppearance
} else {
UINavigationBar.appearance().isTranslucent = false
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: ViewController())
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| f3faaaadba96599219c37eceb7d79559 | 45.457627 | 285 | 0.729296 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/compiler_crashers_fixed/00140-swift-nominaltypedecl-computetype.swift | apache-2.0 | 65 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
| d1f9e1eb8c7e7644c6e8b8185d40b75b | 16.777778 | 79 | 0.54375 | false | false | false | false |
regnerjr/Microfiche | refs/heads/master | MicroficheTests/MicroficheTests.swift | mit | 1 | import UIKit
import XCTest
import Microfiche
/// Person Struct will be an example Immutable Data Structure we want to archive
struct Person {
let name: String
let age: Int
}
private struct Archive {
static var path: String? {
let documentsDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]
let documentDirectory = documentsDirectories?.first
if let dir = documentDirectory {
let documentPath = dir + "/items.archive"
return documentPath
}
return nil
}
}
// Person needs to be equatable in order to be used in a Set
extension Person: Equatable {}
func ==(rhs: Person, lhs: Person) -> Bool{
return (rhs.name == lhs.name) && (rhs.age == lhs.age)
}
// Person Must be hashable to be used in a set
extension Person : Hashable {
var hashValue: Int {
return self.name.hashValue
}
}
class microficheTests: XCTestCase {
func testArrayArchiveAndRestore() {
// Create and Array for archiving
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let people = [me, shelby]
// Archive the Collection, In this case an Array<People>
let arrayArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(people))
// Restore the data from the archive, Note the required cast to NSMutableArray
let arayUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(arrayArchive) as? NSMutableArray
// Finally take the Restored NSMutableArray, and convert it back to our preferred Data type
// NOTE: The cast is required! Without this the Type Inference Engine will not know what type
// of object should be returned to you
let restoredArray = restoreFromArchiveArray(arayUnarchive!) as Array<Person>
XCTAssert(restoredArray == people, "Restored Array is equal to the Source Data")
}
func testDictionaryArchiveAndRestore(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let dictionaryPeeps: Dictionary<NSUUID, Person> = [NSUUID(): me, NSUUID(): shelby]
let dictionaryArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(dictionaryPeeps))
let dictionaryUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(dictionaryArchive) as? NSMutableArray
let restoredDictionary = restoreFromArchiveArray(dictionaryUnarchive!) as Dictionary<NSUUID, Person>
XCTAssert(restoredDictionary == dictionaryPeeps, "Restored Dictionary is equal to the Source Data")
}
func testSetArchiveAndRestore(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let setPeeps: Set<Person> = [me, shelby]
let setArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(setPeeps))
let setUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(setArchive) as? NSMutableArray
let restoredSet = restoreFromArchiveArray(setUnarchive!) as Set<Person>
XCTAssert(restoredSet == setPeeps, "Restored Set is equal to the Source Data")
}
func testArchiveCollectionAtPath_Array(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let people = [me, shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(people, atPath: path)
XCTAssert(result == true, "Collection people was sucessfully archived")
let collection: Array<Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == people, "Collection People was successfully restored")
}
}
func testRestoreFromPathWhereNoDataHasBeenSaved_Array(){
let collection: Array<Person>? = restoreCollectionFromPath("someInvalidPath")
XCTAssert(collection == nil, "restoringCollectionfromPath returns nil")
}
func testArchiveCollectionAtPath_Dictionary(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let peopleDict = [NSUUID(): me, NSUUID():shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(peopleDict, atPath: path)
XCTAssert(result == true, "Collection people was sucessfully archived")
let collection: Dictionary<NSUUID,Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == peopleDict, "Collection People was successfully restored")
}
}
func testRestoreFromPathWhereNoDataHasBeenSaved_Dictionary(){
let collection: Dictionary<NSUUID,Person>? = restoreCollectionFromPath("someInvalidPath")
XCTAssert(collection == nil, "restoringCollectionfromPath returns nil")
}
func testArchiveCollectionAtPath_Set(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let setPeeps: Set<Person> = [me, shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(setPeeps, atPath: path)
XCTAssert(result == true, "Collection setPeeps was sucessfully archived")
let collection: Set<Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == setPeeps, "Collection setPeeps was successfully restored")
}
}
}
| ec82cb0ac52af74c576c72c67c5f09f8 | 39.6 | 169 | 0.681386 | false | true | false | false |
juzooda/gift4 | refs/heads/master | ios/Gift4/Gift4/Model/ProductsModel.swift | artistic-2.0 | 1 | //
// ProductsModel.swift
// Gift4
//
// Created by Rafael Juzo G Oda on 4/11/15.
// Copyright (c) 2015 Rafael Juzo Gomes Oda. All rights reserved.
//
import Foundation
class ProducsModel
{
func listAllCategories() -> Array<Category>
{
var categories = [Category]()
if let jsonData = openJSON("Categories", extn: "json") {
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let productCategories = jsonObject["product_categories"] as? NSArray{
for categoryInList in productCategories{
var category = Category()
let count = categoryInList["count"] as? Int
let name = categoryInList["name"] as? String
let slug = categoryInList["slug"] as? String
println("Hello, \(category)!")
}
}
}
return categories
}
func openJSON(fileName: String, extn: String) -> NSData?{
if let fileURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: extn) {
if let data = NSData(contentsOfURL: fileURL) {
return data
}
}
return nil
}
} | d57027d9a6d1fa54b980b0ca670e10fd | 28.408163 | 151 | 0.527778 | false | false | false | false |
jonandersen/calendar | refs/heads/master | Calendar/Sources/CalendarDateCell.swift | mit | 1 | //
// CalendarDateCell.swift
// leapsecond
//
// Created by Jon Andersen on 1/10/16.
// Copyright © 2016 Andersen. All rights reserved.
//
import Foundation
public class CalendarDateCell: UICollectionViewCell {
static let identifier: String = "CalendarDateCell"
@IBOutlet public weak var textLabel: UILabel!
@IBOutlet public weak var circleView: UIView!
@IBOutlet public weak var imageView: UIImageView!
private let circleRatio: CGFloat = 1.0
var calendarDate: CalendarDate = CalendarDate.empty()
public override func awakeFromNib() {
circleView.backgroundColor = UIColor(red: 0x33/256, green: 0xB3/256, blue: 0xB3/256, alpha: 0.5)
self.clipsToBounds = true
imageView.clipsToBounds = true
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.circleView.hidden = true
self.imageView.hidden = true
self.textLabel.textColor = UIColor.darkTextColor()
}
public override func layoutSubviews() {
super.layoutSubviews()
CATransaction.begin()
var sizeCircle = min(self.frame.size.width, self.frame.size.height)
sizeCircle = sizeCircle * circleRatio
sizeCircle = CGFloat(roundf(Float(sizeCircle)))
circleView.frame = CGRect(x: 0, y: 0, width: sizeCircle, height: sizeCircle)
circleView.center = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2.0)
circleView.layer.cornerRadius = sizeCircle / 2.0
imageView.frame = self.circleView.frame
imageView.layer.cornerRadius = self.circleView.layer.cornerRadius
CATransaction.commit()
}
}
| 34d680dd4907305177829800f007c8ba | 38.232558 | 104 | 0.691168 | false | false | false | false |
Yalantis/AppearanceNavigationController | refs/heads/develop | AppearanceNavigationController/NavigationController/Appearance.swift | mit | 1 |
import Foundation
import UIKit
public struct Appearance: Equatable {
public struct Bar: Equatable {
var style: UIBarStyle = .default
var backgroundColor = UIColor(red: 234 / 255, green: 46 / 255, blue: 73 / 255, alpha: 1)
var tintColor = UIColor.white
var barTintColor: UIColor?
}
var statusBarStyle: UIStatusBarStyle = .default
var navigationBar = Bar()
var toolbar = Bar()
}
public func ==(lhs: Appearance.Bar, rhs: Appearance.Bar) -> Bool {
return lhs.style == rhs.style &&
lhs.backgroundColor == rhs.backgroundColor &&
lhs.tintColor == rhs.tintColor &&
rhs.barTintColor == lhs.barTintColor
}
public func ==(lhs: Appearance, rhs: Appearance) -> Bool {
return lhs.statusBarStyle == rhs.statusBarStyle && lhs.navigationBar == rhs.navigationBar && lhs.toolbar == rhs.toolbar
}
| 1bd75178bb4239f6586b27c5c52af581 | 29.482759 | 123 | 0.649321 | false | false | false | false |
trungphamduc/Calendar | refs/heads/master | Example/AAA/CalendarLogic.swift | mit | 2 | //
// CalLogic.swift
// CalendarLogic
//
// Created by Lancy on 01/06/15.
// Copyright (c) 2015 Lancy. All rights reserved.
//
import Foundation
class CalendarLogic: Hashable {
var hashValue: Int {
return baseDate.hashValue
}
// Mark: Public variables and methods.
var baseDate: NSDate {
didSet {
calculateVisibleDays()
}
}
private lazy var dateFormatter = NSDateFormatter()
var currentMonthAndYear: NSString {
dateFormatter.dateFormat = calendarSettings.monthYearFormat
return dateFormatter.stringFromDate(baseDate)
}
var currentMonthDays: [Date]?
var previousMonthVisibleDays: [Date]?
var nextMonthVisibleDays: [Date]?
init(date: NSDate) {
baseDate = date.firstDayOfTheMonth
calculateVisibleDays()
}
func retreatToPreviousMonth() {
baseDate = baseDate.firstDayOfPreviousMonth
}
func advanceToNextMonth() {
baseDate = baseDate.firstDayOfFollowingMonth
}
func moveToMonth(date: NSDate) {
baseDate = date
}
func isVisible(date: NSDate) -> Bool {
let internalDate = Date(date: date)
if contains(currentMonthDays!, internalDate) {
return true
} else if contains(previousMonthVisibleDays!, internalDate) {
return true
} else if contains(nextMonthVisibleDays!, internalDate) {
return true
}
return false
}
func containsDate(date: NSDate) -> Bool {
let date = Date(date: date)
let logicBaseDate = Date(date: baseDate)
if (date.month == logicBaseDate.month) &&
(date.year == logicBaseDate.year) {
return true
}
return false
}
//Mark: Private methods.
private var numberOfDaysInPreviousPartialWeek: Int {
return baseDate.weekDay - 1
}
private var numberOfVisibleDaysforFollowingMonth: Int {
// Traverse to the last day of the month.
let parts = baseDate.monthDayAndYearComponents
parts.day = baseDate.numberOfDaysInMonth
let date = NSCalendar.currentCalendar().dateFromComponents(parts)
// 7*6 = 42 :- 7 columns (7 days in a week) and 6 rows (max 6 weeks in a month)
return 42 - (numberOfDaysInPreviousPartialWeek + baseDate.numberOfDaysInMonth)
}
private var calculateCurrentMonthVisibleDays: [Date] {
var dates = [Date]()
let numberOfDaysInMonth = baseDate.numberOfDaysInMonth
let component = baseDate.monthDayAndYearComponents
for var i = 1; i <= numberOfDaysInMonth; i++ {
dates.append(Date(day: i, month: component.month, year: component.year))
}
return dates
}
private var calculatePreviousMonthVisibleDays: [Date] {
var dates = [Date]()
let date = baseDate.firstDayOfPreviousMonth
let numberOfDaysInMonth = date.numberOfDaysInMonth
let numberOfVisibleDays = numberOfDaysInPreviousPartialWeek
let parts = date.monthDayAndYearComponents
for var i = numberOfDaysInMonth - (numberOfVisibleDays - 1); i <= numberOfDaysInMonth; i++ {
dates.append(Date(day: i, month: parts.month, year: parts.year))
}
return dates
}
private var calculateFollowingMonthVisibleDays: [Date] {
var dates = [Date]()
let date = baseDate.firstDayOfFollowingMonth
let numberOfDays = numberOfVisibleDaysforFollowingMonth
let parts = date.monthDayAndYearComponents
for var i = 1; i <= numberOfVisibleDaysforFollowingMonth; i++ {
dates.append(Date(day: i, month: parts.month, year: parts.year))
}
return dates
}
private func calculateVisibleDays() {
currentMonthDays = calculateCurrentMonthVisibleDays
previousMonthVisibleDays = calculatePreviousMonthVisibleDays
nextMonthVisibleDays = calculateFollowingMonthVisibleDays
}
}
func ==(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func <(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return (lhs.baseDate.compare(rhs.baseDate) == .OrderedAscending)
}
func >(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return (lhs.baseDate.compare(rhs.baseDate) == .OrderedDescending)
}
| 6683d2407df09c0f7b7e818bd7129b8f | 26.789116 | 96 | 0.697674 | false | false | false | false |
joshuajharris/dotfiles | refs/heads/master | Alfred.alfredpreferences/workflows/user.workflow.7CC242B6-984A-48B5-8B68-DA9C29C0EC44/imgpbcopy.swift | mit | 1 | // Ported from http://www.alecjacobson.com/weblog/?p=3816
import Foundation
import Cocoa
let args = CommandLine.arguments
let path = args[1]
let image = NSImage(contentsOfFile: path)!
let pasteboard = NSPasteboard.general()
pasteboard.clearContents()
pasteboard.writeObjects([image])
| f890bbeab6218edb1436ad3880ba80c3 | 22.916667 | 57 | 0.780488 | false | false | false | false |
fthomasmorel/insapp-iOS | refs/heads/master | Insapp/SeeMoreViewController.swift | mit | 1 | //
// SeeMoreViewController.swift
// Insapp
//
// Created by Guillaume Courtet on 21/12/2016.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import UIKit
class SeeMoreViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var resultLabel: UILabel!
var users: [User] = []
var events: [Event] = []
var posts: [Post] = []
var associations: [Association] = []
var associationTable: [String: Association] = [:]
var searchedText: String!
var type: Int!
var prt: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.resultLabel.text = searchedText!
self.tableView.register(UINib(nibName: "SearchUserCell", bundle: nil), forCellReuseIdentifier: kSearchUserCell)
self.tableView.register(UINib(nibName: "SearchEventCell", bundle: nil), forCellReuseIdentifier: kSearchEventCell)
self.tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: kPostCell)
self.tableView.register(UINib(nibName: "SearchPostCell", bundle: nil), forCellReuseIdentifier: kSearchPostCell)
self.tableView.register(UINib(nibName: "SearchAssociationCell", bundle: nil), forCellReuseIdentifier: kSearchAssociationCell)
self.tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (self.type) {
case 1:
return 1
case 2:
return 1
case 3:
return self.events.count
default:
return self.users.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (self.type) {
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchAssociationCell, for: indexPath) as! SearchAssociationCell
cell.parent = self.prt
cell.more = 1
cell.associations = self.associations
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchPostCell, for: indexPath) as! SearchPostCell
cell.more = 1
cell.parent = self.prt
cell.loadPosts(self.posts)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchEventCell, for: indexPath) as! SearchEventCell
let event = self.events[indexPath.row]
cell.load(event: event)
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchUserCell, for: indexPath) as! SearchUserCell
let user = self.users[indexPath.row]
cell.loadUser(user: user)
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch self.type {
case 1:
let test = self.associations.count%3 == 0 ? self.associations.count/3 : self.associations.count/3 + 1
let nb = CGFloat(test)
let res = self.tableView.frame.width/3 * nb
return res
case 2:
let test = self.posts.count%3 == 0 ? self.posts.count/3 : self.posts.count/3 + 1
let nb = CGFloat(test)
return self.tableView.frame.width/3 * nb
case 3:
return 70
default:
return 50
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch self.type {
case 1:
return
case 2:
return
case 3:
let event = self.events[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
vc.association = self.associationTable[event.association!]!
vc.event = event
self.prt.navigationController?.pushViewController(vc, animated: true)
default:
let user = self.users[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "UserViewController") as! UserViewController
vc.user_id = user.id
vc.setEditable(false)
vc.canReturn(true)
self.prt.navigationController?.pushViewController(vc, animated: true)
}
}
@IBAction func dismissAction(_ sender: AnyObject) {
self.navigationController!.popViewController(animated: true)
}
}
| 1a1cd8633681e2cd8114119f863f2572 | 37.42963 | 138 | 0.606207 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie | refs/heads/master | Example/Pods/HandyJSON/HandyJSON/HelpingMapper.swift | mit | 11 | /*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Created by zhouzhuo on 9/20/16.
//
import Foundation
public typealias CustomMappingKeyValueTuple = (Int, MappingPropertyHandler)
public class MappingPropertyHandler {
var mappingNames: [String]?
var assignmentClosure: ((Any?) -> ())?
var takeValueClosure: ((Any?) -> (Any?))?
public init(mappingNames: [String]?, assignmentClosure: ((Any?) -> ())?, takeValueClosure: ((Any?) -> (Any?))?) {
self.mappingNames = mappingNames
self.assignmentClosure = assignmentClosure
self.takeValueClosure = takeValueClosure
}
}
public class HelpingMapper {
private var mappingHandlers = [Int: MappingPropertyHandler]()
private var excludeProperties = [Int]()
internal func getMappingHandler(key: Int) -> MappingPropertyHandler? {
return self.mappingHandlers[key]
}
internal func propertyExcluded(key: Int) -> Bool {
return self.excludeProperties.contains(key)
}
public func specify<T>(property: inout T, name: String) {
self.specify(property: &property, name: name, converter: nil)
}
public func specify<T>(property: inout T, converter: @escaping (String) -> T) {
self.specify(property: &property, name: nil, converter: converter)
}
public func specify<T>(property: inout T, name: String?, converter: ((String) -> T)?) {
let pointer = withUnsafePointer(to: &property, { return $0 })
let key = pointer.hashValue
let names = (name == nil ? nil : [name!])
if let _converter = converter {
let assignmentClosure = { (jsonValue: Any?) in
if let _value = jsonValue{
if let object = _value as? NSObject{
if let str = String.transform(from: object){
UnsafeMutablePointer<T>(mutating: pointer).pointee = _converter(str)
}
}
}
}
self.mappingHandlers[key] = MappingPropertyHandler(mappingNames: names, assignmentClosure: assignmentClosure, takeValueClosure: nil)
} else {
self.mappingHandlers[key] = MappingPropertyHandler(mappingNames: names, assignmentClosure: nil, takeValueClosure: nil)
}
}
public func exclude<T>(property: inout T) {
self._exclude(property: &property)
}
fileprivate func addCustomMapping(key: Int, mappingInfo: MappingPropertyHandler) {
self.mappingHandlers[key] = mappingInfo
}
fileprivate func _exclude<T>(property: inout T) {
let pointer = withUnsafePointer(to: &property, { return $0 })
self.excludeProperties.append(pointer.hashValue)
}
}
infix operator <-- : LogicalConjunctionPrecedence
public func <-- <T>(property: inout T, name: String) -> CustomMappingKeyValueTuple {
return property <-- [name]
}
public func <-- <T>(property: inout T, names: [String]) -> CustomMappingKeyValueTuple {
let pointer = withUnsafePointer(to: &property, { return $0 })
let key = pointer.hashValue
return (key, MappingPropertyHandler(mappingNames: names, assignmentClosure: nil, takeValueClosure: nil))
}
// MARK: non-optional properties
public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: Transform) -> CustomMappingKeyValueTuple {
return property <-- (nil, transformer)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple {
let names = (transformer.0 == nil ? [] : [transformer.0!])
return property <-- (names, transformer.1)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple {
let pointer = withUnsafePointer(to: &property, { return $0 })
let key = pointer.hashValue
let assignmentClosure = { (jsonValue: Any?) in
if let value = transformer.1?.transformFromJSON(jsonValue) {
UnsafeMutablePointer<Transform.Object>(mutating: pointer).pointee = value
}
}
let takeValueClosure = { (objectValue: Any?) -> Any? in
if let _value = objectValue as? Transform.Object {
return transformer.1?.transformToJSON(_value) as Any
}
return nil
}
return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure))
}
// MARK: optional properties
public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: Transform) -> CustomMappingKeyValueTuple {
return property <-- (nil, transformer)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple {
let names = (transformer.0 == nil ? [] : [transformer.0!])
return property <-- (names, transformer.1)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple {
let pointer = withUnsafePointer(to: &property, { return $0 })
let key = pointer.hashValue
let assignmentClosure = { (jsonValue: Any?) in
if let value = transformer.1?.transformFromJSON(jsonValue) {
UnsafeMutablePointer<Transform.Object?>(mutating: pointer).pointee = value
}
}
let takeValueClosure = { (objectValue: Any?) -> Any? in
if let _value = objectValue as? Transform.Object {
return transformer.1?.transformToJSON(_value) as Any
}
return nil
}
return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure))
}
// MARK: implicitly unwrap optional properties
public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: Transform) -> CustomMappingKeyValueTuple {
return property <-- (nil, transformer)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple {
let names = (transformer.0 == nil ? [] : [transformer.0!])
return property <-- (names, transformer.1)
}
public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple {
let pointer = withUnsafePointer(to: &property, { return $0 })
let key = pointer.hashValue
let assignmentClosure = { (jsonValue: Any?) in
if let value = transformer.1?.transformFromJSON(jsonValue) {
UnsafeMutablePointer<Transform.Object!>(mutating: pointer).pointee = value
}
}
let takeValueClosure = { (objectValue: Any?) -> Any? in
if let _value = objectValue as? Transform.Object {
return transformer.1?.transformToJSON(_value) as Any
}
return nil
}
return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure))
}
infix operator <<< : AssignmentPrecedence
public func <<< (mapper: HelpingMapper, mapping: CustomMappingKeyValueTuple) {
mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1)
}
public func <<< (mapper: HelpingMapper, mappings: [CustomMappingKeyValueTuple]) {
mappings.forEach { (mapping) in
mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1)
}
}
infix operator >>> : AssignmentPrecedence
public func >>> <T> (mapper: HelpingMapper, property: inout T) {
mapper._exclude(property: &property)
}
| e7c147faddbdf9f31a8f871750f6c97c | 40.139303 | 146 | 0.675777 | false | false | false | false |
0x73/SwiftIconFont | refs/heads/master | SwiftIconFont/Classes/Shared/SwiftIconFont.swift | mit | 1 | //
// UIFont+SwiftIconFont.swift
// SwiftIconFont
//
// Created by Sedat Ciftci on 18/03/16.
// Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
public struct SwiftIcon {
let font: Fonts
let code: String
let color: Color
let imageSize: CGSize
let fontSize: CGFloat
}
public enum Fonts: String {
case fontAwesome5 = "FontAwesome5Free-Regular"
case fontAwesome5Brand = "FontAwesome5Brands-Regular"
case fontAwesome5Solid = "FontAwesome5Free-Solid"
case iconic = "open-iconic"
case ionicon = "Ionicons"
case octicon = "octicons"
case themify = "themify"
case mapIcon = "map-icons"
case materialIcon = "MaterialIcons-Regular"
case segoeMDL2 = "SegoeMDL2Assets"
case foundation = "fontcustom"
case elegantIcon = "ElegantIcons"
case captain = "captainicon"
var fontFamilyName: String {
switch self {
case .fontAwesome5:
return "Font Awesome 5 Free"
case .fontAwesome5Brand:
return "Font Awesome 5 Brands"
case .fontAwesome5Solid:
return "Font Awesome 5 Free"
case .iconic:
return "Icons"
case .ionicon:
return "Ionicons"
case .octicon:
return "octicons"
case .themify:
return "Themify"
case .mapIcon:
return "map-icons"
case .materialIcon:
return "Material Icons"
case .segoeMDL2:
return "Segoe MDL2 Assets"
case .foundation:
return "fontcustom"
case .elegantIcon:
return "ElegantIcons"
case .captain:
return "captainicon"
}
}
}
func replace(withText string: NSString) -> NSString {
if string.lowercased.range(of: "-") != nil {
return string.replacingOccurrences(of: "-", with: "_") as NSString
}
return string
}
func getAttributedString(_ text: NSString, ofSize size: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text as String)
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count < 2 {
continue
}
let substringRange = text.range(of: substring)
let fontPrefix: String = splitArr[0].lowercased()
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-")
}
var fontType: Fonts = .fontAwesome5
var fontArr: [String: String] = ["": ""]
if fontPrefix == "ic" {
fontType = Fonts.iconic
fontArr = iconicIconArr
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
fontArr = ioniconArr
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
fontArr = octiconArr
} else if fontPrefix == "ti" {
fontType = Fonts.themify
fontArr = temifyIconArr
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
fontArr = mapIconArr
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
fontArr = materialIconArr
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
fontArr = segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fo" {
fontType = .foundation
fontArr = foundationIconArr
} else if fontPrefix == "el" {
fontType = .elegantIcon
fontArr = elegantIconArr
} else if fontPrefix == "cp" {
fontType = .captain
fontArr = captainIconArr
}
if let _ = fontArr[fontCode] {
attributedString.replaceCharacters(in: substringRange, with: String.getIcon(from: fontType, code: fontCode)!)
let newRange = NSRange(location: substringRange.location, length: 1)
attributedString.addAttribute(.font, value: Font.icon(from: fontType, ofSize: size), range: newRange)
}
}
return attributedString
}
func getAttributedStringForRuntimeReplace(_ text: NSString, ofSize size: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text as String)
do {
let input = text as String
let regex = try NSRegularExpression(pattern: "icon:\\((\\w+):(\\w+)\\)", options: NSRegularExpression.Options.caseInsensitive)
let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
if let match = matches.first {
var fontPrefix = ""
var fontCode = ""
let iconLibraryNameRange = match.range(at: 1)
let iconNameRange = match.range(at: 2)
if let swiftRange = iconLibraryNameRange.range(for: text as String) {
fontPrefix = String(input[swiftRange])
}
if let swiftRange = iconNameRange.range(for: text as String) {
fontCode = String(input[swiftRange])
}
if fontPrefix.utf16.count > 0 && fontCode.utf16.count > 0 {
var fontType: Fonts = .fontAwesome5
var fontArr: [String: String] = ["": ""]
if fontPrefix == "ic" {
fontType = Fonts.iconic
fontArr = iconicIconArr
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
fontArr = ioniconArr
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
fontArr = octiconArr
} else if fontPrefix == "ti" {
fontType = Fonts.themify
fontArr = temifyIconArr
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
fontArr = mapIconArr
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
fontArr = materialIconArr
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
fontArr = segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fo" {
fontType = .foundation
fontArr = foundationIconArr
} else if fontPrefix == "el" {
fontType = .elegantIcon
fontArr = elegantIconArr
} else if fontPrefix == "cp" {
fontType = .captain
fontArr = captainIconArr
}
if let _ = fontArr[fontCode] {
attributedString.replaceCharacters(in: match.range, with: String.getIcon(from: fontType, code: fontCode)!)
let newRange = NSRange(location: match.range.location, length: 1)
attributedString.addAttribute(.font, value: Font.icon(from: fontType, ofSize: size), range: newRange)
}
}
}
} catch {
// regex was bad!
}
return attributedString
}
public func GetIconIndexWithSelectedIcon(_ icon: String) -> String {
let text = icon as NSString
var iconIndex: String = ""
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count == 1{
continue
}
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = fontCode.replacingOccurrences(of: "_", with: "-")
}
iconIndex = fontCode
}
return iconIndex
}
public func GetFontTypeWithSelectedIcon(_ icon: String) -> Fonts {
let text = icon as NSString
var fontType: Fonts = .fontAwesome5
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count == 1{
continue
}
let fontPrefix: String = splitArr[0].lowercased()
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-")
}
if fontPrefix == "ic" {
fontType = Fonts.iconic
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
} else if fontPrefix == "ti" {
fontType = Fonts.themify
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
} else if fontPrefix == "fo" {
fontType = .foundation
} else if fontPrefix == "el" {
fontType = .elegantIcon
} else if fontPrefix == "cp" {
fontType = .captain
}
}
return fontType
}
| dfe1b0208ce122344122fdd3b9920ef2 | 33.61859 | 134 | 0.533839 | false | false | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/AssistantV1/Models/LogMessageSource.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2021.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
An object that identifies the dialog element that generated the error message.
*/
public struct LogMessageSource: Codable, Equatable {
/**
A string that indicates the type of dialog element that generated the error message.
*/
public enum TypeEnum: String {
case dialogNode = "dialog_node"
}
/**
A string that indicates the type of dialog element that generated the error message.
*/
public var type: String?
/**
The unique identifier of the dialog node that generated the error message.
*/
public var dialogNode: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
case dialogNode = "dialog_node"
}
/**
Initialize a `LogMessageSource` with member variables.
- parameter type: A string that indicates the type of dialog element that generated the error message.
- parameter dialogNode: The unique identifier of the dialog node that generated the error message.
- returns: An initialized `LogMessageSource`.
*/
public init(
type: String? = nil,
dialogNode: String? = nil
)
{
self.type = type
self.dialogNode = dialogNode
}
}
| 46f572f5651b897586bc9e1d7619331b | 29.125 | 108 | 0.681535 | false | false | false | false |
yangligeryang/codepath | refs/heads/master | assignments/DropboxDemo/DropboxDemo/SignInFormViewController.swift | apache-2.0 | 1 | //
// SignInFormViewController.swift
// DropboxDemo
//
// Created by Yang Yang on 10/15/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class SignInFormViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var formImage: UIImageView!
let resetImage = UIImage(named: "sign_in")
let activeImage = UIImage(named: "sign_in1")
override func viewDidLoad() {
super.viewDidLoad()
emailField.delegate = self
emailField.becomeFirstResponder()
passwordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if emailField.isFirstResponder {
emailField.resignFirstResponder()
passwordField.becomeFirstResponder()
} else if passwordField.isFirstResponder {
let characterCount = passwordField.text?.characters.count
if characterCount! > 0 {
performSegue(withIdentifier: "existingAccount", sender: nil)
}
}
return false
}
@IBAction func onBack(_ sender: UIButton) {
navigationController!.popViewController(animated: true)
}
@IBAction func onCreate(_ sender: UIButton) {
performSegue(withIdentifier: "existingAccount", sender: nil)
}
@IBAction func didTap(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
@IBAction func onForgotPassword(_ sender: UIButton) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let forgotAction = UIAlertAction(title: "Forgot Password?", style: .default) { (action) in
}
alertController.addAction(forgotAction)
let ssoAction = UIAlertAction(title: "Single Sign-On", style: .default) { (action) in
}
alertController.addAction(ssoAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
}
alertController.addAction(cancelAction)
present(alertController, animated: true) {}
}
@IBAction func onPasswordChanged(_ sender: UITextField) {
let characterCount = passwordField.text?.characters.count
if characterCount! > 0 {
signInButton.isEnabled = true
formImage.image = activeImage
} else {
formImage.image = resetImage
signInButton.isEnabled = false
}
}
}
| accfaf1fc3deaba091e51aa940ab2d6d | 30.142857 | 103 | 0.634439 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | refs/heads/master | Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+CALayer.swift | mit | 1 | //
// Core+CALayer.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension CALayer {
func convertedToImage(
size: CGSize = .zero,
scale: CGFloat = UIScreen.main.scale
) -> UIImage? {
var toSize: CGSize
if size.equalTo(.zero) {
toSize = frame.size
}else {
toSize = size
}
UIGraphicsBeginImageContextWithOptions(toSize, false, scale)
let context = UIGraphicsGetCurrentContext()
render(in: context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 5304ea80f8d6daf93b362047d7a03e7e | 22.714286 | 68 | 0.60241 | false | false | false | false |
leizh007/HiPDA | refs/heads/master | HiPDA/HiPDA/Sections/Home/Post/Html/HtmlManager.swift | mit | 1 | //
// HtmlManager.swift
// HiPDA
//
// Created by leizh007 on 2017/5/18.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
struct HtmlManager {
fileprivate enum Attribute {
static let content = "####content here####"
static let style = "####style here####"
static let script = "####script here####"
static let maxWidth = "####max width####"
static let blockQuoteWidth = "####blockquote width####"
static let blockcodeWidth = "####blockcode width#### "
static let screenScale = "####screen scale####"
static let seperatorLineHeight = "####seperator line height####"
}
fileprivate static let baseHtml: String = {
enum HtmlResource {
static let name = "post"
enum ResourceType {
static let html = "html"
static let css = "css"
static let js = "js"
}
}
guard let htmlPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.html),
let cssPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.css),
let jsPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.js),
let html = try? String(contentsOfFile: htmlPath, encoding: .utf8),
var css = try? String(contentsOfFile: cssPath, encoding: .utf8),
let js = try? String(contentsOfFile: jsPath, encoding: .utf8) else {
fatalError("Load Html Error!")
}
let contentMargin = CGFloat(8.0)
let blockquoteMargin = CGFloat(16.0)
let seperatorLineHeight = 1.0 / C.UI.screenScale
css = css.replacingOccurrences(of: Attribute.maxWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin))px")
.replacingOccurrences(of: Attribute.blockQuoteWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin - 2 * blockquoteMargin))px")
.replacingOccurrences(of: Attribute.blockcodeWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin))px")
.replacingOccurrences(of: Attribute.screenScale, with: "\(Int(C.UI.screenScale))").replacingOccurrences(of: Attribute.seperatorLineHeight, with: String(format:"%.3f", seperatorLineHeight))
return html.replacingOccurrences(of: Attribute.style, with: css)
.replacingOccurrences(of: Attribute.script, with: js)
}()
static func html(with content: String) -> String {
return HtmlManager.baseHtml.replacingOccurrences(of: Attribute.content, with: content)
}
}
| 750431a4a32aa9701a253643bc4442e0 | 46.410714 | 200 | 0.626365 | false | false | false | false |
citysite102/kapi-kaffeine | refs/heads/master | kapi-kaffeine/NetworkRequest.swift | mit | 1 | //
// NetworkRequest.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/1.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import SwiftyJSON
public struct errorInformation {
let error: Error
let statusCode: Int?
let responseBody: KPErrorResponseModel?
let errorCode: String?
init(error: Error, data: Data?, urlResponse: HTTPURLResponse?) {
self.error = error
let json = String(data: data ?? Data(), encoding: String.Encoding.utf8)
responseBody = KPErrorResponseModel(JSONString:json!)
statusCode = urlResponse?.statusCode
errorCode = responseBody?.errorCode
}
}
public enum NetworkRequestError: Error {
case invalidData
case apiError(errorInformation: errorInformation)
case unknownError
case noNetworkConnection
case resultUnavailable
}
public typealias RawJsonResult = JSON
// MARK: Request
public protocol NetworkRequest {
associatedtype ResponseType
// Required
/// End Point.
/// e.g. /cards/:id/dislike
var endpoint: String { get }
/// Will transform given data to requested type of response.
var responseHandler: (Data) throws -> ResponseType { get }
// Optional
var baseURL: String { get }
/// Method to make the request. E.g. get, post.
var method: Alamofire.HTTPMethod { get }
/// Parameter encoding. E.g. JSON, URLEncoding.default.
var encoding: Alamofire.ParameterEncoding { get }
var parameters: [String : Any]? { get }
var headers: [String : String] { get }
/// Client that helps you to make reqeust.
var networkClient: NetworkClientType { get }
}
extension NetworkRequest {
public var url: String { return baseURL + endpoint}
// public var baseURL: String { return "https://kapi-v2-test.herokuapp.com/api/v2" }
public var baseURL: String { return "https://api.kapi.tw/api/v2" }
// public var baseURL: String { return "http://35.201.206.7/api/v2" }
public var method: Alamofire.HTTPMethod { return .get }
public var encoding: Alamofire.ParameterEncoding { return method == .get ?
URLEncoding.default :
JSONEncoding.default }
public var parameters: [String : AnyObject] { return [:] }
public var headers: [String : String] {
return ["token": (KPUserManager.sharedManager.currentUser?.accessToken) ?? ""]
}
public var networkClient: NetworkClientType { return NetworkClient() }
}
extension NetworkRequest where ResponseType: Mappable {
// 輸入 Data 型別,回傳 ResponseType
public var responseHandler: (Data) throws -> ResponseType { return jsonResponseHandler }
public var arrayResponseHandler: (Data) throws -> [ResponseType] { return jsonArrayResponseHandler }
private func jsonResponseHandler(_ data: Data) throws -> ResponseType {
let json = String(data: data, encoding: String.Encoding.utf8)
if let response = Mapper<ResponseType>().map(JSONString: json!) {
return response
} else {
throw NetworkRequestError.invalidData
}
}
private func jsonArrayResponseHandler(_ data: Data) throws -> [ResponseType] {
let json = String(data: data , encoding: String.Encoding.utf8)
if let responses = Mapper<ResponseType>().mapArray(JSONString: json!) {
return responses
} else {
throw NetworkRequestError.invalidData
}
}
}
extension NetworkRequest where ResponseType == RawJsonResult {
public var responseHandler: (Data) throws -> ResponseType {
return rawJsonResponseHandler
}
private func rawJsonResponseHandler(_ data: Data) throws -> ResponseType {
if let responseResult = JSON(data: data).dictionary?["result"] {
if responseResult.boolValue {
return JSON(data: data)
} else {
throw NetworkRequestError.resultUnavailable
}
}
return JSON(data: data)
}
}
// MARK: Upload Request
public protocol NetworkUploadRequest {
associatedtype ResponseType
var endpoint: String { get }
var responseHandler: (Data) throws -> ResponseType { get }
// Optional
var baseURL: String { get }
var method: Alamofire.HTTPMethod { get }
var threshold: UInt64 { get }
var parameters: [String : Any]? { get }
var headers: [String : String] { get }
var fileData: Data? { get }
var fileKey: String? { get }
var fileName: String? { get }
var mimeType: String? { get }
/// Client that helps you to make reqeust.
var networkClient: NetworkClientType { get }
}
extension NetworkUploadRequest {
public var url: String { return baseURL + endpoint}
// public var baseURL: String {return "https://kapi-v2-test.herokuapp.com/api/v2"}
public var baseURL: String { return "https://api.kapi.tw/api/v2" }
// public var baseURL: String { return "http://35.201.206.7/api/v2" }
public var method: Alamofire.HTTPMethod { return .post }
public var threshold: UInt64 { return 100_000_000 }
public var parameters: [String : AnyObject] { return [:] }
public var headers: [String : String] { return ["Content-Type":"multipart/form-data",
"User-Agent":"iReMW4K4fyWos"] }
public var networkClient: NetworkClientType { return NetworkClient() }
}
extension NetworkUploadRequest where ResponseType: Mappable {
// 輸入 Data 型別,回傳 ResponseType
public var responseHandler: (Data) throws -> ResponseType { return jsonResponseHandler }
public var arrayResponseHandler: (Data) throws -> [ResponseType] { return jsonArrayResponseHandler }
private func jsonResponseHandler(_ data: Data) throws -> ResponseType {
let json = String(data: data, encoding: String.Encoding.utf8)
if let response = Mapper<ResponseType>().map(JSONString: json!) {
return response
} else {
throw NetworkRequestError.invalidData
}
}
private func jsonArrayResponseHandler(_ data: Data) throws -> [ResponseType] {
let json = String(data: data , encoding: String.Encoding.utf8)
if let responses = Mapper<ResponseType>().mapArray(JSONString: json!) {
return responses
} else {
throw NetworkRequestError.invalidData
}
}
}
extension NetworkUploadRequest where ResponseType == RawJsonResult {
public var responseHandler: (Data) throws -> ResponseType { return rawJsonResponseHandler }
private func rawJsonResponseHandler(_ data: Data) throws -> ResponseType {
return JSON(data: data)
}
}
| 8693866f71b9a1548d2c156339629598 | 30.509174 | 104 | 0.647838 | false | false | false | false |
howwayla/taipeiAttractions | refs/heads/master | taipeiAttractions/Networking/Model/TAAttraction.swift | mit | 1 | //
// TAAttraction.swift
// taipeiAttractions
//
// Created by Hardy on 2016/6/27.
// Copyright © 2016年 Hardy. All rights reserved.
//
import Foundation
import ObjectMapper
import CoreLocation
struct TAAttraction: Mappable {
var ID: String?
var category: String?
var title: String?
var location: CLLocation?
var description: String?
var photoURL: [URL]?
init(JSON: JSONDictionary) {
let restructJSON = restructLocation(JSON: JSON)
if let object = Mapper<TAAttraction>().map(JSON: restructJSON) {
self = object
}
}
fileprivate func restructLocation(JSON: JSONDictionary) -> JSONDictionary {
var restructJSON = JSON
guard restructJSON["location"] == nil else {
return JSON
}
guard let longitude = JSON["longitude"] as? String,
let latitude = JSON["latitude"] as? String else {
return JSON
}
restructJSON["location"] = [ "longitude" : longitude,
"latitude" : latitude ]
return restructJSON
}
//MARK:- Mappable
init?(map: Map) {
}
mutating func mapping(map: Map) {
ID <- map["_id"]
category <- map["CAT2"]
title <- map["stitle"]
location <- (map["location"], LocationTransform())
description <- map["xbody"]
photoURL <- (map["file"], PhotoURLTransform())
}
}
| b1460e6d45b7ecba7af075e34cd5e6c4 | 23.693548 | 79 | 0.546048 | false | false | false | false |
liuweicode/LinkimFoundation | refs/heads/master | Example/LinkimFoundation/Foundation/System/Network/NetworkClient.swift | mit | 1 | //
// NetworkClient.swift
// Pods
//
// Created by 刘伟 on 16/6/30.
//
//
import UIKit
import Alamofire
typealias NetworkSuccessBlock = (message:NetworkMessage) -> Void
typealias NetworkFailBlock = (message:NetworkMessage) -> Void
enum NetworkRequestMethod : Int {
case POST, GET
}
var clientNO:UInt = 1
class NetworkClient : NSObject {
// 网络数据封装
lazy var message = NetworkMessage()
// 回调者
private var target:NSObject
// 超时时间
let networkTimeout:NSTimeInterval = 30
// 请求任务
var task:Request?
// 当前任务标识
var clientId:NSNumber?
// 回调
var successBlock:NetworkSuccessBlock?
var failBlock:NetworkFailBlock?
init(target obj:NSObject) {
target = obj
super.init()
clientNO = clientNO + 1
clientId = NSNumber(unsignedInteger: clientNO)
NetworkClientManager.sharedInstance.addClient(client: self, forClientId: clientId!)
}
func send(method method:NetworkRequestMethod, params:[String:AnyObject], url:String, successBlock:NetworkSuccessBlock, failBlock:NetworkFailBlock ) -> NSNumber? {
self.message.request.url = url
self.message.request.params = params
self.message.request.method = method
self.successBlock = successBlock
self.failBlock = failBlock
return self.send()
}
private func send() -> NSNumber?
{
switch self.message.request.method {
case .POST:
self.task = self.POST()
case .GET:
self.task = self.GET()
}
return self.clientId
}
private func POST() -> Request? {
return Alamofire.request(.POST, self.message.request.url!,
parameters:[:],
encoding: Alamofire.ParameterEncoding.Custom({ (convertible, params) -> (NSMutableURLRequest, NSError?) in
var data:NSData?
do{
data = try NSJSONSerialization.dataWithJSONObject(self.message.request.params!, options: NSJSONWritingOptions.init(rawValue: 0))
}catch{
print("--------请求参数报错-------")
}
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = data
mutableRequest.addValue("abcdefg", forHTTPHeaderField: "id")
return (mutableRequest, nil)
}),
headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in
// 设置请求头信息
self?.message.request.headers = request?.allHTTPHeaderFields
// 设置响应信息
self?.message.response.data = data
self?.message.response.headers = response?.allHeaderFields
// 是否有错误
if let responseError = error{
self?.message.networkError = .httpError(responseError.code, responseError.description)
self?.failure()
}else{
self?.success()
}
NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!)
})
}
private func GET() -> Request? {
return Alamofire.request(.GET, self.message.request.url!,
parameters:self.message.request.params,
encoding: Alamofire.ParameterEncoding.JSON,
headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in
// 设置请求头信息
self?.message.request.headers = request?.allHTTPHeaderFields
// 设置响应信息
self?.message.response.data = data
self?.message.response.headers = response?.allHeaderFields
// 是否有错误
if let responseError = error{
self?.message.networkError = .httpError(responseError.code, responseError.description)
self?.failure()
}else{
self?.success()
}
NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!)
})
}
private func success()
{
self.successBlock?(message:self.message)
}
private func failure()
{
self.failBlock?(message:self.message)
}
// 取消请求
func cancel() {
self.task?.cancel()
}
// 获取调用者
func requestReceive() -> NSObject {
return self.target
}
}
| d95e52b121b1d27cf9d133d5271f806c | 30.623288 | 166 | 0.566385 | false | false | false | false |
alblue/swift | refs/heads/master | stdlib/public/core/StringComparable.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension StringProtocol {
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func == <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .equal)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func != <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs == rhs)
}
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func < <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .less)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func > <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return rhs < lhs
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func <= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(rhs < lhs)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func >= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs < rhs)
}
}
extension String : Equatable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func == (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .equal)
}
}
extension String : Comparable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func < (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .less)
}
}
extension Substring : Equatable {}
| 7a3190b8671dbad3ea29a3f2df379514 | 32.578313 | 80 | 0.63258 | false | false | false | false |
mleiv/MEGameTracker | refs/heads/master | MEGameTracker/Library/IBIncluded/IBIncludedThing.swift | mit | 1 | ////
//// IBIncludedThing.swift
////
//// Copyright 2016 Emily Ivie
//
//// Licensed under The MIT License
//// For full copyright and license information, please see http://opensource.org/licenses/MIT
//// Redistributions of files must retain the above copyright notice.
import UIKit
/// Allows for removing individual scene design from the flow storyboards
/// and into individual per-controller storyboards, which minimizes git merge conflicts.
///
/// *NOT* @IBDesignable - we only use preview for IB preview
open class IBIncludedThing: UIViewController, IBIncludedThingLoadable {
@IBInspectable
open var incStoryboard: String? // abbreviated for shorter label in IB
open var includedStoryboard: String? {
get { return incStoryboard }
set { incStoryboard = newValue }
}
@IBInspectable
open var sceneId: String?
@IBInspectable
open var incNib: String? // abbreviated for shorter label in IB
open var includedNib: String? {
get { return incNib }
set { incNib = newValue }
}
@IBInspectable
open var nibController: String?
/// The controller loaded during including the above storyboard or nib
open weak var includedController: UIViewController?
/// Typical initialization of IBIncludedThing when it is created during normal scene loading at run time.
open override func awakeFromNib() {
super.awakeFromNib()
attach(toController: self, toView: nil)
}
open override func loadView() {
super.loadView()
attach(toController: nil, toView: self.view)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
includedController?.prepare(for: segue, sender: sender)
// The following code will run prepareForSegue in all child view controllers.
// This can cause unexpected multiple calls to prepareForSegue,
// so I prefer to be more cautious about which view controllers invoke prepareForSegue.
// See IBIncludedThingDemo Fourth/SixthController for examples/options with embedded view controllers.
// includedController?.findType(UIViewController.self) { controller in
// controller.prepareForSegue(segue, sender: sender)
// }
}
}
/// Because UIViewController does not preview in Interface Builder,
/// this is an Interface-Builder-only companion to IBIncludedThing.
/// Typically you would set the scene owner to IBIncludedThing
/// and then set the top-level view to IBIncludedThingPreview, with identical IBInspectable values.
@IBDesignable
open class IBIncludedThingPreview: UIView, IBIncludedThingLoadable {
@IBInspectable
open var incStoryboard: String? // abbreviated for shorter label in IB
open var includedStoryboard: String? {
get { return incStoryboard }
set { incStoryboard = newValue }
}
@IBInspectable
open var sceneId: String?
@IBInspectable
open var incNib: String? // abbreviated for shorter label in IB
open var includedNib: String? {
get { return incNib }
set { incNib = newValue }
}
@IBInspectable
open var nibController: String?
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
attach(toController: nil, toView: self)
}
// protocol conformance only (does not use):
open weak var includedController: UIViewController?
}
/// Can be used identically to IBIncludedThing, but for subviews inside scenes rather than an entire scene.
/// The major difference is that IBIncludedSubThing views, unfortunately, cannot be configured using prepareForSegue,
/// because they are loaded too late in the view controller lifecycle.
@IBDesignable
open class IBIncludedSubThing: UIView, IBIncludedThingLoadable {
@IBInspectable
open var incStoryboard: String? // abbreviated for shorter label in IB
open var includedStoryboard: String? {
get { return incStoryboard }
set { incStoryboard = newValue }
}
@IBInspectable
open var sceneId: String?
@IBInspectable
open var incNib: String? // abbreviated for shorter label in IB
open var includedNib: String? {
get { return incNib }
set { incNib = newValue }
}
@IBInspectable
open var nibController: String?
/// The controller loaded during including the above storyboard or nib
open weak var includedController: UIViewController?
/// An optional parent controller to use when this is being instantiated in code (and so might not have a hierarchy).
/// This would be private, but the protocol needs it.
open weak var parentController: UIViewController?
/// Initializes the IBIncludedSubThing for preview inside Xcode.
/// Does not bother attaching view controller to hierarchy.
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
attach(toController: nil, toView: self)
}
/// Typical initialization of IBIncludedSubThing when it is created during normal scene loading at run time.
open override func awakeFromNib() {
super.awakeFromNib()
if parentController == nil {
parentController = findParent(ofController: activeController(under: topController()))
}
attach(toController: parentController, toView: self)
}
// And then we need all these to get parent controller:
/// Grabs access to view controller hierarchy if possible.
fileprivate func topController() -> UIViewController? {
if let controller = window?.rootViewController {
return controller
} else if let controller = UIApplication.shared.windows
.first(where: { $0.isKeyWindow })?.rootViewController {
return controller
}
return nil
}
/// Locates the top-most currently visible controller.
fileprivate func activeController(under controller: UIViewController?) -> UIViewController? {
guard let controller = controller else {
return nil
}
if let tabController = controller as? UITabBarController,
let nextController = tabController.selectedViewController {
return activeController(under: nextController)
} else if let navController = controller as? UINavigationController,
let nextController = navController.visibleViewController {
return activeController(under: nextController)
} else if let nextController = controller.presentedViewController {
return activeController(under: nextController)
}
return controller
}
/// Locates the view controller with this view inside of it (depth first, since in a hierarchy
/// of view controllers the view would likely be in all the parentViewControllers of its view controller).
fileprivate func findParent(ofController topController: UIViewController!) -> UIViewController? {
if topController == nil {
return nil
}
for viewController in topController.children {
// first try, deep dive into child controllers
if let parentViewController = findParent(ofController: viewController) {
return parentViewController
}
}
// second try, top view controller (most generic, most things will be in this view)
if let topView = topController?.view, findSelf(inView: topView) {
return topController
}
return nil
}
/// Identifies if the IBIncludedSubThing view is equal to or under the view given.
fileprivate func findSelf(inView topView: UIView) -> Bool {
if topView == self || topView == self.superview {
return true
} else {
for view in topView.subviews {
if findSelf(inView: view ) {
return true
}
}
}
return false
}
}
/// This holds all the shared functionality of the IBIncludedThing variants.
public protocol IBIncludedThingLoadable: class {
// defining properties:
var includedStoryboard: String? { get set }
var sceneId: String? { get set }
var includedNib: String? { get set }
var nibController: String? { get set }
// reference:
var includedController: UIViewController? { get set }
// main:
func attach(toController parentController: UIViewController?, toView parentView: UIView?)
func detach()
// supporting:
func getController(inBundle bundle: Bundle) -> UIViewController?
func attach(controller: UIViewController?, toParent parentController: UIViewController?)
func attach(view: UIView?, toView parentView: UIView)
// useful:
func reload(includedStoryboard: String, sceneId: String?)
func reload(includedNib: String, nibController: String?)
}
extension IBIncludedThingLoadable {
/// Main function to attach the included content.
public func attach(toController parentController: UIViewController?, toView parentView: UIView?) {
guard let includedController = includedController ?? getController(inBundle: Bundle(for: type(of: self))) else {
return
}
if let parentController = parentController {
attach(controller: includedController, toParent: parentController)
}
if let parentView = parentView {
attach(view: includedController.view, toView: parentView)
}
}
/// Main function to remove the included content.
public func detach() {
includedController?.view.removeFromSuperview()
includedController?.removeFromParent()
self.includedStoryboard = nil
self.sceneId = nil
self.includedNib = nil
self.nibController = nil
}
/// Internal: loads the controller from the storyboard or nib
public func getController(inBundle bundle: Bundle) -> UIViewController? {
var foundController: UIViewController?
if let storyboardName = self.includedStoryboard {
// load storyboard
let storyboardObj = UIStoryboard(name: storyboardName, bundle: bundle)
let sceneId = self.sceneId ?? ""
foundController = sceneId.isEmpty
? storyboardObj.instantiateInitialViewController()
: storyboardObj.instantiateViewController(withIdentifier: sceneId)
} else if let nibName = self.includedNib {
// load nib
if let controllerName = nibController,
let appName = bundle.object(forInfoDictionaryKey: "CFBundleName") as? String {
// load specified controller
let classStringName = "\(appName).\(controllerName)"
if let ControllerType = NSClassFromString(classStringName) as? UIViewController.Type {
foundController = ControllerType.init(nibName: nibName, bundle: bundle) as UIViewController
}
} else {
// load generic controller
foundController = UIViewController(nibName: nibName, bundle: bundle)
}
}
return foundController
}
/// Internal: inserts the included controller into the view hierarchy
/// (this helps trigger correct view hierarchy lifecycle functions)
public func attach(controller: UIViewController?, toParent parentController: UIViewController?) {
// save for later (do not explicitly reference view or you will trigger viewDidLoad)
guard let controller = controller, let parentController = parentController else {
return
}
// save for later use
includedController = controller
// attach to hierarchy
controller.willMove(toParent: parentController)
parentController.addChild(controller)
controller.didMove(toParent: parentController)
}
/// Internal: inserts the included view inside the IBIncludedThing view.
/// Makes this nesting invisible by removing any background on IBIncludedThing
/// and sets constraints so included content fills IBIncludedThing.
public func attach(view: UIView?, toView parentView: UIView) {
guard let view = view else {
return
}
parentView.addSubview(view)
//clear out top-level view visibility, so only subview shows
parentView.isOpaque = false
parentView.backgroundColor = UIColor.clear
//tell child to fit itself to the edges of wrapper (self)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true
}
/// Programmatic reloading of a storyboard inside the same IBIncludedSubThing view.
/// parentController is only necessary when the storyboard has had no previous storyboard,
/// and so is missing an included controller (and its parent).
public func reload(includedStoryboard: String, sceneId: String?) {
let parentController = (self as? IBIncludedThing) ?? (self as? IBIncludedSubThing)?.parentController
guard includedStoryboard != self.includedStoryboard || sceneId != self.sceneId,
let parentView = (self as? IBIncludedSubThing) ?? parentController?.view else {
return
}
// cleanup old stuff
detach()
self.includedController = nil
// reset to new values
self.includedStoryboard = includedStoryboard
self.sceneId = sceneId
self.includedNib = nil
self.nibController = nil
// reload
attach(toController: parentController, toView: parentView)
}
/// Programmatic reloading of a nib inside the same IBIncludedSubThing view.
/// parentController is only necessary when the storyboard has had no previous storyboard,
/// and so is missing an included controller (and its parent).
public func reload(includedNib: String, nibController: String?) {
let parentController = (self as? IBIncludedThing) ?? (self as? IBIncludedSubThing)?.parentController
guard includedNib != self.includedNib || nibController != self.nibController,
let parentView = (self as? IBIncludedSubThing) ?? parentController?.view else {
return
}
// cleanup old stuff
detach()
self.includedController = nil
// reset to new values
self.includedStoryboard = nil
self.sceneId = nil
self.includedNib = includedNib
self.nibController = nibController
// reload
attach(toController: parentController, toView: parentView)
}
}
extension UIViewController {
/// A convenient utility for quickly running some code on a view controller of a specific type
/// in the current view controller hierarchy.
public func find<T: UIViewController>(controllerType: T.Type, apply: ((T) -> Void)) {
for childController in children {
if let foundController = childController as? T {
apply(foundController)
} else {
childController.find(controllerType: controllerType, apply: apply)
}
}
if let foundController = self as? T {
apply(foundController)
}
}
}
extension UIWindow {
static var isInterfaceBuilder: Bool {
#if TARGET_INTERFACE_BUILDER
return true
#else
return false
#endif
}
}
| f5ff589c1cbdd34e2a8d0a7f6272abca | 36.031414 | 118 | 0.756256 | false | false | false | false |
xiongxiong/TagList | refs/heads/master | Example/TagList/ViewController.swift | mit | 1 | //
// ViewController.swift
// TagList
//
// Created by 王继荣 on 13/12/2016.
// Copyright © 2016 wonderbear. All rights reserved.
//
import UIKit
import SwiftTagList
class ViewController: UIViewController {
var addBtn: UIButton = {
let view = UIButton()
view.setTitle("Add Tag", for: .normal)
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.blue.cgColor
view.layer.cornerRadius = 10
view.setTitleColor(UIColor.blue, for: .normal)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var typeLabel: UILabel = {
let view = UILabel()
view.text = "tag type"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var typeSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["text", "icon", "icon & text"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectLabel: UILabel = {
let view = UILabel()
view.text = "multi selection"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["none", "single", "multi"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignHorizontalLabel: UILabel = {
let view = UILabel()
view.text = "horizontal alignment"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignHorizontalSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["left", "center", "right"])
view.selectedSegmentIndex = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignVerticalLabel: UILabel = {
let view = UILabel()
view.text = "vertical alignment"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var alignVerticalSegment: UISegmentedControl = {
let view = UISegmentedControl(items: ["top", "center", "bottom"])
view.selectedSegmentIndex = 1
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchSeparateLabel: UILabel = {
let view = UILabel()
view.text = "tag is separated"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchSeparateBtn: UISwitch = {
let view = UISwitch()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchDeleteLabel: UILabel = {
let view = UILabel()
view.text = "tag is deletable"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var switchDeleteBtn: UISwitch = {
let view = UISwitch()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var areaSelected: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.lightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var selectedTagList: TagList = {
let view = TagList()
view.isAutowrap = false
view.backgroundColor = UIColor.yellow
view.tagMargin = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
view.separator.image = #imageLiteral(resourceName: "icon_arrow_right")
view.separator.size = CGSize(width: 16, height: 16)
view.separator.margin = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return view
}()
var areaList: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = UIColor.cyan
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var tagList: TagList = {
let view = TagList()
view.backgroundColor = UIColor.green
view.tagMargin = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
view.separator.image = #imageLiteral(resourceName: "icon_arrow_right")
view.separator.size = CGSize(width: 16, height: 16)
view.separator.margin = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
return view
}()
var areaListMask = UIView()
var swiDelete: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(addBtn)
view.addSubview(typeLabel)
view.addSubview(typeSegment)
view.addSubview(selectLabel)
view.addSubview(selectSegment)
view.addSubview(alignHorizontalLabel)
view.addSubview(alignHorizontalSegment)
view.addSubview(alignVerticalLabel)
view.addSubview(alignVerticalSegment)
view.addSubview(switchSeparateLabel)
view.addSubview(switchSeparateBtn)
view.addSubview(switchDeleteLabel)
view.addSubview(switchDeleteBtn)
view.addSubview(areaSelected)
areaSelected.addSubview(selectedTagList)
view.addSubview(areaList)
areaList.addSubview(tagList)
addBtn.addTarget(self, action: #selector(addTag), for: .touchUpInside)
typeSegment.addTarget(self, action: #selector(switchType), for: .valueChanged)
selectSegment.addTarget(self, action: #selector(switchSelect), for: .valueChanged)
alignHorizontalSegment.addTarget(self, action: #selector(switchHorizontalAlign), for: .valueChanged)
alignVerticalSegment.addTarget(self, action: #selector(switchVerticalAlign), for: .valueChanged)
switchSeparateBtn.addTarget(self, action: #selector(switchSeparate), for: .valueChanged)
switchDeleteBtn.addTarget(self, action: #selector(switchDelete), for: .valueChanged)
selectedTagList.delegate = self
tagList.delegate = self
// ==================================
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: addBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 40))
// ==================================
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .trailing, relatedBy: .equal, toItem: selectSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .top, relatedBy: .equal, toItem: addBtn, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: typeSegment, attribute: .centerY, relatedBy: .equal, toItem: typeLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .trailing, relatedBy: .equal, toItem: selectSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .top, relatedBy: .equal, toItem: typeLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: selectSegment, attribute: .centerY, relatedBy: .equal, toItem: selectLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .trailing, relatedBy: .equal, toItem: alignHorizontalSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .top, relatedBy: .equal, toItem: selectLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: alignHorizontalSegment, attribute: .centerY, relatedBy: .equal, toItem: alignHorizontalLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .trailing, relatedBy: .equal, toItem: alignHorizontalSegment, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .top, relatedBy: .equal, toItem: alignHorizontalLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 160))
view.addConstraint(NSLayoutConstraint(item: alignVerticalSegment, attribute: .centerY, relatedBy: .equal, toItem: alignVerticalLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .trailing, relatedBy: .equal, toItem: switchSeparateBtn, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .top, relatedBy: .equal, toItem: alignVerticalLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: switchSeparateBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchSeparateBtn, attribute: .centerY, relatedBy: .equal, toItem: switchSeparateLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .trailing, relatedBy: .equal, toItem: switchDeleteBtn, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .top, relatedBy: .equal, toItem: switchSeparateLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50))
view.addConstraint(NSLayoutConstraint(item: switchDeleteBtn, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: switchDeleteBtn, attribute: .centerY, relatedBy: .equal, toItem: switchDeleteLabel, attribute: .centerY, multiplier: 1, constant: 0))
// ==================================
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .top, relatedBy: .equal, toItem: switchDeleteLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaSelected, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 80))
// ==================================
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .top, relatedBy: .equal, toItem: areaSelected, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: areaList, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedTagList.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: areaSelected.frame.height))
tagList.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: areaList.frame.width, height: 0))
}
func addTag() {
let str = "In 1886 he moved to Paris where he met members of the avant-garde"
let icons = ["tag_0","tag_1","tag_2","tag_3","tag_4","tag_5","tag_6","tag_7","tag_8","tag_9"]
let tagArr = str.components(separatedBy: .whitespaces)
let tagStr = tagArr[Int(arc4random_uniform(UInt32(tagArr.count)))]
var newPresent: TagPresentable!
switch typeSegment.selectedSegmentIndex {
case 1:
newPresent = TagPresentableIcon(tag: tagStr, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))], height: 30)
case 2:
newPresent = TagPresentableIconText(tag: tagStr, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))]) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
default:
newPresent = TagPresentableText(tag: tagStr) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
}
let tag = Tag(content: newPresent, onInit: {
$0.padding = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
$0.backgroundColor = UIColor.white
}, onSelect: {
$0.backgroundColor = $0.isSelected ? UIColor.orange : UIColor.white
})
if swiDelete {
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
tagList.tags.append(tag)
}
func switchType() {
let icons = ["tag_0","tag_1","tag_2","tag_3","tag_4","tag_5","tag_6","tag_7","tag_8","tag_9"]
tagList.tags = tagList.tagPresentables().map({ (present) -> Tag in
var newPresent: TagPresentable!
switch typeSegment.selectedSegmentIndex {
case 1:
newPresent = TagPresentableIcon(tag: present.tag, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))], height: 30)
case 2:
newPresent = TagPresentableIconText(tag: present.tag, icon: icons[Int(arc4random_uniform(UInt32(icons.count)))]) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
default:
newPresent = TagPresentableText(tag: present.tag) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}
}
let tag = Tag(content: newPresent, onInit: {
$0.padding = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
$0.backgroundColor = UIColor.white
}, onSelect: {
$0.backgroundColor = $0.isSelected ? UIColor.orange : UIColor.white
})
if swiDelete {
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
return tag
})
}
func switchSelect() {
tagList.selectionMode = [TagSelectionMode.none, TagSelectionMode.single, TagSelectionMode.multiple][selectSegment.selectedSegmentIndex]
if tagList.selectionMode == TagSelectionMode.none {
tagList.clearSelected()
}
}
func switchSeparate() {
tagList.isSeparatorEnabled = switchSeparateBtn.isOn
}
func switchDelete() {
swiDelete = switchDeleteBtn.isOn
if switchDeleteBtn.isOn {
tagList.tags.forEach { (tag) in
tag.wrappers = [TagWrapperRemover(onInit: {
$0.space = 8
$0.deleteButton.tintColor = UIColor.black
}) {
$0.deleteButton.tintColor = $1 ? UIColor.white : UIColor.black
}]
}
} else {
tagList.tags.forEach { (tag) in
tag.wrappers = []
}
}
}
func switchHorizontalAlign() {
tagList.horizontalAlignment = [TagHorizontalAlignment.left, TagHorizontalAlignment.center, TagHorizontalAlignment.right][alignHorizontalSegment.selectedSegmentIndex]
}
func switchVerticalAlign() {
tagList.verticalAlignment = [TagVerticalAlignment.top, TagVerticalAlignment.center, TagVerticalAlignment.bottom][alignHorizontalSegment.selectedSegmentIndex]
}
func updateSelectedTagList() {
selectedTagList.tags = tagList.selectedTagPresentables().map({ (tag) -> Tag in
Tag(content: TagPresentableText(tag: tag.tag) {
$0.label.font = UIFont.systemFont(ofSize: 16)
}, onInit: {
$0.padding = UIEdgeInsets(top: 3, left: 5, bottom: 3, right: 5)
$0.layer.borderColor = UIColor.cyan.cgColor
$0.layer.borderWidth = 2
$0.layer.cornerRadius = 5
})
})
}
}
extension ViewController: TagListDelegate {
func tagListUpdated(tagList: TagList) {
if tagList == selectedTagList {
areaSelected.contentSize = tagList.intrinsicContentSize
} else {
areaList.contentSize = tagList.intrinsicContentSize
updateSelectedTagList()
}
}
func tagActionTriggered(tagList: TagList, action: TagAction, content: TagPresentable, index: Int) {
print("========= action -- \(action), content -- \(content.tag), index -- \(index)")
}
}
| ae24b4935be2c0b5b5a84f30dae2a5cf | 57.06366 | 196 | 0.656053 | false | false | false | false |
leuski/Coiffeur | refs/heads/github | Coiffeur/src/view/OptionsRowView.swift | apache-2.0 | 1 | //
// OptionsRowView.swift
// Coiffeur
//
// Created by Anton Leuski on 4/16/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import Cocoa
class ConfigCellView: NSTableCellView {
// prevent the state restoration mechanism to save/restore this view properties
override class var restorableStateKeyPaths: [String] { return [] }
}
class ConfigOptionCellView: ConfigCellView {
// will use this to shift the content of the cell appropriately
@IBOutlet weak var leftMargin: NSLayoutConstraint!
}
class ConfigChoiceCellView: ConfigOptionCellView {
@IBOutlet weak var segmented: NSSegmentedControl!
}
extension ConfigNodeLocation {
var color: NSColor {
// section color
return NSColor(calibratedHue: CGFloat(index)/CGFloat(12),
saturation: 0.7, brightness: 0.7, alpha: 1)
}
}
class ConfigRowView: NSTableRowView {
// prevent the state restoration mechanism to save/restore this view properties
override class var restorableStateKeyPaths: [String] { return [] }
@IBOutlet weak var leftMargin: NSLayoutConstraint!
@IBOutlet weak var textField: NSTextField!
var drawSeparator = false
typealias Location = ConfigNode.Location
var locations = [Location]()
override func drawBackground(in dirtyRect: NSRect)
{
if self.isGroupRowStyle {
// start with the background color
var backgroundColor = self.backgroundColor
if self.locations.count > 1 {
// if this is a subsection, add a splash of supersection color
backgroundColor = backgroundColor.blended(
withFraction: 0.1, of: locations[0].color)
?? backgroundColor
}
// make it a bit darker
backgroundColor = backgroundColor.shadow(withLevel: 0.025)
?? backgroundColor
if self.isFloating {
// if the row is floating, add a bit of transparency
backgroundColor = backgroundColor.withAlphaComponent(0.75)
}
backgroundColor.setFill()
} else {
_adjustTextFieldFont()
self.backgroundColor.setFill()
}
NSRect(x: CGFloat(0), y: CGFloat(0),
width: self.bounds.size.width, height: self.bounds.size.height).fill()
if drawSeparator {
_separatorPath().stroke()
}
// draw the colored lines using the section colors
for index in 0 ..< min(1, locations.count - 1) {
locations[index].color.setFill()
NSRect(x: CGFloat(3 + index*5), y: CGFloat(0),
width: CGFloat(3), height: self.bounds.size.height-1).fill()
}
// if we are a group, underline the title with the appropriate color
if self.isGroupRowStyle && locations.count == 1 {
locations.last?.color.set()
let path = NSBezierPath()
let lineLength = 200
let hOffset = 3 + 5*(locations.count-1)
path.lineWidth = CGFloat(1)
path.move(to: NSPoint(x: CGFloat(hOffset),
y: self.bounds.size.height-path.lineWidth+0.5))
path.line(to: NSPoint(x: CGFloat(lineLength - hOffset),
y: self.bounds.size.height-path.lineWidth+0.5))
path.stroke()
}
}
private func _adjustTextFieldFont() {
guard
let textField = textField,
let textFieldFont = textField.font
else { return }
if self.interiorBackgroundStyle == .dark {
textField.textColor = .selectedTextColor
if self.window?.backingScaleFactor == 1 {
// light on dark looks bad on regular resolution screen,
// so we make the font bold to improve readability
textField.font = NSFontManager.shared.convert(
textFieldFont, toHaveTrait: .boldFontMask)
} else {
// on a retina screen the same text looks fine. no need to do bold.
textField.font = NSFontManager.shared.convert(
textFieldFont, toNotHaveTrait: .boldFontMask)
}
} else {
textField.textColor = NSColor.textColor
textField.font = NSFontManager.shared.convert(
textFieldFont, toNotHaveTrait: .boldFontMask)
}
}
private func _separatorPath() -> NSBezierPath {
// draw the top border
let path = NSBezierPath()
path.lineWidth = CGFloat(1)
path.move(to: NSPoint(x: CGFloat(0),
y: self.bounds.size.height-path.lineWidth+0.5))
path.line(to: NSPoint(x: self.bounds.size.width,
y: self.bounds.size.height-path.lineWidth+0.5))
NSColor.gridColor.set()
return path
}
override func drawSelection(in dirtyRect: NSRect)
{
let margin = CGFloat(7)
// start with the regular selection color
var color = NSColor.selectedMenuItemColor
// add a hint of the current section color
if locations.count > 0 {
color = color.blended(
withFraction: 0.25, of: locations[0].color) ?? color
}
if self.interiorBackgroundStyle == .light {
// if we are out of focus, lighten the color
color = color.blended(
withFraction: 0.9, of: NSColor(calibratedWhite: 0.9, alpha: 1))
?? color
}
// make sure it is not transparent
color = color.withAlphaComponent(1)
// paint
color.setFill()
NSRect(
x: margin, y: CGFloat(0),
width: bounds.size.width-margin,
height: bounds.size.height-1)
.fill()
}
}
| d7a673e493cdbcb0a8be4eda39bab2e5 | 31.831461 | 81 | 0.660849 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/develop | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Views/SpinnerCell.swift | apache-2.0 | 4 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import IGListKit
import UIKit
func spinnerSectionController() -> ListSingleSectionController {
let configureBlock = { (item: Any, cell: UICollectionViewCell) in
guard let cell = cell as? SpinnerCell else { return }
cell.activityIndicator.startAnimating()
}
let sizeBlock = { (item: Any, context: ListCollectionContext?) -> CGSize in
guard let context = context else { return .zero }
return CGSize(width: context.containerSize.width, height: 100)
}
return ListSingleSectionController(cellClass: SpinnerCell.self,
configureBlock: configureBlock,
sizeBlock: sizeBlock)
}
final class SpinnerCell: UICollectionViewCell {
lazy var activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
let bounds = contentView.bounds
activityIndicator.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
}
| e5201107606987c493a145cdc0147528 | 36.875 | 80 | 0.70462 | false | true | false | false |
li13418801337/DouyuTV | refs/heads/master | DouyuZB/DouyuZB/Classes/Main/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DouyuZB
//
// Created by work on 16/10/18.
// Copyright © 2016年 xiaosi. All rights reserved.
//
import UIKit
//协议
protocol PageTitleViewDelegate : class {
func pageTitleView(titleView : PageTitleView,selectedIndex index : Int)
}
//定义常量
private let kscrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
private let KSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
class PageTitleView: UIView {
//懒加载属性
private lazy var titleLabels : [UILabel] = [UILabel]()
private lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
private lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orangeColor()
return scrollLine
}()
//定义属性
private var titles : [String]
private var currentIndex : Int = 0
//代理属性
weak var delegate : PageTitleViewDelegate?
//自定义构造函数
init(frame:CGRect ,titles: [String]){
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//-- 设置ui界面
extension PageTitleView{
private func setupUI(){
addSubview(scrollView)
scrollView.frame = bounds
//添加title对应的label
setupTitlelabels()
//设置底线和滑动的滑块
setupBottonMenuAndScrollLine()
}
private func setupTitlelabels(){
for (index,title) in titles.enumerate() {
let labelW: CGFloat = frame.width / CGFloat(titles.count)
let labelH: CGFloat = frame.height - kscrollLineH
let labelY: CGFloat = 0
//1.创建label
let label = UILabel()
//2.设置属性
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .Center
//设置label的frame
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//将label添加到scrollview中
scrollView.addSubview(label)
titleLabels.append(label)
//添加label手势
label.userInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titileLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottonMenuAndScrollLine(){
//添加底线
let buttomLine = UIView()
buttomLine.backgroundColor = UIColor.lightGrayColor()
let lineH : CGFloat = 0.5
buttomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(buttomLine)
//添加底部滑动线
guard let firstLabel = titleLabels.first else{return}
firstLabel.textColor = UIColor(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height
- kscrollLineH, width: firstLabel.frame.width, height: kscrollLineH)
}
}
// ----监听label的监听手势
extension PageTitleView{
@objc private func titileLabelClick(tapGes : UITapGestureRecognizer){
//获取当前的label
guard let currentLabel = tapGes.view as? UILabel else{return}
//获取之前的label
let oldLabel = titleLabels[currentIndex]
(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2)
//切换文字的颜色
currentLabel.textColor = UIColor(r: KSelectColor.0, g: KSelectColor.1, b: KSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//保存最新的label
currentIndex = currentLabel.tag
//滚动条位置
let scrollLineX = CGFloat(currentIndex ) * self.scrollLine.frame.width
UIView.animateWithDuration(0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
//通知代理
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
//对外暴露的方法
extension PageTitleView{
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int){
//1.取出sourcelabel/targetlabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//3.颜色的渐变
//3.1 取出变化的范围
let colorDelta = (KSelectColor.0 - kNormalColor.0, KSelectColor.1 - kNormalColor.1, KSelectColor.2 - kNormalColor.2)
//3.2 变化sourcelabel
sourceLabel.textColor = UIColor(r: KSelectColor.0 - colorDelta.0 * progress, g: KSelectColor.1 - colorDelta.1 * progress, b: KSelectColor.2 - colorDelta.2 * progress)
//3.3 变化targetlable
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
currentIndex = targetIndex
}
}
| 074aa4b44b03c64a3f46b68da6dcc500 | 27.096154 | 174 | 0.602841 | false | false | false | false |
cemolcay/Fretboard | refs/heads/master | Source/FretboardView.swift | mit | 1 | //
// FretboardView.swift
// Fretboard
//
// Created by Cem Olcay on 20/04/2017.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
import MusicTheorySwift
import CenterTextLayer
// MARK: - FretLabel
@IBDesignable
public class FretLabel: FRView {
public var textLayer = CenterTextLayer()
// MARK: Init
#if os(iOS) || os(tvOS)
public override init(frame: CGRect) {
super.init(frame: frame)
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(textLayer)
}
#elseif os(OSX)
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = NSScreen.main?.backingScaleFactor ?? 1
layer?.addSublayer(textLayer)
}
#endif
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
textLayer.frame = layer.bounds
}
#elseif os(OSX)
public override func layout() {
super.layout()
guard let layer = layer else { return }
textLayer.frame = layer.bounds
}
#endif
}
// MARK: - FretView
public enum FretNoteType {
case `default`
case capoStart
case capo
case capoEnd
case none
}
@IBDesignable
public class FretView: FRView {
/// `FretboardNote` on fretboard.
public var note: FretboardNote
/// Direction of fretboard.
public var direction: FretboardDirection = .horizontal
/// Note drawing style if it is pressed.
public var noteType: FretNoteType = .none
/// Note drawing offset from edges.
public var noteOffset: CGFloat = 5
/// If its 0th fret, than it is an open string, which is not a fret technically but represented as a FretView.
public var isOpenString: Bool = false
/// Draws the selected note on its text layer.
public var isDrawSelectedNoteText: Bool = true
/// When we are on chordMode, we check the if capo on the fret to detect chords.
public var isCapoOn: Bool = false
/// Shape layer that strings draws on.
public var stringLayer = CAShapeLayer()
/// Shape layer that frets draws on.
public var fretLayer = CAShapeLayer()
/// Shape layer that notes draws on.
public var noteLayer = CAShapeLayer()
/// Text layer that notes writes on.
public var textLayer = CenterTextLayer()
/// `textLayer` color that note text draws on.
public var textColor = FRColor.white.cgColor
// MARK: Init
public init(note: FretboardNote) {
self.note = note
super.init(frame: .zero)
setup()
}
required public init?(coder: NSCoder) {
note = FretboardNote(note: Pitch(midiNote: 0), fretIndex: 0, stringIndex: 0)
super.init(coder: coder)
setup()
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
draw()
}
#elseif os(OSX)
public override func layout() {
super.layout()
draw()
}
#endif
// MARK: Setup
private func setup() {
#if os(OSX)
wantsLayer = true
guard let layer = layer else { return }
#endif
layer.addSublayer(stringLayer)
layer.addSublayer(fretLayer)
layer.addSublayer(noteLayer)
layer.addSublayer(textLayer)
#if os(iOS) || os(tvOS)
textLayer.contentsScale = UIScreen.main.scale
#elseif os(OSX)
textLayer.contentsScale = NSScreen.main?.backingScaleFactor ?? 1
#endif
}
// MARK: Draw
private func draw() {
#if os(OSX)
guard let layer = layer else { return }
#endif
CATransaction.setDisableActions(true)
// FretLayer
fretLayer.frame = layer.bounds
let fretPath = FRBezierPath()
switch direction {
case .horizontal:
fretPath.move(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.minY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.maxY))
case .vertical:
#if os(iOS) || os(tvOS)
fretPath.move(to: CGPoint(x: fretLayer.frame.minX, y: fretLayer.frame.maxY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.maxY))
#elseif os(OSX)
fretPath.move(to: CGPoint(x: fretLayer.frame.minX, y: fretLayer.frame.minY))
fretPath.addLine(to: CGPoint(x: fretLayer.frame.maxX, y: fretLayer.frame.minY))
#endif
}
fretLayer.path = fretPath.cgPath
// StringLayer
stringLayer.frame = layer.bounds
let stringPath = FRBezierPath()
if !isOpenString { // Don't draw strings on fret 0 because it is open string.
switch direction {
case .horizontal:
stringPath.move(to: CGPoint(x: stringLayer.frame.minX, y: stringLayer.frame.midY))
stringPath.addLine(to: CGPoint(x: stringLayer.frame.maxX, y: stringLayer.frame.midY))
case .vertical:
stringPath.move(to: CGPoint(x: stringLayer.frame.midX, y: stringLayer.frame.minY))
stringPath.addLine(to: CGPoint(x: stringLayer.frame.midX, y: stringLayer.frame.maxY))
}
}
stringLayer.path = stringPath.cgPath
// NoteLayer
noteLayer.frame = layer.bounds
let noteSize = max(min(noteLayer.frame.size.width, noteLayer.frame.size.height) - noteOffset, 0)
var notePath = FRBezierPath()
switch noteType {
case .none:
break
case .capo:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height))
#elseif os(OSX)
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width,
height: noteSize))
#elseif os(OSX)
notePath.appendRect(CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width,
height: noteSize))
#endif
}
case .capoStart:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
#endif
}
case .capoEnd:
switch direction {
case .horizontal:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.minY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY,
width: noteSize,
height: noteLayer.frame.size.height / 2))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(rect: CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
let cap = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.append(cap)
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
notePath.appendRect(CGRect(
x: noteLayer.frame.minX,
y: noteLayer.frame.midY - (noteSize / 2),
width: noteLayer.frame.size.width / 2,
height: noteSize))
#endif
}
default:
#if os(iOS) || os(tvOS)
notePath = UIBezierPath(ovalIn: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
#elseif os(OSX)
notePath.appendOval(in: CGRect(
x: noteLayer.frame.midX - (noteSize / 2),
y: noteLayer.frame.midY - (noteSize / 2),
width: noteSize,
height: noteSize))
#endif
}
noteLayer.path = notePath.cgPath
// TextLayer
let noteText = NSAttributedString(
string: "\(note.note.key)",
attributes: [
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: noteSize / 2)
])
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.string = isDrawSelectedNoteText && note.isSelected ? noteText : nil
textLayer.frame = layer.bounds
}
}
// MARK: - FretboardView
@IBDesignable
public class FretboardView: FRView, FretboardDelegate {
public var fretboard = Fretboard()
@IBInspectable public var fretStartIndex: Int = 0 { didSet { fretboard.startIndex = fretStartIndex }}
@IBInspectable public var fretCount: Int = 5 { didSet { fretboard.count = fretCount }}
@IBInspectable public var direction: String = "horizontal" { didSet { directionDidChange() }}
@IBInspectable public var isDrawNoteName: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawStringName: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawFretNumber: Bool = true { didSet { redraw() }}
@IBInspectable public var isDrawCapo: Bool = true { didSet { redraw() }}
@IBInspectable public var isChordModeOn: Bool = false { didSet { redraw() }}
@IBInspectable public var fretWidth: CGFloat = 5 { didSet { redraw() }}
@IBInspectable public var stringWidth: CGFloat = 0.5 { didSet { redraw() }}
#if os(iOS) || os(tvOS)
@IBInspectable public var stringColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var fretColor: UIColor = .darkGray { didSet { redraw() }}
@IBInspectable public var noteColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var noteTextColor: UIColor = .white { didSet { redraw() }}
@IBInspectable public var stringLabelColor: UIColor = .black { didSet { redraw() }}
@IBInspectable public var fretLabelColor: UIColor = .black { didSet { redraw() }}
#elseif os(OSX)
@IBInspectable public var stringColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var fretColor: NSColor = .darkGray { didSet { redraw() }}
@IBInspectable public var noteColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var noteTextColor: NSColor = .white { didSet { redraw() }}
@IBInspectable public var stringLabelColor: NSColor = .black { didSet { redraw() }}
@IBInspectable public var fretLabelColor: NSColor = .black { didSet { redraw() }}
#endif
private var fretViews: [FretView] = []
private var fretLabels: [FretLabel] = []
private var stringLabels: [FretLabel] = []
// MARK: Init
#if os(iOS) || os(tvOS)
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
#elseif os(OSX)
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
#endif
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Lifecycle
#if os(iOS) || os(tvOS)
public override func layoutSubviews() {
super.layoutSubviews()
draw()
drawNotes()
}
#elseif os(OSX)
public override func layout() {
super.layout()
draw()
drawNotes()
}
#endif
// MARK: Setup
private func setup() {
// Create fret views
fretViews.forEach({ $0.removeFromSuperview() })
fretViews = []
fretboard.notes.forEach{ fretViews.append(FretView(note: $0)) }
fretViews.forEach({ addSubview($0) })
// Create fret numbers
fretLabels.forEach({ $0.removeFromSuperview() })
fretLabels = []
(0..<fretboard.count).forEach({ _ in fretLabels.append(FretLabel(frame: .zero)) })
fretLabels.forEach({ addSubview($0) })
// Create string names
stringLabels.forEach({ $0.removeFromSuperview() })
stringLabels = []
fretboard.tuning.strings.forEach({ _ in stringLabels.append(FretLabel(frame: .zero)) })
stringLabels.forEach({ addSubview($0) })
// Set FretboardDelegate
fretboard.delegate = self
}
private func directionDidChange() {
switch direction {
case "vertical", "Vertical":
fretboard.direction = .vertical
default:
fretboard.direction = .horizontal
}
}
// MARK: Draw
private func draw() {
let gridWidth = frame.size.width / (CGFloat(fretboard.direction == .horizontal ? fretboard.count : fretboard.tuning.strings.count) + 0.5)
let gridHeight = frame.size.height / (CGFloat(fretboard.direction == .horizontal ? fretboard.tuning.strings.count: fretboard.count) + 0.5)
// String label size
var stringLabelSize = CGSize()
if isDrawStringName {
let horizontalSize = CGSize(
width: gridWidth / 2,
height: gridHeight)
let verticalSize = CGSize(
width: gridWidth,
height: gridHeight / 2)
stringLabelSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
}
// Fret label size
var fretLabelSize = CGSize()
if isDrawFretNumber {
let horizontalSize = CGSize(
width: (frame.size.width - stringLabelSize.width) / CGFloat(fretboard.direction == .horizontal ? fretboard.count : fretboard.tuning.strings.count),
height: gridHeight / 2)
let verticalSize = CGSize(
width: gridWidth / 2,
height: (frame.size.height - stringLabelSize.height) / CGFloat(fretboard.direction == .horizontal ? fretboard.tuning.strings.count : fretboard.count))
fretLabelSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
}
// Fret view size
let horizontalSize = CGSize(
width: (frame.size.width - stringLabelSize.width) / CGFloat(fretboard.count),
height: (frame.size.height - fretLabelSize.height) / CGFloat(fretboard.tuning.strings.count))
let verticalSize = CGSize(
width: (frame.size.width - fretLabelSize.width) / CGFloat(fretboard.tuning.strings.count),
height: (frame.size.height - stringLabelSize.height) / CGFloat(fretboard.count))
var fretSize = fretboard.direction == .horizontal ? horizontalSize : verticalSize
// Layout string labels
for (index, label) in stringLabels.enumerated() {
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
#if os(iOS) || os(tvOS)
position.y = stringLabelSize.height * CGFloat(index)
#elseif os(OSX)
position.y = frame.size.height - stringLabelSize.height - (stringLabelSize.height * CGFloat(index))
#endif
case .vertical:
position.x = stringLabelSize.width * CGFloat(index) + fretLabelSize.width
}
label.textLayer.string = NSAttributedString(
string: "\(fretboard.strings[index].key)",
attributes: [
NSAttributedString.Key.foregroundColor: stringLabelColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: (min(stringLabelSize.width, stringLabelSize.height) * 2) / 3)
])
label.frame = CGRect(origin: position, size: stringLabelSize)
}
// Layout fret labels
for (index, label) in fretLabels.enumerated() {
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
position.x = (fretLabelSize.width * CGFloat(index)) + stringLabelSize.width
#if os(iOS) || os(tvOS)
position.y = frame.size.height - fretLabelSize.height
#endif
case .vertical:
#if os(iOS) || os(tvOS)
position.y = fretLabelSize.height * CGFloat(index) + stringLabelSize.height
#elseif os(OSX)
position.y = frame.size.height - fretLabelSize.height - (fretLabelSize.height * CGFloat(index)) - stringLabelSize.height
#endif
}
if fretboard.startIndex == 0, index == 0 {
label.textLayer.string = nil
} else {
label.textLayer.string = NSAttributedString(
string: "\(fretboard.startIndex + index)",
attributes: [
NSAttributedString.Key.foregroundColor: fretLabelColor,
NSAttributedString.Key.font: FRFont.systemFont(ofSize: (min(fretLabelSize.width, fretLabelSize.height) * 2) / 3)
])
}
label.frame = CGRect(origin: position, size: fretLabelSize)
}
// Layout fret views
for (index, fret) in fretViews.enumerated() {
let fretIndex = fret.note.fretIndex
let stringIndex = fret.note.stringIndex
// Position
var position = CGPoint()
switch fretboard.direction {
case .horizontal:
#if os(iOS) || os(tvOS)
position.x = fretSize.width * CGFloat(fretIndex) + stringLabelSize.width
position.y = fretSize.height * CGFloat(stringIndex)
#elseif os(OSX)
position.x = fretSize.width * CGFloat(fretIndex) + stringLabelSize.width
position.y = frame.size.height - fretSize.height - (fretSize.height * CGFloat(stringIndex))
#endif
case .vertical:
#if os(iOS) || os(tvOS)
position.x = fretSize.width * CGFloat(stringIndex) + fretLabelSize.width
position.y = fretSize.height * CGFloat(fretIndex) + stringLabelSize.height
#elseif os(OSX)
position.x = fretSize.width * CGFloat(stringIndex) + fretLabelSize.width
position.y = frame.size.height - fretSize.height - (fretSize.height * CGFloat(fretIndex)) - stringLabelSize.height
#endif
}
// Fret options
fret.note = fretboard.notes[index]
fret.direction = fretboard.direction
fret.isOpenString = fretboard.startIndex == 0 && fretIndex == 0
fret.isDrawSelectedNoteText = isDrawNoteName
fret.textColor = noteTextColor.cgColor
fret.stringLayer.strokeColor = stringColor.cgColor
fret.stringLayer.lineWidth = stringWidth
fret.fretLayer.strokeColor = fretColor.cgColor
fret.fretLayer.lineWidth = fretWidth * (fretboard.startIndex == 0 && fretIndex == 0 ? 2 : 1)
fret.noteLayer.fillColor = noteColor.cgColor
fret.frame = CGRect(origin: position, size: fretSize)
}
}
private func drawNotes() {
for (index, fret) in fretViews.enumerated() {
let fretIndex = fret.note.fretIndex
let stringIndex = fret.note.stringIndex
let note = fretboard.notes[index]
fret.note = note
if note.isSelected, isDrawCapo {
// Set note types
let notesOnFret = fretboard.notes.filter({ $0.fretIndex == fretIndex }).sorted(by: { $0.stringIndex < $1.stringIndex })
if (notesOnFret[safe: stringIndex-1] == nil || notesOnFret[safe: stringIndex-1]?.isSelected == false),
notesOnFret[safe: stringIndex+1]?.isSelected == true,
notesOnFret[safe: stringIndex+2]?.isSelected == true {
fret.noteType = .capoStart
} else if (notesOnFret[safe: stringIndex+1] == nil || notesOnFret[safe: stringIndex+1]?.isSelected == false),
notesOnFret[safe: stringIndex-1]?.isSelected == true,
notesOnFret[safe: stringIndex-2]?.isSelected == true {
fret.noteType = .capoEnd
} else if notesOnFret[safe: stringIndex-1]?.isSelected == true,
notesOnFret[safe: stringIndex+1]?.isSelected == true {
fret.noteType = .capo
} else {
fret.noteType = .default
}
// Do not draw higher notes on the same string
if isChordModeOn {
let selectedNotesOnString = fretboard.notes
.filter({ $0.stringIndex == stringIndex && $0.isSelected })
.sorted(by: { $0.fretIndex < $1.fretIndex })
if selectedNotesOnString.count > 1,
selectedNotesOnString
.suffix(from: 1)
.contains(where: { $0.fretIndex == fretIndex }) {
fret.noteType = .none
}
}
} else if note.isSelected, !isDrawCapo {
fret.noteType = .default
} else {
fret.noteType = .none
}
#if os(iOS) || os(tvOS)
fret.setNeedsLayout()
#elseif os(OSX)
fret.needsLayout = true
#endif
}
}
private func redraw() {
#if os(iOS) || os(tvOS)
setNeedsLayout()
#elseif os(OSX)
needsLayout = true
#endif
}
// MARK: FretboardDelegate
public func fretboard(_ fretboard: Fretboard, didChange: [FretboardNote]) {
setup()
drawNotes()
}
public func fretboard(_ fretboard: Fretboard, didDirectionChange: FretboardDirection) {
redraw()
}
public func fretboad(_ fretboard: Fretboard, didSelectedNotesChange: [FretboardNote]) {
drawNotes()
}
}
| 40b21bc8e84461df243dd45949c3908f | 32.372521 | 158 | 0.628199 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/views/trip overview/TKSegment+AccessoryViews.swift | apache-2.0 | 1 | //
// TKSegment+AccessoryViews.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 06.03.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
extension TKSegment {
/// Builds recommended accessory views to show for this segment in a detail
/// view.
///
/// These accessory views can include the following:
/// - `TKUITrainOccupancyView`
/// - `TKUIOccupancyView`
/// - `TKUIPathFriendlinessView`
///
/// - Returns: List of accessory view instances; can be empty
func buildAccessoryViews() -> [UIView] {
var accessoryViews: [UIView] = []
let occupancies = realTimeVehicle?.components?.map { $0.map { $0.occupancy ?? .unknown } }
if let occupancies = occupancies, occupancies.count > 1 {
let trainView = TKUITrainOccupancyView()
trainView.occupancies = occupancies
accessoryViews.append(trainView)
}
if let occupancy = realTimeVehicle?.averageOccupancy {
let occupancyView = TKUIOccupancyView(with: .occupancy(occupancy.0, title: occupancy.title))
accessoryViews.append(occupancyView)
}
if let accessibility = wheelchairAccessibility, accessibility.showInUI() {
let wheelchairView = TKUIOccupancyView(with: .wheelchair(accessibility))
accessoryViews.append(wheelchairView)
}
if canShowPathFriendliness {
let pathFriendlinessView = TKUIPathFriendlinessView.newInstance()
pathFriendlinessView.segment = self
accessoryViews.append(pathFriendlinessView)
}
return accessoryViews
}
}
| daba7f920fa9f69a8446879d06d48af8 | 28.462963 | 98 | 0.693903 | false | false | false | false |
mparrish91/gifRecipes | refs/heads/master | application/UIViewController+reddift.swift | mit | 2 | //
// UIViewController+reddift.swift
// reddift
//
// Created by sonson on 2016/09/11.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
extension UIViewController {
func createImageViewPageControllerWith(_ thumbnails: [Thumbnail], openThumbnail: Thumbnail, isOpenedBy3DTouch: Bool = false) -> ImageViewPageController {
for i in 0 ..< thumbnails.count {
if thumbnails[i].thumbnailURL == openThumbnail.thumbnailURL && thumbnails[i].parentID == openThumbnail.parentID {
return ImageViewPageController.controller(thumbnails: thumbnails, index: i, isOpenedBy3DTouch: isOpenedBy3DTouch)
}
}
return ImageViewPageController.controller(thumbnails: thumbnails, index: 0, isOpenedBy3DTouch: isOpenedBy3DTouch)
}
}
| 530c4cce61dc0e5a8d6ac6b36c365316 | 39.15 | 157 | 0.716065 | false | false | false | false |
samsao/DataProvider | refs/heads/master | Example/DataProvider/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// DataProvider
//
// Created by Guilherme Lisboa on 12/22/2015.
// Copyright (c) 2015 Guilherme Lisboa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let tabbarController = UITabBarController()
let tableVC = TableViewExampleController()
tableVC.tabBarItem = UITabBarItem(title: "TableView Example", image: UIImage(named: "TableIcon"), tag: 0)
let collectionVC = CollectionViewExampleController()
collectionVC.tabBarItem = UITabBarItem(title: "CollectionView Example", image: UIImage(named: "CollectionIcon"), tag: 1)
tabbarController.viewControllers = [UINavigationController(rootViewController: tableVC),UINavigationController(rootViewController: collectionVC)]
self.window!.rootViewController = tabbarController
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| c4a1f7291d553254e224276b43dda319 | 50.140351 | 285 | 0.748885 | false | false | false | false |
LTMana/LTPageView | refs/heads/master | LTPageVIew/LTPageVIew/LTPageView/LTPageStyle.swift | mit | 1 | //
// LTPageStyle.swift
// LTPageVIew
//
// Created by liubotong on 2017/5/8.
// Copyright © 2017年 LTMana. All rights reserved.
//
import UIKit
struct LTPageStyle{
var titleHeight:CGFloat = 44
var normalColor:UIColor = UIColor.white
var selectColor:UIColor = UIColor.orange
var titleFont : UIFont = UIFont.systemFont(ofSize: 14.0)
var isScrollEnable:Bool = false
var titleMargin:CGFloat = 20
}
| 3ebb2b9bc3209f244a4f4f5a3aeac796 | 22.555556 | 60 | 0.705189 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Serialization/inherited-initializer.swift | apache-2.0 | 32 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t -module-name InheritedInitializerBase %S/Inputs/inherited-initializer-base.swift
// RUN: %target-swift-frontend -emit-silgen -I %t %s | %FileCheck %s
import InheritedInitializerBase
class InheritsInit : Base {}
// CHECK-LABEL: sil hidden [ossa] @$s4main10testSimpleyyF
func testSimple() {
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase0C0CyACSicfcfA_
// CHECK: [[ARG:%.+]] = apply [[DEFAULT]]()
// CHECK: [[INIT:%.+]] = function_ref @$s4main12InheritsInitCyACSicfC
// CHECK: apply [[INIT]]([[ARG]], {{%.+}})
_ = InheritsInit()
// CHECK: [[VALUE:%.+]] = integer_literal $Builtin.IntLiteral, 5
// CHECK: [[ARG:%.+]] = apply {{%.+}}([[VALUE]], {{%.+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[INIT:%.+]] = function_ref @$s4main12InheritsInitCyACSicfC
// CHECK: apply [[INIT]]([[ARG]], {{%.+}})
_ = InheritsInit(5)
} // CHECK: end sil function '$s4main10testSimpleyyF'
struct Reinitializable<T>: Initializable {
init() {}
}
class GenericSub<T: Initializable> : GenericBase<T> {}
class ModifiedGenericSub<U> : GenericBase<Reinitializable<U>> {}
class NonGenericSub : GenericBase<Reinitializable<Int>> {}
// CHECK-LABEL: sil hidden [ossa] @$s4main11testGenericyyF
func testGeneric() {
// CHECK: [[TYPE:%.+]] = metatype $@thick GenericSub<Reinitializable<Int8>>.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int8>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main10GenericSubCyACyxGxcfC
// CHECK: apply [[INIT]]<Reinitializable<Int8>>({{%.+}}, [[TYPE]])
_ = GenericSub<Reinitializable<Int8>>.init() // works around SR-3806
// CHECK: [[TYPE:%.+]] = metatype $@thick ModifiedGenericSub<Int16>.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int16>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main18ModifiedGenericSubCyACyxGAA15ReinitializableVyxGcfC
// CHECK: apply [[INIT]]<Int16>({{%.+}}, [[TYPE]])
_ = ModifiedGenericSub<Int16>()
// CHECK: [[TYPE:%.+]] = metatype $@thick NonGenericSub.Type
// CHECK: [[DEFAULT:%.+]] = function_ref @$s24InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
// CHECK: apply [[DEFAULT]]<Reinitializable<Int>>({{%.+}})
// CHECK: [[INIT:%.+]] = function_ref @$s4main13NonGenericSubCyAcA15ReinitializableVySiGcfC
// CHECK: apply [[INIT]]({{%.+}}, [[TYPE]])
_ = NonGenericSub()
} // CHECK: end sil function '$s4main11testGenericyyF'
| 38318071870f5313cc7d9afd7fea0bb9 | 48.462963 | 130 | 0.666043 | false | true | false | false |
iAugux/Weboot | refs/heads/master | Weboot/PanDirectionGestureRecognizer+Addtions.swift | mit | 1 | //
// PanDirectionGestureRecognizer+Addtions.swift
// TinderSwipeCellSwift
//
// Created by Augus on 8/23/15.
// Copyright © 2015 iAugus. All rights reserved.
// http://stackoverflow.com/a/30607392/4656574
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum PanDirection {
case Vertical
case Horizontal
}
class PanDirectionGestureRecognizer: UIPanGestureRecognizer {
let direction : PanDirection
init(direction: PanDirection, target: AnyObject, action: Selector) {
self.direction = direction
super.init(target: target, action: action)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if state == .Began {
let velocity = velocityInView(self.view!)
switch direction {
// disable local gesture when locationInView < 44 to ensure UIScreenEdgePanGestureRecognizer is only avalible
// The comfortable minimum size of tappable UI elements is 44 x 44 points.
case .Horizontal where fabs(velocity.y) > fabs(velocity.x) || locationInView(self.view).x <= 44:
state = .Cancelled
case .Vertical where fabs(velocity.x) > fabs(velocity.y):
state = .Cancelled
default:
break
}
}
}
} | 6c9d91ca9daebf4a02a8abb81126d5a5 | 31.045455 | 125 | 0.638041 | false | false | false | false |
nzaghini/b-viper | refs/heads/master | WeatherTests/Modules/WeatherLocation/WeatherLocationDefaultPresenterMapperSpec.swift | mit | 2 | import Nimble
import Quick
@testable import Weather
class WeatherLocationDefaultPresenterMapperSpec: QuickSpec {
var viewModelBuilder: SelectableLocationListViewModelBuilder!
override func spec() {
beforeEach {
self.viewModelBuilder = SelectableLocationListViewModelBuilder()
}
context("When building with a list of locations") {
it("Should return one view model") {
let location = Location.locationWithIndex(1)
let viewModel = self.viewModelBuilder.buildViewModel([location])
expect(viewModel.locations[0].locationId).to(equal(location.locationId))
expect(viewModel.locations[0].name).to(equal(location.name))
expect(viewModel.locations[0].detail).to(equal("Region1, Country1"))
}
}
context("When mapping a map location without region") {
it("Should return a view model with a detail that contains only the country") {
let location = Location(locationId: "id", name: "name", region: "", country: "country", latitude: nil, longitude: nil)
let viewModel = self.viewModelBuilder.buildViewModel([location])
expect(viewModel.locations[0].detail).to(equal("country"))
}
}
}
}
| 4affaae1693d42888509949461cc4df9 | 38.222222 | 134 | 0.596317 | false | false | false | false |
PangPangPangPangPang/MXPlayer | refs/heads/master | Source/MXPlayerViewController.swift | mit | 1 | //
// MXPlayerViewController.swift
// MXPlayer
//
// Created by Max Wang on 16/5/20.
// Copyright © 2016年 Max Wang. All rights reserved.
//
import UIKit
import AVFoundation
typealias MXPlayerViewSubClazzImp = MXPlayerViewController
class MXPlayerViewController: UIViewController,MXPlayerCallBack, MXPlayerProtocol,MXPlayerSubClazzProtocol {
var url: NSURL?
var player: MXPlayer!
var playerView: MXPlayerView!
var currentTime: NSTimeInterval! = 0
var duration: NSTimeInterval! = 0
var playableDuration: NSTimeInterval! = 0
var loadState: MXPlayerLoadState! = .unknown
var originFrame: CGRect! {
didSet {
playerView.frame = originFrame
}
}
var scalingMode: MXPlayerScaleMode! {
didSet {
let layer = playerView.layer as! AVPlayerLayer
switch scalingMode as MXPlayerScaleMode {
case .none, .aspectFit:
layer.videoGravity = AVLayerVideoGravityResizeAspect
break
case .aspectFill:
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
break
case .Fill:
layer.videoGravity = AVLayerVideoGravityResize
break
}
}
}
var shouldAutoPlay: Bool! = false
var allowsMediaAirPlay :Bool! = false
var isDanmakuMediaAirPlay: Bool! = false
var airPlayMediaActive: Bool! = false
var playbackRate: Float! = 0
var bufferState: MXPlayerBufferState! {
didSet {
switch bufferState as MXPlayerBufferState {
case .unknown:
break
case .empty:
self.playableBufferBecomeEmpty()
break
case .keepUp:
self.playableBufferBecomeKeepUp()
break
case .full:
break
}
print("bufferState:\(bufferState)")
}
}
var orientationLandScapeRight: Bool! {
didSet {
let value: Int!
if orientationLandScapeRight == true {
value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
playerView.frame = UIScreen.mainScreen().bounds
} else {
value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
playerView.frame = originFrame
}
}
}
var movieState: MXPlayerMovieState! {
didSet {
print(movieState)
}
}
var canPlayFastForward: Bool? {
get {
return self.player.currentItem?.canPlayFastForward
}
}
var canPlaySlowForward: Bool? {
get {
return self.player.currentItem?.canPlaySlowForward
}
}
var canPlayFastReverse: Bool? {
get {
return self.player.currentItem?.canPlayFastReverse
}
}
var canPlaySlowReverse: Bool? {
get {
return self.player.currentItem?.canPlaySlowReverse
}
}
init(url: NSURL?) {
super.init(nibName: nil, bundle: nil)
self.url = url
orientationLandScapeRight = false
scalingMode = .Fill
bufferState = .unknown
movieState = .stopped
AudioSessionManager.shareInstance.audioSession()
self.prepareToplay(self.url)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MXPlayerViewController {
func playerObserver(item: AVPlayerItem?, keyPath: String?, change: [String : AnyObject]?) {
switch keyPath! {
case "status":
do {
let status = change![NSKeyValueChangeNewKey] as! Int
switch status {
case AVPlayerItemStatus.ReadyToPlay.rawValue:
loadState = .playable
duration = player.duration
break
case AVPlayerItemStatus.Failed.rawValue:
loadState = .failed
break
default:
break
}
}
break
case "loadedTimeRanges":
do {
playableDuration = player.availableDuration()
self.playableDurationDidChange()
}
break
case "playbackBufferFull":
do {
bufferState = .full
}
break
case "playbackLikelyToKeepUp":
do {
bufferState = .keepUp
loadState = .playable
}
break
case "playbackBufferEmpty":
do {
bufferState = .empty
}
break;
default:
break
}
}
func playerPlayWithTime(time: CMTime) {
guard duration != 0 else {return}
currentTime = CMTimeGetSeconds(time)
playbackRate = Float(currentTime) / Float(duration)
self.playDurationDidChange(playbackRate, second: currentTime)
}
}
extension MXPlayerViewController {
func prepareToplay(url: NSURL?) -> Void {
let item = AVPlayerItem.init(URL: url ?? self.url!);
if player == nil {
player = MXPlayer.init(item: item, delegate: self)
playerView = MXPlayerView.init(player: player, frame: self.view.bounds);
originFrame = playerView.frame
playerView.userInteractionEnabled = false
self.view.addSubview(playerView)
self.view.insertSubview(playerView, atIndex: 0)
} else {
self.pause()
player.changePlayerItem(item)
self.play()
}
}
func play() -> Void {
if loadState == MXPlayerLoadState.playable
&& movieState != MXPlayerMovieState.playing {
player.play()
movieState = .playing
}
}
func pause() -> Void {
player.pause()
movieState = .paused
}
func stop() -> Void {
player.setRate(0, time: kCMTimeInvalid, atHostTime: kCMTimeInvalid)
movieState = .stopped
}
func isPlayer() -> Bool {
return movieState == MXPlayerMovieState.playing
}
func shutDown() -> Void {
}
func switchScaleMode(mode: MXPlayerScaleMode!) -> Void {
scalingMode = mode
}
func flashImage() -> UIImage {
return UIImage()
}
func seekToTime(time: NSTimeInterval) -> Void {
player.seekToTime(CMTimeMakeWithSeconds(time, Int32(kCMTimeMaxTimescale)),
toleranceBefore: CMTimeMakeWithSeconds(0.2, Int32(kCMTimeMaxTimescale)),
toleranceAfter: CMTimeMakeWithSeconds(0.2, Int32(kCMTimeMaxTimescale))) {
(result) in
print(result)
}
}
}
extension MXPlayerViewSubClazzImp {
func playableDurationDidChange() {}
func playDurationDidChange(rate: Float, second: NSTimeInterval) {}
func playableBufferBecomeEmpty() {}
func playableBufferBecomeKeepUp() {}
}
| fee4e2d5e4a98842f9cd8db06edff5c5 | 28.785425 | 108 | 0.558923 | false | false | false | false |
jasnig/ScrollPageView | refs/heads/master | ScrollViewController/other/TestController.swift | mit | 1 | //
// TestController.swift
// ScrollViewController
//
// Created by jasnig on 16/4/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class TestController: UIViewController {
// storyBoard中的controller初始化会调用这个初始化方法, 在这里面注册通知监听者
// 如果在viewDidLoad()里面注册第一次出现的时候接受不到通知, 这个在oc里面是没有问题的, 很无奈
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.didSelectIndex(_:)), name: ScrollPageViewDidShowThePageNotification, object: nil)
}
func didSelectIndex(noti: NSNotification) {
let userInfo = noti.userInfo!
//注意键名是currentIndex
print(userInfo["currentIndex"])
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
print("\(self.debugDescription) --- 销毁")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func btnOnClick(sender: UIButton) {
let testSelectedVc = TestSelectedIndexController()
testSelectedVc.backClosure = {[weak self] in
guard let strongSelf = self else { return }
// 或者通过navigationController 的stack 来获取到指定的控制器
if let vc9Controller = strongSelf.parentViewController as? Vc9Controller {
// 返回的时候设置其他页为选中页
vc9Controller.scrollPageView.selectedIndex(3, animated: true)
}
if let vc6Controller = strongSelf.parentViewController as? Vc6Controller {
// 返回的时候设置其他页为选中页
vc6Controller.reloadChildVcs()
}
let rootNav = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController
rootNav?.popViewControllerAnimated(true)
}
showViewController(testSelectedVc, sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class Test1Controller: PageTableViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承1-----------------\(indexPath.row)"
return cell
}
}
class Test2Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承2--------------\(indexPath.row)"
return cell
}
}
class Test3Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承3--------------\(indexPath.row)"
return cell
}
}
class Test4Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承4--------------\(indexPath.row)"
return cell
}
}
class Test5Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承5--------------\(indexPath.row)"
return cell
}
}
class Test6Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承6--------------\(indexPath.row)"
return cell
}
}
class Test7Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承7--------------\(indexPath.row)"
return cell
}
}
class Test8Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承8--------------\(indexPath.row)"
return cell
}
}
class Test9Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承9--------------\(indexPath.row)"
return cell
}
}
class Test10Controller: PageTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellId")
cell.textLabel?.text = "继承10--------------"
return cell
}
}
| 7413b5cc1aaa5cbf84e86ad15d4b2a71 | 31.577963 | 169 | 0.665475 | false | false | false | false |
DashiDashCam/iOS-App | refs/heads/master | Dashi/Dashi/Controllers/VideosTableViewController.swift | mit | 1 | //
// VideosTableViewController.swift
// Dashi
//
// Created by Arslan Memon on 10/31/17.
// Copyright © 2017 Senior Design. All rights reserved.
//
import UIKit
import Photos
import CoreMedia
import CoreData
import PromiseKit
import SwiftyJSON
import MapKit
import SVGKit
class VideosTableViewController: UITableViewController {
var videos: [Video] = []
var timer: Timer?
let appDelegate =
UIApplication.shared.delegate as? AppDelegate
// get's video metadata from local db and cloud
override func viewDidLoad() {
super.viewDidLoad()
getMetaData()
// navigation bar and back button
navigationController?.isNavigationBarHidden = false
// override back button to ensure it always returns to the home screen
if let rootVC = navigationController?.viewControllers.first {
navigationController?.viewControllers = [rootVC, self]
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_: Bool) {
self.tableView.reloadData()
// set orientation
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
// lock orientation
AppUtility.lockOrientation(.portrait)
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true){_ in
let cells = self.tableView.visibleCells as! Array<VideoTableViewCell>
self.tableView.beginUpdates()
var indexToRemove : IndexPath? = nil
for cell in cells{
let indexPath = self.tableView.indexPath(for: cell)
let row = indexPath?.row
//prevent code from firing if video was deleted in videoDetail
if(!self.videos[row!].wasDeleted()){
cell.storageIcon.image = UIImage(named: self.videos[row!].getStorageStat()) // idk why, but don't delete this
// set storage image based off stat
var storageImage: SVGKImage
let storageStat = self.videos[row!].getStorageStat()
cell.location.text = self.videos[row!].getLocation()
// video hasn't been uploaded
if storageStat == "local" {
storageImage = SVGKImage(named: "local")
} else {
storageImage = SVGKImage(named: "cloud")
}
cell.storageIcon.image = storageImage.uiImage
if self.videos[row!].getDownloadInProgress() {
var namSvgImgVar: SVGKImage = SVGKImage(named: "download")
cell.uploadDownloadIcon.image = namSvgImgVar.uiImage
cell.uploadDownloadIcon.isHidden = false
} else if self.videos[row!].getUploadInProgress() {
var namSvgImgVar: SVGKImage = SVGKImage(named: "upload")
cell.uploadDownloadIcon.image = namSvgImgVar.uiImage
cell.uploadDownloadIcon.isHidden = false
} else {
cell.uploadDownloadIcon.isHidden = true
}
}
else{
indexToRemove = indexPath
}
}
//I am assuming it is impossible for a user to be able to delete more than one video
//in under 0.5 seconds, so only 1 cell will ever need to be removed at a time
if(indexToRemove != nil){
self.videos.remove(at: (indexToRemove?.row)!)
self.tableView.deleteRows(at: [indexToRemove!], with: .automatic)
}
self.tableView.endUpdates()
}
timer?.fire()
}
override func viewWillDisappear(_ animated: Bool) {
timer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
// returns the number of sections(types of cells) that are going to be in the table to the table view controller
override func numberOfSections(in _: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
// returns how many of each type of cell the table has
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return videos.count
}
// allows a row to be deleted
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func getMetaData() {
var fetchedmeta: [NSManagedObject] = []
let managedContext =
appDelegate?.persistentContainer.viewContext
// 2
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Videos")
fetchRequest.predicate = NSPredicate(format: "accountID == %d", (sharedAccount?.getId())!)
fetchRequest.propertiesToFetch = ["startDate", "length", "size", "thumbnail", "id", "startLat", "startLong", "endLat", "endLong", "locationName"]
// 3
do {
fetchedmeta = (try managedContext?.fetch(fetchRequest))!
} catch let error as Error {
print("Could not fetch. \(error), \(error.localizedDescription)")
}
for meta in fetchedmeta {
var video: Video
let id = meta.value(forKey: "id") as! String
let date = meta.value(forKey: "startDate") as! Date
let thumbnailData = meta.value(forKey: "thumbnail") as! Data
let size = meta.value(forKey: "size") as! Int
let length = meta.value(forKey: "length") as! Int
let startLat = meta.value(forKey: "startLat") as! CLLocationDegrees?
let startLong = meta.value(forKey: "startLong") as! CLLocationDegrees?
let endLat = meta.value(forKey: "endLat") as! CLLocationDegrees?
let endLong = meta.value(forKey: "endLong") as! CLLocationDegrees?
let locationName = meta.value(forKey: "locationName") as! String?
if let lat1 = startLat, let lat2 = endLat, let long1 = startLong, let long2 = endLong{
// dates.append(video.value(forKeyPath: "startDate") as! Date)
video = Video(started: date, imageData: thumbnailData, id: id, length: length, size: size, startLoc: CLLocationCoordinate2D(latitude: lat1, longitude: long1), endLoc: CLLocationCoordinate2D(latitude: lat2, longitude: long2), locationName: locationName )
}
else{
video = Video(started: date, imageData: thumbnailData, id: id, length: length, size: size, startLoc: nil, endLoc: nil, locationName: locationName )
}
videos.append(video)
}
videos.sort(by: { $0.getStarted() > $1.getStarted() })
}
// sets cell data for each video
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: "vidCell2", for: indexPath) as! VideoTableViewCell
let dateFormatter = DateFormatter()
// US English Locale (en_US)
dateFormatter.dateFormat = "MMMM dd"
// dateFormatter.timeStyle = .short
cell.thumbnail.image = videos[row].getThumbnail()
cell.date.text = dateFormatter.string(from: videos[row].getStarted())
cell.location.text = videos[row].getLocation()
// set time
dateFormatter.dateFormat = "hh:mm a"
cell.time.text = dateFormatter.string(from: videos[row].getStarted())
cell.id = videos[row].getId()
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let preview = segue.destination as! VideoDetailViewController
let row = (tableView.indexPath(for: (sender as! UITableViewCell))?.row)!
let selectedVideo = videos[row]
preview.selectedVideo = selectedVideo
}
// pass the id of a desired video to delete it from core data
func deleteLocal(id: String) {
var content: [NSManagedObject]
let managedContext =
appDelegate?.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Videos")
fetchRequest.propertiesToFetch = ["videoContent"]
fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id, (sharedAccount?.getId())!)
do {
content = (try managedContext?.fetch(fetchRequest))!
managedContext?.delete(content[0])
do {
// commit changes to context
try managedContext!.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.localizedDescription)")
return
}
}
}
| 6f29d614fa05e29b42c757ad810c6f2e | 40.106227 | 270 | 0.611567 | false | false | false | false |
vauxhall/worldcities | refs/heads/master | worldcities/Model/ModelListSearch.swift | mit | 1 | import Foundation
extension ModelList
{
private static let kStringEmpty:String = ""
private static let kStringSpace:String = " "
private static let kStringNewLine:String = "\n"
private static let kStringTab:String = "\t"
private static let kStringReturn:String = "\r"
private class func cleanInput(input:String) -> String
{
var cleaned:String = input.lowercased()
cleaned = cleaned.replacingOccurrences(
of:kStringSpace,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringNewLine,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringTab,
with:kStringEmpty)
cleaned = cleaned.replacingOccurrences(
of:kStringReturn,
with:kStringEmpty)
return cleaned
}
//MARK: internal
func searchItems(forInput:String) -> [ModelListItem]
{
let cleanedInput:String = ModelList.cleanInput(
input:forInput)
let countCharacters:Int = cleanedInput.characters.count
let items:[ModelListItem]
if countCharacters > 0
{
items = mappedItems(withString:cleanedInput)
}
else
{
items = self.items
}
return items
}
//MARK: private
private func mappedItems(withString:String) -> [ModelListItem]
{
guard
let items:[ModelListItem] = itemsMap[withString]
else
{
return []
}
return items
}
}
| 3e30cf0d5916897e11cac67bdf90f0d7 | 24.136364 | 66 | 0.566606 | false | false | false | false |
itechline/bonodom_new | refs/heads/master | SlideMenuControllerSwift/MyEstatesCell.swift | mit | 1 | //
// MyEstatesCell.swift
// Bonodom
//
// Created by Attila Dán on 2016. 07. 20..
// Copyright © 2016. Itechline. All rights reserved.
//
import UIKit
import SwiftyJSON
import SDWebImage
struct MyEstatesCellData {
init(id: Int, imageUrl: String, adress: String, description: String, row: Int) {
self.id = id
self.imageUrl = imageUrl
self.adress = adress
self.description = description
self.row = row
}
var id: Int
var imageUrl: String
var adress: String
var description: String
var row: Int
}
class MyEstatesCell : BaseTableViewCell {
var id : Int!
var row : Int!
let screensize = UIScreen.mainScreen().bounds
@IBOutlet weak var cellWidth: NSLayoutConstraint!
@IBOutlet weak var modifyHeight: NSLayoutConstraint!
@IBOutlet weak var modifyWidth: NSLayoutConstraint!
@IBOutlet weak var deleteHeight: NSLayoutConstraint!
@IBOutlet weak var deleteWidth: NSLayoutConstraint!
@IBOutlet weak var upWidth: NSLayoutConstraint!
@IBOutlet weak var upHeight: NSLayoutConstraint!
@IBOutlet weak var adress_text: UILabel!
@IBOutlet weak var description_text: UILabel!
@IBOutlet weak var estate_image: UIImageView!
@IBOutlet weak var up_text: UIButton!
@IBAction func up_button(sender: AnyObject) {
}
@IBOutlet weak var modify_text: UIButton!
@IBAction func modify_button(sender: AnyObject) {
let mod: [String:AnyObject] = [ "mod": "1", "row": String(row!)]
NSNotificationCenter.defaultCenter().postNotificationName("estate_adding", object: mod)
}
@IBOutlet weak var delete_text: UIButton!
@IBAction func delete_button(sender: AnyObject) {
let del_id: [String:AnyObject] = [ "del_id":String(id!), "row":String(row!)]
NSNotificationCenter.defaultCenter().postNotificationName("delete_estate", object: del_id)
/*EstateUtil.sharedInstance.delete_estate(String(self.id), onCompletion: { (json: JSON) in
print ("DELETE ESTATE")
print (json)
dispatch_async(dispatch_get_main_queue(),{
if (!json["error"].boolValue) {
} else {
}
})
})*/
}
override func awakeFromNib() {
//self.dataText?.font = UIFont.boldSystemFontOfSize(16)
//self.dataText?.textColor = UIColor(hex: "000000")
let iconsize = (((screensize.width)-estate_image.frame.width)-20)/5
let iconwidth = (((screensize.width)-estate_image.frame.width)-20)/4
cellWidth.constant = screensize.width
modifyWidth.constant = iconwidth
modifyHeight.constant = iconsize
deleteWidth.constant = iconwidth
deleteHeight.constant = iconsize
upWidth.constant = iconwidth
upHeight.constant = iconsize
print("iconsize: ", iconsize)
}
override class func height() -> CGFloat {
return 170
}
override func setData(data: Any?) {
if let data = data as? MyEstatesCellData {
if (data.imageUrl != "") {
let url: NSURL = NSURL(string: data.imageUrl)!
self.estate_image.sd_setImageWithURL(url)
} else {
self.estate_image.image = UIImage(named: "noimage")
}
self.estate_image.sizeThatFits(CGSize.init(width: 116.0, height: 169.0))
self.adress_text.text = data.adress
self.description_text.text = data.description
self.row = data.row
self.id = data.id
self.delete_text.layer.cornerRadius = 3
self.delete_text.layer.borderColor = UIColor.redColor().CGColor
self.delete_text.layer.borderWidth = 1
self.modify_text.layer.cornerRadius = 3
self.modify_text.layer.borderColor = UIColor.blueColor().CGColor
self.modify_text.layer.borderWidth = 1
//00D548 -> UP BUTTON COLOR
self.up_text.layer.cornerRadius = 3
self.up_text.layer.borderColor = UIColor(hex: "00D548").CGColor
self.up_text.layer.borderWidth = 1
}
}
}
| 175202f5c763502323cdaf3ac02918cb | 30.264286 | 98 | 0.594243 | false | false | false | false |
Antondomashnev/Sourcery | refs/heads/master | Pods/Yams/Sources/Yams/Tag.swift | mit | 3 | //
// Tag.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
import CYaml
#endif
import Foundation
public final class Tag {
public struct Name: RawRepresentable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
public static var implicit: Tag {
return Tag(.implicit)
}
// internal
let constructor: Constructor
var name: Name
public init(_ name: Name,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) {
self.resolver = resolver
self.constructor = constructor
self.name = name
}
func resolved<T>(with value: T) -> Tag where T: TagResolvable {
if name == .implicit {
name = resolver.resolveTag(of: value)
} else if name == .nonSpecific {
name = T.defaultTagName
}
return self
}
// fileprivate
fileprivate let resolver: Resolver
}
extension Tag: CustomStringConvertible {
public var description: String {
return name.rawValue
}
}
extension Tag: Hashable {
public var hashValue: Int {
return name.hashValue
}
public static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.name == rhs.name
}
}
extension Tag.Name: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.rawValue = value
}
public init(unicodeScalarLiteral value: String) {
self.rawValue = value
}
public init(extendedGraphemeClusterLiteral value: String) {
self.rawValue = value
}
}
extension Tag.Name: Hashable {
public var hashValue: Int {
return rawValue.hashValue
}
public static func == (lhs: Tag.Name, rhs: Tag.Name) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
// http://www.yaml.org/spec/1.2/spec.html#Schema
extension Tag.Name {
// Special
/// Tag should be resolved by value.
public static let implicit: Tag.Name = ""
/// Tag should not be resolved by value, and be resolved as .str, .seq or .map.
public static let nonSpecific: Tag.Name = "!"
// Failsafe Schema
/// "tag:yaml.org,2002:str" <http://yaml.org/type/str.html>
public static let str: Tag.Name = "tag:yaml.org,2002:str"
/// "tag:yaml.org,2002:seq" <http://yaml.org/type/seq.html>
public static let seq: Tag.Name = "tag:yaml.org,2002:seq"
/// "tag:yaml.org,2002:map" <http://yaml.org/type/map.html>
public static let map: Tag.Name = "tag:yaml.org,2002:map"
// JSON Schema
/// "tag:yaml.org,2002:bool" <http://yaml.org/type/bool.html>
public static let bool: Tag.Name = "tag:yaml.org,2002:bool"
/// "tag:yaml.org,2002:float" <http://yaml.org/type/float.html>
public static let float: Tag.Name = "tag:yaml.org,2002:float"
/// "tag:yaml.org,2002:null" <http://yaml.org/type/null.html>
public static let null: Tag.Name = "tag:yaml.org,2002:null"
/// "tag:yaml.org,2002:int" <http://yaml.org/type/int.html>
public static let int: Tag.Name = "tag:yaml.org,2002:int"
// http://yaml.org/type/index.html
/// "tag:yaml.org,2002:binary" <http://yaml.org/type/binary.html>
public static let binary: Tag.Name = "tag:yaml.org,2002:binary"
/// "tag:yaml.org,2002:merge" <http://yaml.org/type/merge.html>
public static let merge: Tag.Name = "tag:yaml.org,2002:merge"
/// "tag:yaml.org,2002:omap" <http://yaml.org/type/omap.html>
public static let omap: Tag.Name = "tag:yaml.org,2002:omap"
/// "tag:yaml.org,2002:pairs" <http://yaml.org/type/pairs.html>
public static let pairs: Tag.Name = "tag:yaml.org,2002:pairs"
/// "tag:yaml.org,2002:set". <http://yaml.org/type/set.html>
public static let set: Tag.Name = "tag:yaml.org,2002:set"
/// "tag:yaml.org,2002:timestamp" <http://yaml.org/type/timestamp.html>
public static let timestamp: Tag.Name = "tag:yaml.org,2002:timestamp"
/// "tag:yaml.org,2002:value" <http://yaml.org/type/value.html>
public static let value: Tag.Name = "tag:yaml.org,2002:value"
/// "tag:yaml.org,2002:yaml" <http://yaml.org/type/yaml.html> We don't support this.
public static let yaml: Tag.Name = "tag:yaml.org,2002:yaml"
}
protocol TagResolvable {
var tag: Tag { get }
static var defaultTagName: Tag.Name { get }
func resolveTag(using resolver: Resolver) -> Tag.Name
}
extension TagResolvable {
var resolvedTag: Tag {
return tag.resolved(with: self)
}
func resolveTag(using resolver: Resolver) -> Tag.Name {
return tag.name == .implicit ? Self.defaultTagName : tag.name
}
}
| 9731ee881b78a50d2d3a7384e534924c | 31.135135 | 88 | 0.631623 | false | false | false | false |
oarrabi/Guaka-Generator | refs/heads/master | Tests/GuakaClILibTests/MockTypes.swift | mit | 1 | //
// MockDirectoryType.swift
// guaka-cli
//
// Created by Omar Abdelhafith on 27/11/2016.
//
//
@testable import GuakaClILib
struct MockDirectoryType: DirectoryType {
static var currentDirectory: String = ""
static var pathsCreated: [String] = []
static var pathsEmptyValue: [String: Bool] = [:]
static var pathsCreationValue: [String: Bool] = [:]
static var pathsValidationValue: [String: Bool] = [:]
static var pathsExistanceValue: [String: Bool] = [:]
static func clear() {
currentDirectory = ""
pathsCreated = []
pathsEmptyValue = [:]
pathsCreationValue = [:]
pathsValidationValue = [:]
pathsExistanceValue = [:]
}
static func isEmpty(directoryPath: String) -> Bool {
return pathsEmptyValue[directoryPath] ?? false
}
static func create(atPath path: String) -> Bool {
pathsCreated.append(path)
return pathsCreationValue[path] ?? false
}
static func isValidDirectory(atPath path: String) -> Bool {
return pathsValidationValue[path] ?? false
}
static func exists(atPath path: String) -> Bool {
return pathsExistanceValue[path] ?? false
}
}
struct MockFileType: FileType {
static var fileExistanceValue: [String: Bool] = [:]
static var fileReadValue: [String: String] = [:]
static var fileWriteValue: [String: Bool] = [:]
static var writtenFiles: [String: String] = [:]
static func clear() {
fileExistanceValue = [:]
fileReadValue = [:]
fileWriteValue = [:]
writtenFiles = [:]
}
static func write(string: String, toFile file: String) -> Bool {
writtenFiles[file] = string
return fileWriteValue[file] ?? false
}
static func read(fromFile file: String) -> String? {
return fileReadValue[file]
}
static func exists(atPath path: String) -> Bool {
return fileExistanceValue[path] ?? false
}
}
| a045a13a27ceecf0727550540c13e0d0 | 23.573333 | 66 | 0.66739 | false | false | false | false |
nostramap/nostra-sdk-sample-ios | refs/heads/master | SearchSample/Swift/SearchSample/MapResultViewController.swift | apache-2.0 | 1 | //
// MapResultViewController.swift
// SearchSample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
import ArcGIS
class MapResultViewController: UIViewController, AGSLayerDelegate, AGSCalloutDelegate, AGSMapViewLayerDelegate {
let referrer = ""
@IBOutlet weak var mapView: AGSMapView!
var result: NTLocationSearchResult!;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.initializeMap();
}
//MARK: Callout delegate
func callout(_ callout: AGSCallout!, willShowFor feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
callout.title = result!.name_L;
callout.detail = "\(result!.adminLevel3_L), \(result!.adminLevel2_L), \(result!.adminLevel1_L)"
return true;
}
//MARK: layer delegate
func layerDidLoad(_ layer: AGSLayer!) {
if result != nil {
let point = AGSPoint(x: result.lon, y: result.lat, spatialReference: AGSSpatialReference.wgs84());
let mappoint = AGSPoint(fromDegreesDecimalMinutesString: point?.decimalDegreesString(withNumDigits: 7),
with: AGSSpatialReference.webMercator());
mapView.zoom(toScale: 10000, withCenter: mappoint, animated: true);
let graphicLayer = AGSGraphicsLayer();
mapView.addMapLayer(graphicLayer);
let symbol = AGSPictureMarkerSymbol(imageNamed: "pin_map");
let graphic = AGSGraphic(geometry: mappoint, symbol: symbol, attributes: nil);
graphicLayer.addGraphic(graphic);
mapView.callout.show(at: mappoint, for: graphic, layer: graphicLayer, animated: true);
}
}
func initializeMap() {
mapView.callout.delegate = self;
do {
// Get map permisson.
let resultSet = try NTMapPermissionService.execute();
// Get Street map HD (service id: 2)
if resultSet.results != nil && resultSet.results.count > 0 {
let filtered = resultSet.results.filter({ (mp) -> Bool in
return mp.serviceId == 2;
})
if filtered.count > 0 {
let mapPermisson = filtered.first;
let url = URL(string: mapPermisson!.serviceUrl_L);
let cred = AGSCredential(token: mapPermisson?.serviceToken_L, referer: referrer);
let tiledLayer = AGSTiledMapServiceLayer(url: url, credential: cred)
tiledLayer?.delegate = self;
mapView.addMapLayer(tiledLayer, withName: mapPermisson!.serviceName);
}
}
}
catch let error as NSError {
print("error: \(error)");
}
}
func layer(_ layer: AGSLayer!, didFailToLoadWithError error: Error!) {
print("\(layer.name) failed to load by reason: \(error)");
}
}
| 9534cc3df218f8bdb8287fab9c93e908 | 32.639175 | 123 | 0.560527 | false | false | false | false |
IngmarStein/swift | refs/heads/master | benchmark/single-source/SortStrings.swift | apache-2.0 | 3 | //===--- SortStrings.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Sort an array of strings using an explicit sort predicate.
var stringBenchmarkWords: [String] = [
"woodshed",
"lakism",
"gastroperiodynia",
"afetal",
"ramsch",
"Nickieben",
"undutifulness",
"birdglue",
"ungentlemanize",
"menacingly",
"heterophile",
"leoparde",
"Casearia",
"decorticate",
"neognathic",
"mentionable",
"tetraphenol",
"pseudonymal",
"dislegitimate",
"Discoidea",
"intitule",
"ionium",
"Lotuko",
"timbering",
"nonliquidating",
"oarialgia",
"Saccobranchus",
"reconnoiter",
"criminative",
"disintegratory",
"executer",
"Cylindrosporium",
"complimentation",
"Ixiama",
"Araceae",
"silaginoid",
"derencephalus",
"Lamiidae",
"marrowlike",
"ninepin",
"dynastid",
"lampfly",
"feint",
"trihemimer",
"semibarbarous",
"heresy",
"tritanope",
"indifferentist",
"confound",
"hyperbolaeon",
"planirostral",
"philosophunculist",
"existence",
"fretless",
"Leptandra",
"Amiranha",
"handgravure",
"gnash",
"unbelievability",
"orthotropic",
"Susumu",
"teleutospore",
"sleazy",
"shapeliness",
"hepatotomy",
"exclusivism",
"stifler",
"cunning",
"isocyanuric",
"pseudepigraphy",
"carpetbagger",
"respectiveness",
"Jussi",
"vasotomy",
"proctotomy",
"ovatotriangular",
"aesthetic",
"schizogamy",
"disengagement",
"foray",
"haplocaulescent",
"noncoherent",
"astrocyte",
"unreverberated",
"presenile",
"lanson",
"enkraal",
"contemplative",
"Syun",
"sartage",
"unforgot",
"wyde",
"homeotransplant",
"implicational",
"forerunnership",
"calcaneum",
"stomatodeum",
"pharmacopedia",
"preconcessive",
"trypanosomatic",
"intracollegiate",
"rampacious",
"secundipara",
"isomeric",
"treehair",
"pulmonal",
"uvate",
"dugway",
"glucofrangulin",
"unglory",
"Amandus",
"icterogenetic",
"quadrireme",
"Lagostomus",
"brakeroot",
"anthracemia",
"fluted",
"protoelastose",
"thro",
"pined",
"Saxicolinae",
"holidaymaking",
"strigil",
"uncurbed",
"starling",
"redeemeress",
"Liliaceae",
"imparsonee",
"obtusish",
"brushed",
"mesally",
"probosciformed",
"Bourbonesque",
"histological",
"caroba",
"digestion",
"Vindemiatrix",
"triactinal",
"tattling",
"arthrobacterium",
"unended",
"suspectfulness",
"movelessness",
"chartist",
"Corynebacterium",
"tercer",
"oversaturation",
"Congoleum",
"antiskeptical",
"sacral",
"equiradiate",
"whiskerage",
"panidiomorphic",
"unplanned",
"anilopyrine",
"Queres",
"tartronyl",
"Ing",
"notehead",
"finestiller",
"weekender",
"kittenhood",
"competitrix",
"premillenarian",
"convergescence",
"microcoleoptera",
"slirt",
"asteatosis",
"Gruidae",
"metastome",
"ambuscader",
"untugged",
"uneducated",
"redistill",
"rushlight",
"freakish",
"dosology",
"papyrine",
"iconologist",
"Bidpai",
"prophethood",
"pneumotropic",
"chloroformize",
"intemperance",
"spongiform",
"superindignant",
"divider",
"starlit",
"merchantish",
"indexless",
"unidentifiably",
"coumarone",
"nomism",
"diaphanous",
"salve",
"option",
"anallantoic",
"paint",
"thiofurfuran",
"baddeleyite",
"Donne",
"heterogenicity",
"decess",
"eschynite",
"mamma",
"unmonarchical",
"Archiplata",
"widdifow",
"apathic",
"overline",
"chaetophoraceous",
"creaky",
"trichosporange",
"uninterlined",
"cometwise",
"hermeneut",
"unbedraggled",
"tagged",
"Sminthurus",
"somniloquacious",
"aphasiac",
"Inoperculata",
"photoactivity",
"mobship",
"unblightedly",
"lievrite",
"Khoja",
"Falerian",
"milfoil",
"protectingly",
"householder",
"cathedra",
"calmingly",
"tordrillite",
"rearhorse",
"Leonard",
"maracock",
"youngish",
"kammererite",
"metanephric",
"Sageretia",
"diplococcoid",
"accelerative",
"choreal",
"metalogical",
"recombination",
"unimprison",
"invocation",
"syndetic",
"toadback",
"vaned",
"cupholder",
"metropolitanship",
"paramandelic",
"dermolysis",
"Sheriyat",
"rhabdus",
"seducee",
"encrinoid",
"unsuppliable",
"cololite",
"timesaver",
"preambulate",
"sampling",
"roaster",
"springald",
"densher",
"protraditional",
"naturalesque",
"Hydrodamalis",
"cytogenic",
"shortly",
"cryptogrammatical",
"squat",
"genual",
"backspier",
"solubleness",
"macroanalytical",
"overcovetousness",
"Natalie",
"cuprobismutite",
"phratriac",
"Montanize",
"hymnologist",
"karyomiton",
"podger",
"unofficiousness",
"antisplasher",
"supraclavicular",
"calidity",
"disembellish",
"antepredicament",
"recurvirostral",
"pulmonifer",
"coccidial",
"botonee",
"protoglobulose",
"isonym",
"myeloid",
"premiership",
"unmonopolize",
"unsesquipedalian",
"unfelicitously",
"theftbote",
"undauntable",
"lob",
"praenomen",
"underriver",
"gorfly",
"pluckage",
"radiovision",
"tyrantship",
"fraught",
"doppelkummel",
"rowan",
"allosyndetic",
"kinesiology",
"psychopath",
"arrent",
"amusively",
"preincorporation",
"Montargis",
"pentacron",
"neomedievalism",
"sima",
"lichenicolous",
"Ecclesiastes",
"woofed",
"cardinalist",
"sandaracin",
"gymnasial",
"lithoglyptics",
"centimeter",
"quadrupedous",
"phraseology",
"tumuli",
"ankylotomy",
"myrtol",
"cohibitive",
"lepospondylous",
"silvendy",
"inequipotential",
"entangle",
"raveling",
"Zeugobranchiata",
"devastating",
"grainage",
"amphisbaenian",
"blady",
"cirrose",
"proclericalism",
"governmentalist",
"carcinomorphic",
"nurtureship",
"clancular",
"unsteamed",
"discernibly",
"pleurogenic",
"impalpability",
"Azotobacterieae",
"sarcoplasmic",
"alternant",
"fitly",
"acrorrheuma",
"shrapnel",
"pastorize",
"gulflike",
"foreglow",
"unrelated",
"cirriped",
"cerviconasal",
"sexuale",
"pussyfooter",
"gadolinic",
"duplicature",
"codelinquency",
"trypanolysis",
"pathophobia",
"incapsulation",
"nonaerating",
"feldspar",
"diaphonic",
"epiglottic",
"depopulator",
"wisecracker",
"gravitational",
"kuba",
"lactesce",
"Toxotes",
"periomphalic",
"singstress",
"fannier",
"counterformula",
"Acemetae",
"repugnatorial",
"collimator",
"Acinetina",
"unpeace",
"drum",
"tetramorphic",
"descendentalism",
"cementer",
"supraloral",
"intercostal",
"Nipponize",
"negotiator",
"vacationless",
"synthol",
"fissureless",
"resoap",
"pachycarpous",
"reinspiration",
"misappropriation",
"disdiazo",
"unheatable",
"streng",
"Detroiter",
"infandous",
"loganiaceous",
"desugar",
"Matronalia",
"myxocystoma",
"Gandhiism",
"kiddier",
"relodge",
"counterreprisal",
"recentralize",
"foliously",
"reprinter",
"gender",
"edaciousness",
"chondriomite",
"concordant",
"stockrider",
"pedary",
"shikra",
"blameworthiness",
"vaccina",
"Thamnophilinae",
"wrongwise",
"unsuperannuated",
"convalescency",
"intransmutable",
"dropcloth",
"Ceriomyces",
"ponderal",
"unstentorian",
"mem",
"deceleration",
"ethionic",
"untopped",
"wetback",
"bebar",
"undecaying",
"shoreside",
"energize",
"presacral",
"undismay",
"agricolite",
"cowheart",
"hemibathybian",
"postexilian",
"Phacidiaceae",
"offing",
"redesignation",
"skeptically",
"physicianless",
"bronchopathy",
"marabuto",
"proprietory",
"unobtruded",
"funmaker",
"plateresque",
"preadventure",
"beseeching",
"cowpath",
"pachycephalia",
"arthresthesia",
"supari",
"lengthily",
"Nepa",
"liberation",
"nigrify",
"belfry",
"entoolitic",
"bazoo",
"pentachromic",
"distinguishable",
"slideable",
"galvanoscope",
"remanage",
"cetene",
"bocardo",
"consummation",
"boycottism",
"perplexity",
"astay",
"Gaetuli",
"periplastic",
"consolidator",
"sluggarding",
"coracoscapular",
"anangioid",
"oxygenizer",
"Hunanese",
"seminary",
"periplast",
"Corylus",
"unoriginativeness",
"persecutee",
"tweaker",
"silliness",
"Dabitis",
"facetiousness",
"thymy",
"nonimperial",
"mesoblastema",
"turbiniform",
"churchway",
"cooing",
"frithbot",
"concomitantly",
"stalwartize",
"clingfish",
"hardmouthed",
"parallelepipedonal",
"coracoacromial",
"factuality",
"curtilage",
"arachnoidean",
"semiaridity",
"phytobacteriology",
"premastery",
"hyperpurist",
"mobed",
"opportunistic",
"acclimature",
"outdistance",
"sophister",
"condonement",
"oxygenerator",
"acetonic",
"emanatory",
"periphlebitis",
"nonsociety",
"spectroradiometric",
"superaverage",
"cleanness",
"posteroventral",
"unadvised",
"unmistakedly",
"pimgenet",
"auresca",
"overimitate",
"dipnoan",
"chromoxylograph",
"triakistetrahedron",
"Suessiones",
"uncopiable",
"oligomenorrhea",
"fribbling",
"worriable",
"flot",
"ornithotrophy",
"phytoteratology",
"setup",
"lanneret",
"unbraceleted",
"gudemother",
"Spica",
"unconsolatory",
"recorruption",
"premenstrual",
"subretinal",
"millennialist",
"subjectibility",
"rewardproof",
"counterflight",
"pilomotor",
"carpetbaggery",
"macrodiagonal",
"slim",
"indiscernible",
"cuckoo",
"moted",
"controllingly",
"gynecopathy",
"porrectus",
"wanworth",
"lutfisk",
"semiprivate",
"philadelphy",
"abdominothoracic",
"coxcomb",
"dambrod",
"Metanemertini",
"balminess",
"homotypy",
"waremaker",
"absurdity",
"gimcrack",
"asquat",
"suitable",
"perimorphous",
"kitchenwards",
"pielum",
"salloo",
"paleontologic",
"Olson",
"Tellinidae",
"ferryman",
"peptonoid",
"Bopyridae",
"fallacy",
"ictuate",
"aguinaldo",
"rhyodacite",
"Ligydidae",
"galvanometric",
"acquisitor",
"muscology",
"hemikaryon",
"ethnobotanic",
"postganglionic",
"rudimentarily",
"replenish",
"phyllorhine",
"popgunnery",
"summar",
"quodlibetary",
"xanthochromia",
"autosymbolically",
"preloreal",
"extent",
"strawberry",
"immortalness",
"colicwort",
"frisca",
"electiveness",
"heartbroken",
"affrightingly",
"reconfiscation",
"jacchus",
"imponderably",
"semantics",
"beennut",
"paleometeorological",
"becost",
"timberwright",
"resuppose",
"syncategorematical",
"cytolymph",
"steinbok",
"explantation",
"hyperelliptic",
"antescript",
"blowdown",
"antinomical",
"caravanserai",
"unweariedly",
"isonymic",
"keratoplasty",
"vipery",
"parepigastric",
"endolymphatic",
"Londonese",
"necrotomy",
"angelship",
"Schizogregarinida",
"steeplebush",
"sparaxis",
"connectedness",
"tolerance",
"impingent",
"agglutinin",
"reviver",
"hieroglyphical",
"dialogize",
"coestate",
"declamatory",
"ventilation",
"tauromachy",
"cotransubstantiate",
"pome",
"underseas",
"triquadrantal",
"preconfinemnt",
"electroindustrial",
"selachostomous",
"nongolfer",
"mesalike",
"hamartiology",
"ganglioblast",
"unsuccessive",
"yallow",
"bacchanalianly",
"platydactyl",
"Bucephala",
"ultraurgent",
"penalist",
"catamenial",
"lynnhaven",
"unrelevant",
"lunkhead",
"metropolitan",
"hydro",
"outsoar",
"vernant",
"interlanguage",
"catarrhal",
"Ionicize",
"keelless",
"myomantic",
"booker",
"Xanthomonas",
"unimpeded",
"overfeminize",
"speronaro",
"diaconia",
"overholiness",
"liquefacient",
"Spartium",
"haggly",
"albumose",
"nonnecessary",
"sulcalization",
"decapitate",
"cellated",
"unguirostral",
"trichiurid",
"loveproof",
"amakebe",
"screet",
"arsenoferratin",
"unfrizz",
"undiscoverable",
"procollectivistic",
"tractile",
"Winona",
"dermostosis",
"eliminant",
"scomberoid",
"tensile",
"typesetting",
"xylic",
"dermatopathology",
"cycloplegic",
"revocable",
"fissate",
"afterplay",
"screwship",
"microerg",
"bentonite",
"stagecoaching",
"beglerbeglic",
"overcharitably",
"Plotinism",
"Veddoid",
"disequalize",
"cytoproct",
"trophophore",
"antidote",
"allerion",
"famous",
"convey",
"postotic",
"rapillo",
"cilectomy",
"penkeeper",
"patronym",
"bravely",
"ureteropyelitis",
"Hildebrandine",
"missileproof",
"Conularia",
"deadening",
"Conrad",
"pseudochylous",
"typologically",
"strummer",
"luxuriousness",
"resublimation",
"glossiness",
"hydrocauline",
"anaglyph",
"personifiable",
"seniority",
"formulator",
"datiscaceous",
"hydracrylate",
"Tyranni",
"Crawthumper",
"overprove",
"masher",
"dissonance",
"Serpentinian",
"malachite",
"interestless",
"stchi",
"ogum",
"polyspermic",
"archegoniate",
"precogitation",
"Alkaphrah",
"craggily",
"delightfulness",
"bioplast",
"diplocaulescent",
"neverland",
"interspheral",
"chlorhydric",
"forsakenly",
"scandium",
"detubation",
"telega",
"Valeriana",
"centraxonial",
"anabolite",
"neger",
"miscellanea",
"whalebacker",
"stylidiaceous",
"unpropelled",
"Kennedya",
"Jacksonite",
"ghoulish",
"Dendrocalamus",
"paynimhood",
"rappist",
"unluffed",
"falling",
"Lyctus",
"uncrown",
"warmly",
"pneumatism",
"Morisonian",
"notate",
"isoagglutinin",
"Pelidnota",
"previsit",
"contradistinctly",
"utter",
"porometer",
"gie",
"germanization",
"betwixt",
"prenephritic",
"underpier",
"Eleutheria",
"ruthenious",
"convertor",
"antisepsin",
"winterage",
"tetramethylammonium",
"Rockaway",
"Penaea",
"prelatehood",
"brisket",
"unwishful",
"Minahassa",
"Briareus",
"semiaxis",
"disintegrant",
"peastick",
"iatromechanical",
"fastus",
"thymectomy",
"ladyless",
"unpreened",
"overflutter",
"sicker",
"apsidally",
"thiazine",
"guideway",
"pausation",
"tellinoid",
"abrogative",
"foraminulate",
"omphalos",
"Monorhina",
"polymyarian",
"unhelpful",
"newslessness",
"oryctognosy",
"octoradial",
"doxology",
"arrhythmy",
"gugal",
"mesityl",
"hexaplaric",
"Cabirian",
"hordeiform",
"eddyroot",
"internarial",
"deservingness",
"jawbation",
"orographically",
"semiprecious",
"seasick",
"thermically",
"grew",
"tamability",
"egotistically",
"fip",
"preabsorbent",
"leptochroa",
"ethnobotany",
"podolite",
"egoistic",
"semitropical",
"cero",
"spinelessness",
"onshore",
"omlah",
"tintinnabulist",
"machila",
"entomotomy",
"nubile",
"nonscholastic",
"burnt",
"Alea",
"befume",
"doctorless",
"Napoleonic",
"scenting",
"apokreos",
"cresylene",
"paramide",
"rattery",
"disinterested",
"idiopathetic",
"negatory",
"fervid",
"quintato",
"untricked",
"Metrosideros",
"mescaline",
"midverse",
"Musophagidae",
"fictionary",
"branchiostegous",
"yoker",
"residuum",
"culmigenous",
"fleam",
"suffragism",
"Anacreon",
"sarcodous",
"parodistic",
"writmaking",
"conversationism",
"retroposed",
"tornillo",
"presuspect",
"didymous",
"Saumur",
"spicing",
"drawbridge",
"cantor",
"incumbrancer",
"heterospory",
"Turkeydom",
"anteprandial",
"neighbourship",
"thatchless",
"drepanoid",
"lusher",
"paling",
"ecthlipsis",
"heredosyphilitic",
"although",
"garetta",
"temporarily",
"Monotropa",
"proglottic",
"calyptro",
"persiflage",
"degradable",
"paraspecific",
"undecorative",
"Pholas",
"myelon",
"resteal",
"quadrantly",
"scrimped",
"airer",
"deviless",
"caliciform",
"Sefekhet",
"shastaite",
"togate",
"macrostructure",
"bipyramid",
"wey",
"didynamy",
"knacker",
"swage",
"supermanism",
"epitheton",
"overpresumptuous"
]
@inline(never)
func benchSortStrings(_ words: [String]) {
// Notice that we _copy_ the array of words before we sort it.
// Pass an explicit '<' predicate to benchmark reabstraction thunks.
var tempwords = words
tempwords.sort(by: <)
}
public func run_SortStrings(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(stringBenchmarkWords)
}
}
var stringBenchmarkWordsUnicode: [String] = [
"❄️woodshed",
"❄️lakism",
"❄️gastroperiodynia",
"❄️afetal",
"❄️ramsch",
"❄️Nickieben",
"❄️undutifulness",
"❄️birdglue",
"❄️ungentlemanize",
"❄️menacingly",
"❄️heterophile",
"❄️leoparde",
"❄️Casearia",
"❄️decorticate",
"❄️neognathic",
"❄️mentionable",
"❄️tetraphenol",
"❄️pseudonymal",
"❄️dislegitimate",
"❄️Discoidea",
"❄️intitule",
"❄️ionium",
"❄️Lotuko",
"❄️timbering",
"❄️nonliquidating",
"❄️oarialgia",
"❄️Saccobranchus",
"❄️reconnoiter",
"❄️criminative",
"❄️disintegratory",
"❄️executer",
"❄️Cylindrosporium",
"❄️complimentation",
"❄️Ixiama",
"❄️Araceae",
"❄️silaginoid",
"❄️derencephalus",
"❄️Lamiidae",
"❄️marrowlike",
"❄️ninepin",
"❄️dynastid",
"❄️lampfly",
"❄️feint",
"❄️trihemimer",
"❄️semibarbarous",
"❄️heresy",
"❄️tritanope",
"❄️indifferentist",
"❄️confound",
"❄️hyperbolaeon",
"❄️planirostral",
"❄️philosophunculist",
"❄️existence",
"❄️fretless",
"❄️Leptandra",
"❄️Amiranha",
"❄️handgravure",
"❄️gnash",
"❄️unbelievability",
"❄️orthotropic",
"❄️Susumu",
"❄️teleutospore",
"❄️sleazy",
"❄️shapeliness",
"❄️hepatotomy",
"❄️exclusivism",
"❄️stifler",
"❄️cunning",
"❄️isocyanuric",
"❄️pseudepigraphy",
"❄️carpetbagger",
"❄️respectiveness",
"❄️Jussi",
"❄️vasotomy",
"❄️proctotomy",
"❄️ovatotriangular",
"❄️aesthetic",
"❄️schizogamy",
"❄️disengagement",
"❄️foray",
"❄️haplocaulescent",
"❄️noncoherent",
"❄️astrocyte",
"❄️unreverberated",
"❄️presenile",
"❄️lanson",
"❄️enkraal",
"❄️contemplative",
"❄️Syun",
"❄️sartage",
"❄️unforgot",
"❄️wyde",
"❄️homeotransplant",
"❄️implicational",
"❄️forerunnership",
"❄️calcaneum",
"❄️stomatodeum",
"❄️pharmacopedia",
"❄️preconcessive",
"❄️trypanosomatic",
"❄️intracollegiate",
"❄️rampacious",
"❄️secundipara",
"❄️isomeric",
"❄️treehair",
"❄️pulmonal",
"❄️uvate",
"❄️dugway",
"❄️glucofrangulin",
"❄️unglory",
"❄️Amandus",
"❄️icterogenetic",
"❄️quadrireme",
"❄️Lagostomus",
"❄️brakeroot",
"❄️anthracemia",
"❄️fluted",
"❄️protoelastose",
"❄️thro",
"❄️pined",
"❄️Saxicolinae",
"❄️holidaymaking",
"❄️strigil",
"❄️uncurbed",
"❄️starling",
"❄️redeemeress",
"❄️Liliaceae",
"❄️imparsonee",
"❄️obtusish",
"❄️brushed",
"❄️mesally",
"❄️probosciformed",
"❄️Bourbonesque",
"❄️histological",
"❄️caroba",
"❄️digestion",
"❄️Vindemiatrix",
"❄️triactinal",
"❄️tattling",
"❄️arthrobacterium",
"❄️unended",
"❄️suspectfulness",
"❄️movelessness",
"❄️chartist",
"❄️Corynebacterium",
"❄️tercer",
"❄️oversaturation",
"❄️Congoleum",
"❄️antiskeptical",
"❄️sacral",
"❄️equiradiate",
"❄️whiskerage",
"❄️panidiomorphic",
"❄️unplanned",
"❄️anilopyrine",
"❄️Queres",
"❄️tartronyl",
"❄️Ing",
"❄️notehead",
"❄️finestiller",
"❄️weekender",
"❄️kittenhood",
"❄️competitrix",
"❄️premillenarian",
"❄️convergescence",
"❄️microcoleoptera",
"❄️slirt",
"❄️asteatosis",
"❄️Gruidae",
"❄️metastome",
"❄️ambuscader",
"❄️untugged",
"❄️uneducated",
"❄️redistill",
"❄️rushlight",
"❄️freakish",
"❄️dosology",
"❄️papyrine",
"❄️iconologist",
"❄️Bidpai",
"❄️prophethood",
"❄️pneumotropic",
"❄️chloroformize",
"❄️intemperance",
"❄️spongiform",
"❄️superindignant",
"❄️divider",
"❄️starlit",
"❄️merchantish",
"❄️indexless",
"❄️unidentifiably",
"❄️coumarone",
"❄️nomism",
"❄️diaphanous",
"❄️salve",
"❄️option",
"❄️anallantoic",
"❄️paint",
"❄️thiofurfuran",
"❄️baddeleyite",
"❄️Donne",
"❄️heterogenicity",
"❄️decess",
"❄️eschynite",
"❄️mamma",
"❄️unmonarchical",
"❄️Archiplata",
"❄️widdifow",
"❄️apathic",
"❄️overline",
"❄️chaetophoraceous",
"❄️creaky",
"❄️trichosporange",
"❄️uninterlined",
"❄️cometwise",
"❄️hermeneut",
"❄️unbedraggled",
"❄️tagged",
"❄️Sminthurus",
"❄️somniloquacious",
"❄️aphasiac",
"❄️Inoperculata",
"❄️photoactivity",
"❄️mobship",
"❄️unblightedly",
"❄️lievrite",
"❄️Khoja",
"❄️Falerian",
"❄️milfoil",
"❄️protectingly",
"❄️householder",
"❄️cathedra",
"❄️calmingly",
"❄️tordrillite",
"❄️rearhorse",
"❄️Leonard",
"❄️maracock",
"❄️youngish",
"❄️kammererite",
"❄️metanephric",
"❄️Sageretia",
"❄️diplococcoid",
"❄️accelerative",
"❄️choreal",
"❄️metalogical",
"❄️recombination",
"❄️unimprison",
"❄️invocation",
"❄️syndetic",
"❄️toadback",
"❄️vaned",
"❄️cupholder",
"❄️metropolitanship",
"❄️paramandelic",
"❄️dermolysis",
"❄️Sheriyat",
"❄️rhabdus",
"❄️seducee",
"❄️encrinoid",
"❄️unsuppliable",
"❄️cololite",
"❄️timesaver",
"❄️preambulate",
"❄️sampling",
"❄️roaster",
"❄️springald",
"❄️densher",
"❄️protraditional",
"❄️naturalesque",
"❄️Hydrodamalis",
"❄️cytogenic",
"❄️shortly",
"❄️cryptogrammatical",
"❄️squat",
"❄️genual",
"❄️backspier",
"❄️solubleness",
"❄️macroanalytical",
"❄️overcovetousness",
"❄️Natalie",
"❄️cuprobismutite",
"❄️phratriac",
"❄️Montanize",
"❄️hymnologist",
"❄️karyomiton",
"❄️podger",
"❄️unofficiousness",
"❄️antisplasher",
"❄️supraclavicular",
"❄️calidity",
"❄️disembellish",
"❄️antepredicament",
"❄️recurvirostral",
"❄️pulmonifer",
"❄️coccidial",
"❄️botonee",
"❄️protoglobulose",
"❄️isonym",
"❄️myeloid",
"❄️premiership",
"❄️unmonopolize",
"❄️unsesquipedalian",
"❄️unfelicitously",
"❄️theftbote",
"❄️undauntable",
"❄️lob",
"❄️praenomen",
"❄️underriver",
"❄️gorfly",
"❄️pluckage",
"❄️radiovision",
"❄️tyrantship",
"❄️fraught",
"❄️doppelkummel",
"❄️rowan",
"❄️allosyndetic",
"❄️kinesiology",
"❄️psychopath",
"❄️arrent",
"❄️amusively",
"❄️preincorporation",
"❄️Montargis",
"❄️pentacron",
"❄️neomedievalism",
"❄️sima",
"❄️lichenicolous",
"❄️Ecclesiastes",
"❄️woofed",
"❄️cardinalist",
"❄️sandaracin",
"❄️gymnasial",
"❄️lithoglyptics",
"❄️centimeter",
"❄️quadrupedous",
"❄️phraseology",
"❄️tumuli",
"❄️ankylotomy",
"❄️myrtol",
"❄️cohibitive",
"❄️lepospondylous",
"❄️silvendy",
"❄️inequipotential",
"❄️entangle",
"❄️raveling",
"❄️Zeugobranchiata",
"❄️devastating",
"❄️grainage",
"❄️amphisbaenian",
"❄️blady",
"❄️cirrose",
"❄️proclericalism",
"❄️governmentalist",
"❄️carcinomorphic",
"❄️nurtureship",
"❄️clancular",
"❄️unsteamed",
"❄️discernibly",
"❄️pleurogenic",
"❄️impalpability",
"❄️Azotobacterieae",
"❄️sarcoplasmic",
"❄️alternant",
"❄️fitly",
"❄️acrorrheuma",
"❄️shrapnel",
"❄️pastorize",
"❄️gulflike",
"❄️foreglow",
"❄️unrelated",
"❄️cirriped",
"❄️cerviconasal",
"❄️sexuale",
"❄️pussyfooter",
"❄️gadolinic",
"❄️duplicature",
"❄️codelinquency",
"❄️trypanolysis",
"❄️pathophobia",
"❄️incapsulation",
"❄️nonaerating",
"❄️feldspar",
"❄️diaphonic",
"❄️epiglottic",
"❄️depopulator",
"❄️wisecracker",
"❄️gravitational",
"❄️kuba",
"❄️lactesce",
"❄️Toxotes",
"❄️periomphalic",
"❄️singstress",
"❄️fannier",
"❄️counterformula",
"❄️Acemetae",
"❄️repugnatorial",
"❄️collimator",
"❄️Acinetina",
"❄️unpeace",
"❄️drum",
"❄️tetramorphic",
"❄️descendentalism",
"❄️cementer",
"❄️supraloral",
"❄️intercostal",
"❄️Nipponize",
"❄️negotiator",
"❄️vacationless",
"❄️synthol",
"❄️fissureless",
"❄️resoap",
"❄️pachycarpous",
"❄️reinspiration",
"❄️misappropriation",
"❄️disdiazo",
"❄️unheatable",
"❄️streng",
"❄️Detroiter",
"❄️infandous",
"❄️loganiaceous",
"❄️desugar",
"❄️Matronalia",
"❄️myxocystoma",
"❄️Gandhiism",
"❄️kiddier",
"❄️relodge",
"❄️counterreprisal",
"❄️recentralize",
"❄️foliously",
"❄️reprinter",
"❄️gender",
"❄️edaciousness",
"❄️chondriomite",
"❄️concordant",
"❄️stockrider",
"❄️pedary",
"❄️shikra",
"❄️blameworthiness",
"❄️vaccina",
"❄️Thamnophilinae",
"❄️wrongwise",
"❄️unsuperannuated",
"❄️convalescency",
"❄️intransmutable",
"❄️dropcloth",
"❄️Ceriomyces",
"❄️ponderal",
"❄️unstentorian",
"❄️mem",
"❄️deceleration",
"❄️ethionic",
"❄️untopped",
"❄️wetback",
"❄️bebar",
"❄️undecaying",
"❄️shoreside",
"❄️energize",
"❄️presacral",
"❄️undismay",
"❄️agricolite",
"❄️cowheart",
"❄️hemibathybian",
"❄️postexilian",
"❄️Phacidiaceae",
"❄️offing",
"❄️redesignation",
"❄️skeptically",
"❄️physicianless",
"❄️bronchopathy",
"❄️marabuto",
"❄️proprietory",
"❄️unobtruded",
"❄️funmaker",
"❄️plateresque",
"❄️preadventure",
"❄️beseeching",
"❄️cowpath",
"❄️pachycephalia",
"❄️arthresthesia",
"❄️supari",
"❄️lengthily",
"❄️Nepa",
"❄️liberation",
"❄️nigrify",
"❄️belfry",
"❄️entoolitic",
"❄️bazoo",
"❄️pentachromic",
"❄️distinguishable",
"❄️slideable",
"❄️galvanoscope",
"❄️remanage",
"❄️cetene",
"❄️bocardo",
"❄️consummation",
"❄️boycottism",
"❄️perplexity",
"❄️astay",
"❄️Gaetuli",
"❄️periplastic",
"❄️consolidator",
"❄️sluggarding",
"❄️coracoscapular",
"❄️anangioid",
"❄️oxygenizer",
"❄️Hunanese",
"❄️seminary",
"❄️periplast",
"❄️Corylus",
"❄️unoriginativeness",
"❄️persecutee",
"❄️tweaker",
"❄️silliness",
"❄️Dabitis",
"❄️facetiousness",
"❄️thymy",
"❄️nonimperial",
"❄️mesoblastema",
"❄️turbiniform",
"❄️churchway",
"❄️cooing",
"❄️frithbot",
"❄️concomitantly",
"❄️stalwartize",
"❄️clingfish",
"❄️hardmouthed",
"❄️parallelepipedonal",
"❄️coracoacromial",
"❄️factuality",
"❄️curtilage",
"❄️arachnoidean",
"❄️semiaridity",
"❄️phytobacteriology",
"❄️premastery",
"❄️hyperpurist",
"❄️mobed",
"❄️opportunistic",
"❄️acclimature",
"❄️outdistance",
"❄️sophister",
"❄️condonement",
"❄️oxygenerator",
"❄️acetonic",
"❄️emanatory",
"❄️periphlebitis",
"❄️nonsociety",
"❄️spectroradiometric",
"❄️superaverage",
"❄️cleanness",
"❄️posteroventral",
"❄️unadvised",
"❄️unmistakedly",
"❄️pimgenet",
"❄️auresca",
"❄️overimitate",
"❄️dipnoan",
"❄️chromoxylograph",
"❄️triakistetrahedron",
"❄️Suessiones",
"❄️uncopiable",
"❄️oligomenorrhea",
"❄️fribbling",
"❄️worriable",
"❄️flot",
"❄️ornithotrophy",
"❄️phytoteratology",
"❄️setup",
"❄️lanneret",
"❄️unbraceleted",
"❄️gudemother",
"❄️Spica",
"❄️unconsolatory",
"❄️recorruption",
"❄️premenstrual",
"❄️subretinal",
"❄️millennialist",
"❄️subjectibility",
"❄️rewardproof",
"❄️counterflight",
"❄️pilomotor",
"❄️carpetbaggery",
"❄️macrodiagonal",
"❄️slim",
"❄️indiscernible",
"❄️cuckoo",
"❄️moted",
"❄️controllingly",
"❄️gynecopathy",
"❄️porrectus",
"❄️wanworth",
"❄️lutfisk",
"❄️semiprivate",
"❄️philadelphy",
"❄️abdominothoracic",
"❄️coxcomb",
"❄️dambrod",
"❄️Metanemertini",
"❄️balminess",
"❄️homotypy",
"❄️waremaker",
"❄️absurdity",
"❄️gimcrack",
"❄️asquat",
"❄️suitable",
"❄️perimorphous",
"❄️kitchenwards",
"❄️pielum",
"❄️salloo",
"❄️paleontologic",
"❄️Olson",
"❄️Tellinidae",
"❄️ferryman",
"❄️peptonoid",
"❄️Bopyridae",
"❄️fallacy",
"❄️ictuate",
"❄️aguinaldo",
"❄️rhyodacite",
"❄️Ligydidae",
"❄️galvanometric",
"❄️acquisitor",
"❄️muscology",
"❄️hemikaryon",
"❄️ethnobotanic",
"❄️postganglionic",
"❄️rudimentarily",
"❄️replenish",
"❄️phyllorhine",
"❄️popgunnery",
"❄️summar",
"❄️quodlibetary",
"❄️xanthochromia",
"❄️autosymbolically",
"❄️preloreal",
"❄️extent",
"❄️strawberry",
"❄️immortalness",
"❄️colicwort",
"❄️frisca",
"❄️electiveness",
"❄️heartbroken",
"❄️affrightingly",
"❄️reconfiscation",
"❄️jacchus",
"❄️imponderably",
"❄️semantics",
"❄️beennut",
"❄️paleometeorological",
"❄️becost",
"❄️timberwright",
"❄️resuppose",
"❄️syncategorematical",
"❄️cytolymph",
"❄️steinbok",
"❄️explantation",
"❄️hyperelliptic",
"❄️antescript",
"❄️blowdown",
"❄️antinomical",
"❄️caravanserai",
"❄️unweariedly",
"❄️isonymic",
"❄️keratoplasty",
"❄️vipery",
"❄️parepigastric",
"❄️endolymphatic",
"❄️Londonese",
"❄️necrotomy",
"❄️angelship",
"❄️Schizogregarinida",
"❄️steeplebush",
"❄️sparaxis",
"❄️connectedness",
"❄️tolerance",
"❄️impingent",
"❄️agglutinin",
"❄️reviver",
"❄️hieroglyphical",
"❄️dialogize",
"❄️coestate",
"❄️declamatory",
"❄️ventilation",
"❄️tauromachy",
"❄️cotransubstantiate",
"❄️pome",
"❄️underseas",
"❄️triquadrantal",
"❄️preconfinemnt",
"❄️electroindustrial",
"❄️selachostomous",
"❄️nongolfer",
"❄️mesalike",
"❄️hamartiology",
"❄️ganglioblast",
"❄️unsuccessive",
"❄️yallow",
"❄️bacchanalianly",
"❄️platydactyl",
"❄️Bucephala",
"❄️ultraurgent",
"❄️penalist",
"❄️catamenial",
"❄️lynnhaven",
"❄️unrelevant",
"❄️lunkhead",
"❄️metropolitan",
"❄️hydro",
"❄️outsoar",
"❄️vernant",
"❄️interlanguage",
"❄️catarrhal",
"❄️Ionicize",
"❄️keelless",
"❄️myomantic",
"❄️booker",
"❄️Xanthomonas",
"❄️unimpeded",
"❄️overfeminize",
"❄️speronaro",
"❄️diaconia",
"❄️overholiness",
"❄️liquefacient",
"❄️Spartium",
"❄️haggly",
"❄️albumose",
"❄️nonnecessary",
"❄️sulcalization",
"❄️decapitate",
"❄️cellated",
"❄️unguirostral",
"❄️trichiurid",
"❄️loveproof",
"❄️amakebe",
"❄️screet",
"❄️arsenoferratin",
"❄️unfrizz",
"❄️undiscoverable",
"❄️procollectivistic",
"❄️tractile",
"❄️Winona",
"❄️dermostosis",
"❄️eliminant",
"❄️scomberoid",
"❄️tensile",
"❄️typesetting",
"❄️xylic",
"❄️dermatopathology",
"❄️cycloplegic",
"❄️revocable",
"❄️fissate",
"❄️afterplay",
"❄️screwship",
"❄️microerg",
"❄️bentonite",
"❄️stagecoaching",
"❄️beglerbeglic",
"❄️overcharitably",
"❄️Plotinism",
"❄️Veddoid",
"❄️disequalize",
"❄️cytoproct",
"❄️trophophore",
"❄️antidote",
"❄️allerion",
"❄️famous",
"❄️convey",
"❄️postotic",
"❄️rapillo",
"❄️cilectomy",
"❄️penkeeper",
"❄️patronym",
"❄️bravely",
"❄️ureteropyelitis",
"❄️Hildebrandine",
"❄️missileproof",
"❄️Conularia",
"❄️deadening",
"❄️Conrad",
"❄️pseudochylous",
"❄️typologically",
"❄️strummer",
"❄️luxuriousness",
"❄️resublimation",
"❄️glossiness",
"❄️hydrocauline",
"❄️anaglyph",
"❄️personifiable",
"❄️seniority",
"❄️formulator",
"❄️datiscaceous",
"❄️hydracrylate",
"❄️Tyranni",
"❄️Crawthumper",
"❄️overprove",
"❄️masher",
"❄️dissonance",
"❄️Serpentinian",
"❄️malachite",
"❄️interestless",
"❄️stchi",
"❄️ogum",
"❄️polyspermic",
"❄️archegoniate",
"❄️precogitation",
"❄️Alkaphrah",
"❄️craggily",
"❄️delightfulness",
"❄️bioplast",
"❄️diplocaulescent",
"❄️neverland",
"❄️interspheral",
"❄️chlorhydric",
"❄️forsakenly",
"❄️scandium",
"❄️detubation",
"❄️telega",
"❄️Valeriana",
"❄️centraxonial",
"❄️anabolite",
"❄️neger",
"❄️miscellanea",
"❄️whalebacker",
"❄️stylidiaceous",
"❄️unpropelled",
"❄️Kennedya",
"❄️Jacksonite",
"❄️ghoulish",
"❄️Dendrocalamus",
"❄️paynimhood",
"❄️rappist",
"❄️unluffed",
"❄️falling",
"❄️Lyctus",
"❄️uncrown",
"❄️warmly",
"❄️pneumatism",
"❄️Morisonian",
"❄️notate",
"❄️isoagglutinin",
"❄️Pelidnota",
"❄️previsit",
"❄️contradistinctly",
"❄️utter",
"❄️porometer",
"❄️gie",
"❄️germanization",
"❄️betwixt",
"❄️prenephritic",
"❄️underpier",
"❄️Eleutheria",
"❄️ruthenious",
"❄️convertor",
"❄️antisepsin",
"❄️winterage",
"❄️tetramethylammonium",
"❄️Rockaway",
"❄️Penaea",
"❄️prelatehood",
"❄️brisket",
"❄️unwishful",
"❄️Minahassa",
"❄️Briareus",
"❄️semiaxis",
"❄️disintegrant",
"❄️peastick",
"❄️iatromechanical",
"❄️fastus",
"❄️thymectomy",
"❄️ladyless",
"❄️unpreened",
"❄️overflutter",
"❄️sicker",
"❄️apsidally",
"❄️thiazine",
"❄️guideway",
"❄️pausation",
"❄️tellinoid",
"❄️abrogative",
"❄️foraminulate",
"❄️omphalos",
"❄️Monorhina",
"❄️polymyarian",
"❄️unhelpful",
"❄️newslessness",
"❄️oryctognosy",
"❄️octoradial",
"❄️doxology",
"❄️arrhythmy",
"❄️gugal",
"❄️mesityl",
"❄️hexaplaric",
"❄️Cabirian",
"❄️hordeiform",
"❄️eddyroot",
"❄️internarial",
"❄️deservingness",
"❄️jawbation",
"❄️orographically",
"❄️semiprecious",
"❄️seasick",
"❄️thermically",
"❄️grew",
"❄️tamability",
"❄️egotistically",
"❄️fip",
"❄️preabsorbent",
"❄️leptochroa",
"❄️ethnobotany",
"❄️podolite",
"❄️egoistic",
"❄️semitropical",
"❄️cero",
"❄️spinelessness",
"❄️onshore",
"❄️omlah",
"❄️tintinnabulist",
"❄️machila",
"❄️entomotomy",
"❄️nubile",
"❄️nonscholastic",
"❄️burnt",
"❄️Alea",
"❄️befume",
"❄️doctorless",
"❄️Napoleonic",
"❄️scenting",
"❄️apokreos",
"❄️cresylene",
"❄️paramide",
"❄️rattery",
"❄️disinterested",
"❄️idiopathetic",
"❄️negatory",
"❄️fervid",
"❄️quintato",
"❄️untricked",
"❄️Metrosideros",
"❄️mescaline",
"❄️midverse",
"❄️Musophagidae",
"❄️fictionary",
"❄️branchiostegous",
"❄️yoker",
"❄️residuum",
"❄️culmigenous",
"❄️fleam",
"❄️suffragism",
"❄️Anacreon",
"❄️sarcodous",
"❄️parodistic",
"❄️writmaking",
"❄️conversationism",
"❄️retroposed",
"❄️tornillo",
"❄️presuspect",
"❄️didymous",
"❄️Saumur",
"❄️spicing",
"❄️drawbridge",
"❄️cantor",
"❄️incumbrancer",
"❄️heterospory",
"❄️Turkeydom",
"❄️anteprandial",
"❄️neighbourship",
"❄️thatchless",
"❄️drepanoid",
"❄️lusher",
"❄️paling",
"❄️ecthlipsis",
"❄️heredosyphilitic",
"❄️although",
"❄️garetta",
"❄️temporarily",
"❄️Monotropa",
"❄️proglottic",
"❄️calyptro",
"❄️persiflage",
"❄️degradable",
"❄️paraspecific",
"❄️undecorative",
"❄️Pholas",
"❄️myelon",
"❄️resteal",
"❄️quadrantly",
"❄️scrimped",
"❄️airer",
"❄️deviless",
"❄️caliciform",
"❄️Sefekhet",
"❄️shastaite",
"❄️togate",
"❄️macrostructure",
"❄️bipyramid",
"❄️wey",
"❄️didynamy",
"❄️knacker",
"❄️swage",
"❄️supermanism",
"❄️epitheton",
"❄️overpresumptuous"
]
public func run_SortStringsUnicode(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(stringBenchmarkWordsUnicode)
}
}
| 4729cdc60a0a162a93fd28e7034fdf38 | 16.036765 | 80 | 0.58475 | false | false | false | false |
yaslab/ZeroFormatter.swift | refs/heads/master | Sources/TimeSpan.swift | mit | 1 | //
// TimeSpan.swift
// ZeroFormatter
//
// Created by Yasuhiro Hatta on 2016/12/15.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
public struct TimeSpan: Serializable {
public let totalSeconds: TimeInterval
public init(totalSeconds: TimeInterval) {
self.totalSeconds = totalSeconds
}
// MARK: - ZeroFormattable
public static var length: Int? {
return 12
}
// MARK: - Serializable
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: TimeSpan) -> Int {
let unixTime = value.totalSeconds
let seconds = Int64(unixTime)
let nanos = Int32((abs(unixTime) - floor(abs(unixTime))) * 1_000_000_000)
var byteSize = 0
byteSize += BinaryUtility.serialize(bytes, seconds)
byteSize += BinaryUtility.serialize(bytes, nanos)
return byteSize
}
public static func serialize(_ bytes: NSMutableData, _ offset: Int, _ value: TimeSpan?) -> Int {
var byteSize = 0
if let value = value {
byteSize += BinaryUtility.serialize(bytes, true)
byteSize += serialize(bytes, -1, value)
} else {
byteSize += BinaryUtility.serialize(bytes, false)
byteSize += BinaryUtility.serialize(bytes, Int64(0)) // seconds
byteSize += BinaryUtility.serialize(bytes, Int32(0)) // nanos
}
return byteSize
}
// MARK: - Deserializable
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> TimeSpan {
let start = byteSize
let seconds: Int64 = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
let nanos: Int32 = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
var unixTime = TimeInterval(seconds)
unixTime += TimeInterval(nanos) / 1_000_000_000.0
return TimeSpan(totalSeconds: unixTime)
}
public static func deserialize(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> TimeSpan? {
let start = byteSize
let hasValue: Bool = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
if hasValue {
let value: TimeSpan = deserialize(bytes, offset + (byteSize - start), &byteSize)
return value
} else {
return nil
}
}
}
| 5da8b716405eafe4363de01fdff705e0 | 32.833333 | 104 | 0.612069 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.