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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/Media/MediaFileManager.swift | gpl-2.0 | 1 | import Foundation
import CocoaLumberjack
/// Type of the local Media directory URL in implementation.
///
enum MediaDirectory {
/// Default, system Documents directory, for persisting media files for upload.
case uploads
/// System Caches directory, for creating discardable media files, such as thumbnails.
case cache
/// System temporary directory, used for unit testing or temporary media files.
case temporary
/// Returns the directory URL for the directory type.
///
fileprivate var url: URL {
let fileManager = FileManager.default
// Get a parent directory, based on the type.
let parentDirectory: URL
switch self {
case .uploads:
parentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
case .cache:
parentDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
case .temporary:
parentDirectory = fileManager.temporaryDirectory
}
return parentDirectory.appendingPathComponent(MediaFileManager.mediaDirectoryName, isDirectory: true)
}
}
/// Encapsulates Media functions relative to the local Media directory.
///
class MediaFileManager: NSObject {
fileprivate static let mediaDirectoryName = "Media"
let directory: MediaDirectory
// MARK: - Class init
/// The default instance of a MediaFileManager.
///
@objc (defaultManager)
static let `default`: MediaFileManager = {
return MediaFileManager()
}()
/// Helper method for getting a MediaFileManager for the .cache directory.
///
@objc (cacheManager)
class var cache: MediaFileManager {
return MediaFileManager(directory: .cache)
}
// MARK: - Init
/// Init with default directory of .uploads.
///
/// - Note: This is particularly because the original Media directory was in the NSFileManager's documents directory.
/// We shouldn't change this default directory lightly as older versions of the app may rely on Media files being in
/// the documents directory for upload.
///
init(directory: MediaDirectory = .uploads) {
self.directory = directory
}
// MARK: - Instance methods
/// Returns filesystem URL for the local Media directory.
///
@objc func directoryURL() throws -> URL {
let fileManager = FileManager.default
let mediaDirectory = directory.url
// Check whether or not the file path exists for the Media directory.
// If the filepath does not exist, or if the filepath does exist but it is not a directory, try creating the directory.
// Note: This way, if unexpectedly a file exists but it is not a dir, an error will throw when trying to create the dir.
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: mediaDirectory.path, isDirectory: &isDirectory) == false || isDirectory.boolValue == false {
try fileManager.createDirectory(at: mediaDirectory, withIntermediateDirectories: true, attributes: nil)
}
return mediaDirectory
}
/// Returns a unique filesystem URL for a Media filename and extension, within the local Media directory.
///
/// - Note: if a file already exists with the same name, the file name is appended with a number
/// and incremented until a unique filename is found.
///
@objc func makeLocalMediaURL(withFilename filename: String, fileExtension: String?, incremented: Bool = true) throws -> URL {
let baseURL = try directoryURL()
var url: URL
if let fileExtension = fileExtension {
let basename = (filename as NSString).deletingPathExtension.lowercased()
url = baseURL.appendingPathComponent(basename, isDirectory: false)
url.appendPathExtension(fileExtension)
} else {
url = baseURL.appendingPathComponent(filename, isDirectory: false)
}
// Increment the filename as needed to ensure we're not
// providing a URL for an existing file of the same name.
return incremented ? url.incrementalFilename() : url
}
/// Objc friendly signature without specifying the `incremented` parameter.
///
@objc func makeLocalMediaURL(withFilename filename: String, fileExtension: String?) throws -> URL {
return try makeLocalMediaURL(withFilename: filename, fileExtension: fileExtension, incremented: true)
}
/// Returns a string appended with the thumbnail naming convention for local Media files.
///
@objc func mediaFilenameAppendingThumbnail(_ filename: String) -> String {
var filename = filename as NSString
let pathExtension = filename.pathExtension
filename = filename.deletingPathExtension.appending("-thumbnail") as NSString
return filename.appendingPathExtension(pathExtension)!
}
/// Returns the size of a Media image located at the file URL, or zero if it doesn't exist.
///
/// - Note: once we drop ObjC, this should be an optional that would return nil instead of zero.
///
@objc func imageSizeForMediaAt(fileURL: URL?) -> CGSize {
guard let fileURL = fileURL else {
return CGSize.zero
}
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: fileURL.path, isDirectory: &isDirectory) == true, isDirectory.boolValue == false else {
return CGSize.zero
}
guard
let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil),
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? Dictionary<String, AnyObject>
else {
return CGSize.zero
}
var width = CGFloat(0), height = CGFloat(0)
if let widthProperty = imageProperties[kCGImagePropertyPixelWidth as String] as? CGFloat {
width = widthProperty
}
if let heightProperty = imageProperties[kCGImagePropertyPixelHeight as String] as? CGFloat {
height = heightProperty
}
return CGSize(width: width, height: height)
}
/// Calculates the allocated size of the Media directory, in bytes, or nil if an error was thrown.
///
func calculateSizeOfDirectory(onCompletion: @escaping (Int64?) -> Void) {
DispatchQueue.global(qos: .default).async {
let fileManager = FileManager.default
let allocatedSize = try? fileManager.allocatedSizeOf(directoryURL: self.directoryURL())
DispatchQueue.main.async {
onCompletion(allocatedSize)
}
}
}
/// Clear the local Media directory of any files that are no longer in use or can be fetched again,
/// such as Media without a blog or with a remote URL.
///
/// - Note: These files can show up because of the app being killed while a media object
/// was being created or when a CoreData migration fails and the database is recreated.
///
@objc func clearUnusedFilesFromDirectory(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
purgeMediaFiles(exceptMedia: NSPredicate(format: "blog != NULL && remoteURL == NULL"),
onCompletion: onCompletion,
onError: onError)
}
/// Clear the local Media directory of any cached media files that are available remotely.
///
@objc func clearFilesFromDirectory(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
do {
try purgeDirectory(exceptFiles: [])
onCompletion?()
} catch {
onError?(error)
}
}
// MARK: - Class methods
/// Helper method for clearing unused Media upload files.
///
@objc class func clearUnusedMediaUploadFiles(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
MediaFileManager.default.clearUnusedFilesFromDirectory(onCompletion: onCompletion, onError: onError)
}
/// Helper method for calculating the size of the Media directories.
///
class func calculateSizeOfMediaDirectories(onCompletion: @escaping (Int64?) -> Void) {
let cacheManager = MediaFileManager(directory: .cache)
cacheManager.calculateSizeOfDirectory { (cacheSize) in
let defaultManager = MediaFileManager.default
defaultManager.calculateSizeOfDirectory { (mediaSize) in
onCompletion( (mediaSize ?? 0) + (cacheSize ?? 0) )
}
}
}
/// Helper method for clearing the Media cache directory.
///
@objc class func clearAllMediaCacheFiles(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
let cacheManager = MediaFileManager(directory: .cache)
cacheManager.clearFilesFromDirectory(onCompletion: {
MediaFileManager.clearUnusedMediaUploadFiles(onCompletion: onCompletion, onError: onError)
}, onError: onError)
}
/// Helper method for getting the default upload directory URL.
///
@objc class func uploadsDirectoryURL() throws -> URL {
return try MediaFileManager.default.directoryURL()
}
// MARK: - Private
/// Removes any local Media files, except any Media matching the predicate.
///
fileprivate func purgeMediaFiles(exceptMedia predicate: NSPredicate, onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
let context = ContextManager.sharedInstance().newDerivedContext()
context.perform {
let fetch = NSFetchRequest<NSDictionary>(entityName: Media.classNameWithoutNamespaces())
fetch.predicate = predicate
fetch.resultType = .dictionaryResultType
let localURLProperty = #selector(getter: Media.localURL).description
let localThumbnailURLProperty = #selector(getter: Media.localThumbnailURL).description
fetch.propertiesToFetch = [localURLProperty,
localThumbnailURLProperty]
do {
let mediaToKeep = try context.fetch(fetch)
var filesToKeep: Set<String> = []
for dictionary in mediaToKeep {
if let localPath = dictionary[localURLProperty] as? String,
let localURL = URL(string: localPath) {
filesToKeep.insert(localURL.lastPathComponent)
}
if let localThumbnailPath = dictionary[localThumbnailURLProperty] as? String,
let localThumbnailURL = URL(string: localThumbnailPath) {
filesToKeep.insert(localThumbnailURL.lastPathComponent)
}
}
try self.purgeDirectory(exceptFiles: filesToKeep)
if let onCompletion = onCompletion {
DispatchQueue.main.async {
onCompletion()
}
}
} catch {
DDLogError("Error while attempting to clean local media: \(error.localizedDescription)")
if let onError = onError {
DispatchQueue.main.async {
onError(error)
}
}
}
}
}
/// Removes files in the Media directory, except any files found in the set.
///
fileprivate func purgeDirectory(exceptFiles: Set<String>) throws {
let fileManager = FileManager.default
let contents = try fileManager.contentsOfDirectory(at: try directoryURL(),
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
var removedCount = 0
for url in contents {
if exceptFiles.contains(url.lastPathComponent) {
continue
}
if fileManager.fileExists(atPath: url.path) {
do {
try fileManager.removeItem(at: url)
removedCount += 1
} catch {
DDLogError("Error while removing unused Media at path: \(error.localizedDescription) - \(url.path)")
}
}
}
if removedCount > 0 {
DDLogInfo("Media: removed \(removedCount) file(s) during cleanup.")
}
}
}
| 5aeba595cb5a3b9de3bd92e02c177358 | 42.385417 | 134 | 0.630172 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | refs/heads/master | ch23-AdvGCD/DispatchDownload/DispatchDownload/ViewController.swift | mit | 1 | //
// ViewController.swift
// DispatchDownload
//
// Created by WJ on 15/12/1.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kHeaderDelimiterString = "\r\n\r\n"
class ViewController: UIViewController {
lazy var headerDelimiter = kHeaderDelimiterString.data(using: String.Encoding.utf8)!
func htons(_ value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8);
}
func connectToHostName(_ hostName:String,port:Int) -> Int32{
let s = socket(PF_INET,SOCK_STREAM,0)
guard s >= 0 else { assert(false , "socket failed:\(errno)") }
var sa = sockaddr_in()
sa.sin_family = UInt8( AF_INET )
sa.sin_port = htons(CUnsignedShort(port))
let he = gethostbyname(hostName)
if he == nil{
assert(false , "gethostbyname failure:\(errno)")
}
bcopy(he?.pointee.h_addr_list[0], &sa.sin_addr,Int( (he?.pointee.h_length)!) )
let cn = withUnsafePointer(to: &sa) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(s, UnsafePointer($0), socklen_t(MemoryLayout.size(ofValue: sa)))
}
}
if cn < 0{
assert(false , "cn<0")
}
return s
}
func outputFilePathForPath(_ path:String)->String{
return (NSTemporaryDirectory() as NSString ).appendingPathComponent((path as NSString).lastPathComponent)
}
func writeToChannel(_ channel:DispatchIO,writeData:DispatchData,queue:DispatchQueue){
channel.write(offset: 0, data: writeData, queue: queue) { (done , remainingData, error) -> Void in
assert(error == 0, "File write error:\(error )")
var unwrittenDataLength = 0
if remainingData != nil{
unwrittenDataLength = (remainingData?.count)!
}
print("Wrote \(writeData.count - unwrittenDataLength) bytes")
}
}
func handleDoneWithChannels(_ channels:[DispatchIO]){
print("Done Downloading")
for channel in channels{
channel.close(flags: DispatchIO.CloseFlags(rawValue: 0))
}
}
func findHeaderInData(_ newData:DispatchData,
previousData:inout DispatchData,
writeChannel:DispatchIO,
queue:DispatchQueue)->DispatchData?{
let mappedData = __dispatch_data_create_concat(previousData as __DispatchData, newData as __DispatchData)
var headerData :__DispatchData?
var bodyData :__DispatchData?
__dispatch_data_apply(mappedData) { (region, offset, buffer, size) -> Bool in
var bf = buffer
let search = NSData(bytesNoCopy: &bf, length: size, freeWhenDone: false)
let r = search.range(of: self.headerDelimiter, options: [], in: NSMakeRange(0, search.length))
if r.location != NSNotFound{
headerData = __dispatch_data_create_subrange(region, 0, r.location)
let body_offset = NSMaxRange(r)
let body_size = size - body_offset
bodyData = __dispatch_data_create_subrange(region, body_offset, body_size)
}
return false
}
if bodyData != nil{
writeToChannel(writeChannel, writeData: bodyData! as DispatchData, queue: queue)
}
return headerData! as DispatchData
}
func printHeader(_ headerData:DispatchData){
print("\nHeader:\n\n")
__dispatch_data_apply(headerData as __DispatchData) { (region, offset, buffer, size) -> Bool in
fwrite(buffer, size, 1, stdout)
return true
}
print("\n\n")
}
func readFromChannel(_ readChannel:DispatchIO,writeChannel:DispatchIO,queue:DispatchQueue){
var previousData = DispatchData.empty
var headerData : DispatchData?
readChannel.read(offset: 0,length: Int.max, queue: queue) { (serverReadDone, serverReadData, serverReadError) -> Void in
assert(serverReadError == 0, "Server read error:\(serverReadError)")
if serverReadData != nil{
self.handleDoneWithChannels([writeChannel,readChannel])
}else{
if headerData == nil{
headerData = self.findHeaderInData(serverReadData!, previousData: &previousData, writeChannel: writeChannel, queue: queue)
if headerData != nil{
self.printHeader(headerData!)
}
}
else{
self.writeToChannel(writeChannel, writeData: serverReadData!, queue: queue)
}
}
}
}
func requestDataForHostName(_ hostName:String,path:String)->DispatchData{
let getString = "GET \(path) HTTP/1.1\r\nHost: \(hostName)\r\n\r\n"
print("Request:\n\(getString)" )
let getData = getString.data(using: String.Encoding.utf8)
return DispatchData(referencing:getData!)
}
func HTTPDownloadContentsFromHostName(_ hostName:String,port:Int,path:String){
let queue = DispatchQueue.main
let socket = connectToHostName(hostName, port: port)
let serverChannel = DispatchIO(__type: DispatchIO.StreamType.stream.rawValue, fd: socket, queue: queue) { (error) in
assert(error == 0, "Failed socket:\(error )")
print("Closing connection")
close(socket)
}
let requestData = requestDataForHostName(hostName, path: path)
let writePath = outputFilePathForPath(path)
print("Writing to \(writePath)")
let fileChannel = DispatchIO(__type: DispatchIO.StreamType.stream.rawValue, path: writePath, oflag: O_WRONLY|O_CREAT|O_TRUNC, mode: S_IRWXU, queue: queue) {(error) in
}
serverChannel.write(offset: 0, data: requestData, queue: queue) { (serverWriteDone, serverWriteData, error ) -> Void in
assert(error == 0, "Failed socket:\(error )")
if serverWriteDone{
self.readFromChannel(serverChannel, writeChannel: fileChannel, queue: queue)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
HTTPDownloadContentsFromHostName("upload.wikimedia.org",
port: 80,
path: "/wikipedia/commons/9/97/The_Earth_seen_from_Apollo_17.jpg")
}
}
extension DispatchData {
init(referencing data: Data) {
guard !data.isEmpty else {
self = .empty
return
}
// will perform a copy if needed
let nsData = data as NSData
if let dispatchData = ((nsData as AnyObject) as? DispatchData) {
self = dispatchData
} else {
self = .empty
nsData.enumerateBytes { (bytes, byteRange, _) in
let innerData = Unmanaged.passRetained(nsData)
let buffer = UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: byteRange.length)
let chunk = DispatchData(bytesNoCopy: buffer, deallocator: .custom(nil, innerData.release))
append(chunk)
}
}
}
}
| 51057c1c121e04004c59721925f8b56c | 37.096939 | 174 | 0.577474 | false | false | false | false |
Contron/Dove | refs/heads/master | Dove/Dove.swift | mit | 1 | //
// Dove.swift
// Dove
//
// Created by Connor Haigh on 03/06/2016.
// Copyright © 2016 Connor Haigh. All rights reserved.
//
import Foundation
public typealias ActionBlock = () -> ()
public typealias ResultBlock = (Bool) -> ()
public typealias ProgressBlock = () -> Double
public let animationConstant = 0.3
public let shorterAnimationConstant = animationConstant / 2
public let longerAnimationConstant = animationConstant * 2
public let springDamping = CGFloat(0.5)
public let springInitialVelocity = CGFloat(0.1)
| d1b4d97fb8a512395c047b935c8b100e | 25.3 | 59 | 0.739544 | false | false | false | false |
Cellane/iWeb | refs/heads/master | Sources/App/Controllers/Web/Admin/AdminPostsController.swift | mit | 1 | import Vapor
import Paginator
extension Controllers.Web {
final class AdminPostsController {
private let droplet: Droplet
private let context = AdminContext()
init(droplet: Droplet) {
self.droplet = droplet
}
func addRoutes() {
let posts = droplet.grouped("admin", "posts")
let adminOrEditorAuthorized = posts.grouped(SessionRolesMiddleware(User.self, roles: [Role.admin, Role.editor]))
adminOrEditorAuthorized.get(handler: showPosts)
adminOrEditorAuthorized.get("new", handler: showNewPost)
adminOrEditorAuthorized.post("new", handler: createPost)
adminOrEditorAuthorized.get(Post.parameter, "edit", handler: showEditPost)
adminOrEditorAuthorized.post(Post.parameter, "edit", handler: editPost)
adminOrEditorAuthorized.get(Post.parameter, "delete", handler: deletePost)
adminOrEditorAuthorized.get(String.parameter, "restore", handler: restorePost)
}
func showPosts(req: Request) throws -> ResponseRepresentable {
let posts = try Post
.makeQuery()
.withSoftDeleted()
.sort(Post.createdAtKey, .descending)
.paginator(50, request: req)
return try droplet.view.makeDefault("admin/posts/list", for: req, [
"posts": posts.makeNode(in: context)
])
}
func showNewPost(req: Request) throws -> ResponseRepresentable {
return try droplet.view.makeDefault("admin/posts/edit", for: req)
}
func createPost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.post()
try post.save()
return Response(redirect: "/admin/posts")
.flash(.success, "Post created.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func showEditPost(req: Request) throws -> ResponseRepresentable {
let post = try req.parameters.next(Post.self)
return try droplet.view.makeDefault("admin/posts/edit", for: req, [
"post": post
])
}
func editPost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.parameters.next(Post.self)
try post.update(for: req)
try post.save()
return Response(redirect: "/admin/posts")
.flash(.success, "Post edited.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func deletePost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.parameters.next(Post.self)
try post.delete()
return Response(redirect: "/admin/posts")
.flash(.success, "Post deleted.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func restorePost(req: Request) throws -> ResponseRepresentable {
do {
let postId = try req.parameters.next(String.self)
let post = try Post.withSoftDeleted().find(postId)!
try post.restore()
return Response(redirect: "/admin/posts")
.flash(.success, "Post restored.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
}
}
| e8905597be04cef701549b30aebaeb41 | 27.37037 | 115 | 0.686031 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/Utilities/PurchaseHandler.swift | gpl-3.0 | 1 | //
// PurchaseHandler.swift
// Habitica
//
// Created by Phillip Thelen on 20.01.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import SwiftyStoreKit
import StoreKit
import Keys
import Shared
class PurchaseHandler: NSObject, SKPaymentTransactionObserver {
@objc static let shared = PurchaseHandler()
static let IAPIdentifiers = ["com.habitrpg.ios.Habitica.4gems", "com.habitrpg.ios.Habitica.21gems",
"com.habitrpg.ios.Habitica.42gems", "com.habitrpg.ios.Habitica.84gems"
]
static let subscriptionIdentifiers = ["subscription1month", "com.habitrpg.ios.habitica.subscription.3month",
"com.habitrpg.ios.habitica.subscription.6month", "com.habitrpg.ios.habitica.subscription.12month"
]
static let noRenewSubscriptionIdentifiers = ["com.habitrpg.ios.habitica.norenew_subscription.1month", "com.habitrpg.ios.habitica.norenew_subscription.3month",
"com.habitrpg.ios.habitica.norenew_subscription.6month", "com.habitrpg.ios.habitica.norenew_subscription.12month"
]
private let itunesSharedSecret = HabiticaKeys().itunesSharedSecret
private let appleValidator: AppleReceiptValidator
private let userRepository = UserRepository()
var pendingGifts = [String: String]()
private var hasCompletionHandler = false
override private init() {
#if DEBUG
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#else
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#endif
}
@objc
func completionHandler() {
if !SKPaymentQueue.canMakePayments() {
return
}
if hasCompletionHandler {
return
}
hasCompletionHandler = true
//Workaround for SwiftyStoreKit.completeTransactions not correctly returning consumable IAPs
SKPaymentQueue.default().add(self)
SwiftyStoreKit.completeTransactions(atomically: false) { _ in
}
SwiftyStoreKit.restorePurchases(atomically: false) { results in
if results.restoreFailedPurchases.isEmpty == false {
print("Restore Failed: \(results.restoreFailedPurchases)")
} else if results.restoredPurchases.isEmpty == false {
for purchase in results.restoredPurchases {
// fetch content from your server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("Restore Success: \(results.restoredPurchases)")
} else {
print("Nothing to Restore")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
if transactions.isEmpty == false {
for product in transactions {
RemoteLogger.shared.log(format: "Purchase: %@", arguments: getVaList([product.payment.productIdentifier]))
}
}
SwiftyStoreKit.fetchReceipt(forceRefresh: false) { result in
switch result {
case .success(let receiptData):
for transaction in transactions {
self.handleUnfinished(transaction: transaction, receiptData: receiptData)
}
case .error(let error):
RemoteLogger.shared.record(error: error)
}
}
}
func handleUnfinished(transaction: SKPaymentTransaction, receiptData: Data) {
let productIdentifier = transaction.payment.productIdentifier
if transaction.transactionState == .purchased || transaction.transactionState == .restored {
if self.isInAppPurchase(productIdentifier) {
self.activatePurchase(productIdentifier, receipt: receiptData) { status in
if status {
SwiftyStoreKit.finishTransaction(transaction)
}
}
} else if self.isSubscription(productIdentifier) {
self.userRepository.getUser().take(first: 1).on(value: {[weak self] user in
if !user.isSubscribed || user.purchased?.subscriptionPlan?.dateCreated == nil {
self?.applySubscription(transaction: transaction)
}
}).start()
} else if self.isNoRenewSubscription(productIdentifier) {
self.activateNoRenewSubscription(productIdentifier, receipt: receiptData, recipientID: self.pendingGifts[productIdentifier]) { status in
if status {
self.pendingGifts.removeValue(forKey: productIdentifier)
SwiftyStoreKit.finishTransaction(transaction)
}
}
}
} else if transaction.transactionState == .failed {
SwiftyStoreKit.finishTransaction(transaction)
}
}
func purchaseGems(_ identifier: String, applicationUsername: String, completion: @escaping (Bool) -> Void) {
SwiftyStoreKit.purchaseProduct(identifier, quantity: 1, atomically: false, applicationUsername: applicationUsername) { (result) in
switch result {
case .success(let product):
self.verifyPurchase(product)
completion(true)
case .error(let error):
RemoteLogger.shared.record(error: error)
completion(false)
}
}
}
func giftGems(_ identifier: String, applicationUsername: String, recipientID: String, completion: @escaping (Bool) -> Void) {
pendingGifts[identifier] = recipientID
SwiftyStoreKit.purchaseProduct(identifier, quantity: 1, atomically: false, applicationUsername: applicationUsername) { (result) in
switch result {
case .success(let product):
self.verifyPurchase(product)
completion(true)
case .error(let error):
RemoteLogger.shared.record(error: error)
completion(false)
}
}
}
func verifyPurchase(_ product: PurchaseDetails) {
SwiftyStoreKit.fetchReceipt(forceRefresh: false) { result in
switch result {
case .success(let receiptData):
// Verify the purchase of a Subscription
self.activatePurchase(product.productId, receipt: receiptData) { status in
if status {
if product.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(product.transaction)
}
}
}
case .error(let error):
RemoteLogger.shared.record(error: error)
print("Receipt verification failed: \(error)")
}
}
}
func activatePurchase(_ identifier: String, receipt: Data, completion: @escaping (Bool) -> Void) {
var recipientID: String? = nil
if let id = pendingGifts[identifier] {
recipientID = id
}
userRepository.purchaseGems(receipt: ["receipt": receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))], recipient: recipientID).observeValues {[weak self] (result) in
if result != nil {
if recipientID != nil {
self?.pendingGifts.removeValue(forKey: identifier)
}
completion(true)
} else {
completion(false)
}
}
}
func activateNoRenewSubscription(_ identifier: String, receipt: Data, recipientID: String?, completion: @escaping (Bool) -> Void) {
pendingGifts[identifier] = recipientID
if (recipientID == nil) {
completion(false)
return
}
userRepository.purchaseNoRenewSubscription(identifier: identifier,
receipt: ["receipt": receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))],
recipient: recipientID).observeValues {[weak self] (result) in
if result != nil {
self?.pendingGifts.removeValue(forKey: identifier)
completion(true)
} else {
completion(false)
}
}
}
func isInAppPurchase(_ identifier: String) -> Bool {
return PurchaseHandler.IAPIdentifiers.contains(identifier)
}
func isValidPurchase(_ identifier: String, receipt: ReceiptInfo) -> Bool {
if !isInAppPurchase(identifier) {
return false
}
let purchaseResult = SwiftyStoreKit.verifyPurchase(productId: identifier, inReceipt: receipt)
switch purchaseResult {
case .purchased:
return true
case .notPurchased:
return false
}
}
func activateSubscription(_ identifier: String, receipt: ReceiptInfo, completion: @escaping (Bool) -> Void) {
if let lastReceipt = receipt["latest_receipt"] as? String {
userRepository.subscribe(sku: identifier, receipt: lastReceipt).observeResult { (result) in
switch result {
case .success:
completion(true)
case .failure:
completion(false)
}
}
}
}
func isSubscription(_ identifier: String) -> Bool {
return PurchaseHandler.subscriptionIdentifiers.contains(identifier)
}
func isNoRenewSubscription(_ identifier: String) -> Bool {
return PurchaseHandler.noRenewSubscriptionIdentifiers.contains(identifier)
}
func isValidSubscription(_ identifier: String, receipt: ReceiptInfo) -> Bool {
if !isSubscription(identifier) {
return false
}
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable,
productId: identifier,
inReceipt: receipt,
validUntil: Date()
)
switch purchaseResult {
case .purchased:
return true
case .expired:
return false
case .notPurchased:
return false
}
}
private func applySubscription(transaction: SKPaymentTransaction) {
SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: {[weak self] (verificationResult) in
switch verificationResult {
case .success(let receipt):
if self?.isValidSubscription(transaction.payment.productIdentifier, receipt: receipt) == true {
self?.activateSubscription(transaction.payment.productIdentifier, receipt: receipt) { status in
if status {
SwiftyStoreKit.finishTransaction(transaction)
}
}
} else {
SwiftyStoreKit.finishTransaction(transaction)
}
case .error(let error):
RemoteLogger.shared.record(error: error)
}
})
}
}
| 8bf2fd90c00d5bfa770a9f818fd9161f | 40.405797 | 201 | 0.591617 | false | false | false | false |
cSquirrel/food-cam | refs/heads/develop | FoodCam/FoodCam/ExistingEntriesViewController.swift | apache-2.0 | 1 | //
// ExistingEntriesViewController.swift
// FoodCam
//
// Created by Marcin Maciukiewicz on 03/11/2016.
// Copyright © 2016 Marcin Maciukiewicz. All rights reserved.
//
import UIKit
class ExistingEntriesViewController: UITableViewController {
fileprivate var dailyEntries:[DailyEntries]? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
doRefresh(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doRefresh(_ sender: Any) {
dailyEntries = DataSource().findAllFoodEntries()
tableView.reloadData()
}
@IBAction func doEditEntry(_ sender: Any) {
print("doEditEntry")
}
@IBAction func doSwipe(_ sender: Any) {
print("doSwipe")
}
/*
// 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.
}
*/
}
// MARK: - UITableViewDelegate
extension ExistingEntriesViewController {
// public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// guard let day = dailyEntries?[indexPath.section] else {
// return
// }
//
//// let entry = day.entries[indexPath.row]
//// if let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: "addEntry") as? NewEntryViewController {
//// detailsVC.editMode(entry: entry)
//// navigationController?.pushViewController(detailsVC, animated: true)
//// }
// }
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
guard let day = dailyEntries?[indexPath.section] else {
return
}
let entry = day.entries[indexPath.row]
if let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: "addEntry") as? NewEntryViewController {
detailsVC.editMode(entry: entry)
navigationController?.pushViewController(detailsVC, animated: true)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true;
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let day = dailyEntries?[indexPath.section] {
let entry = day.entries[indexPath.row]
do {
try DataSource().delete(foodEntry: entry)
dailyEntries = DataSource().findAllFoodEntries()
tableView.deleteRows(at: [indexPath], with: .automatic)
} catch let error as NSError {
print(error)
}
}
}
}
}
// MARK: - UITableViewDataSource
extension ExistingEntriesViewController {
public override func numberOfSections(in tableView: UITableView) -> Int {
guard let e = dailyEntries else {
return 1
}
return e.count
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let de = dailyEntries else {
return 0
}
let e = de[section].entries
return e.count
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let e = dailyEntries else {
return nil
}
let result:String?
let date = e[section].date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
result = dateFormatter.string(from: date)
return result
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "EntryDetails"
let result = tableView.dequeueReusableCell(withIdentifier: cellID)
// if (result == nil) {
// result = UITableViewCell(style: .default, reuseIdentifier: cellID)
// }
if let day = dailyEntries?[indexPath.section] {
let entry = day.entries[indexPath.row]
result?.textLabel?.text = "\(entry.createdAt)"
}
return result!
}
}
| 9ff451586c5589a39405d406005bd47e | 29.968553 | 136 | 0.609058 | false | false | false | false |
gerardogrisolini/iWebretail | refs/heads/master | iWebretail/MovementController.swift | apache-2.0 | 1 | //
// MovementController.swift
// iWebretail
//
// Created by Gerardo Grisolini on 12/04/17.
// Copyright © 2017 Gerardo Grisolini. All rights reserved.
//
import UIKit
class MovementController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var amountLabel: UILabel!
var label: UILabel!
var movementArticles: [MovementArticle]
private var repository: MovementArticleProtocol
required init?(coder aDecoder: NSCoder) {
self.movementArticles = []
repository = IoCContainer.shared.resolve() as MovementArticleProtocol
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
makeBar()
}
func makeBar() {
// badge label
label = UILabel(frame: CGRect(x: 8, y: -4, width: 29, height: 20))
label.layer.borderColor = UIColor.clear.cgColor
label.layer.borderWidth = 2
label.layer.cornerRadius = label.bounds.size.height / 2
label.textAlignment = .center
label.layer.masksToBounds = true
label.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 600))
label.textColor = .darkText
if Synchronizer.shared.movement.completed {
label.backgroundColor = UIColor(name: "whitesmoke")
} else {
label.backgroundColor = UIColor(name: "lightgreen")
}
// button
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 29, height: 29))
let basket = UIImage(named: "basket")?.withRenderingMode(.alwaysTemplate)
rightButton.setImage(basket, for: .normal)
rightButton.tintColor = UINavigationBar.appearance().tintColor
rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside)
rightButton.addSubview(label)
// Bar button item
self.tabBarController?.tabBar.tintColor = UINavigationBar.appearance().tintColor
self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
}
@objc func rightButtonTouched(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "RegisterView") as! RegisterController
self.navigationController!.pushViewController(vc, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
self.movementArticles = try! repository.getAll(id: Synchronizer.shared.movement.movementId)
self.updateAmount()
tableView.reloadData()
}
@IBAction func stepperValueChanged(_ sender: UIStepper) {
let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView)
let indexPath = self.tableView.indexPathForRow(at: point)!
let item = movementArticles[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
item.movementArticleQuantity = sender.value
cell.textQuantity.text = String(sender.value)
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
try! repository.update(id: item.movementArticleId, item: item)
self.updateAmount()
}
@IBAction func textValueChanged(_ sender: UITextField) {
let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView)
let indexPath = self.tableView.indexPathForRow(at: point)!
let item = movementArticles[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
if sender == cell.textQuantity {
item.movementArticleQuantity = Double(sender.text!)!
cell.stepperQuantity.value = item.movementArticleQuantity
} else {
item.movementArticlePrice = Double(sender.text!)!
}
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
try! repository.update(id: item.movementArticleId, item: item)
self.updateAmount()
}
func updateAmount() {
let amount = movementArticles
.map { $0.movementArticleQuantity * $0.movementArticlePrice as Double }
.reduce (0, +)
amountLabel.text = amount.formatCurrency()
let quantity = movementArticles
.map { $0.movementArticleQuantity }
.reduce (0, +)
label.text = quantity.description
if Synchronizer.shared.movement.movementAmount != amount {
try! repository.updateAmount(item: Synchronizer.shared.movement, amount: amount)
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movementArticles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) as! ArticleCell
let index = (indexPath as NSIndexPath).row
let item = movementArticles[index]
cell.labelBarcode.text = item.movementArticleBarcode
cell.labelName.text = item.movementProduct
cell.textPrice.text = String(item.movementArticlePrice)
cell.textQuantity.text = String(item.movementArticleQuantity)
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
cell.stepperQuantity.value = item.movementArticleQuantity
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return !Synchronizer.shared.movement.completed
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
do {
try repository.delete(id: self.movementArticles[indexPath.row].movementArticleId)
self.movementArticles.remove(at: indexPath.row)
self.updateAmount()
tableView.deleteRows(at: [indexPath], with: .fade)
} catch {
self.navigationController?.alert(title: "Error".locale, message: "\(error)")
}
}
}
}
| 6abad016cc39a1c41d9dbcebe7f8ee05 | 37.970588 | 127 | 0.653887 | false | false | false | false |
mikewxk/DYLiveDemo_swift | refs/heads/master | DYLiveDemo/DYLiveDemo/Classes/Tools/Common.swift | unlicense | 1 | //
// Common.swift
// DYLiveDemo
//
// Created by xiaokui wu on 12/16/16.
// Copyright © 2016 wxk. All rights reserved.
//
import UIKit
let kStatusBarHeight: CGFloat = 20
let kNavigationBarHeight: CGFloat = 44
let kTabBarHeight: CGFloat = 44
let kScreenWidth = UIScreen.mainScreen().bounds.width
let kScreenHeight = UIScreen.mainScreen().bounds.height
| 2ea9c7b379167d396380e3b166628520 | 19.055556 | 55 | 0.736842 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | GoDToolCL/main.swift | gpl-2.0 | 1 | //
// main.swift
// XGCommandLineTools
//
// Created by StarsMmd on 13/11/2015.
// Copyright © 2015 StarsMmd. All rights reserved.
//
//
import Foundation
ToolProcess.loadISO(exitOnFailure: true)
var countDownDate: Date?
var posterFile: XGFiles?
var musicScriptFile: XGFiles?
var iso: XGFiles?
var argsAreInvalid = false
let args = CommandLine.arguments
for i in 0 ..< args.count {
guard i < args.count - 1 else { continue }
let arg = args[i]
let next = args[i + 1]
if arg == "--launch-dpp-date" {
countDownDate = Date.fromString(next)
if countDownDate == nil {
let secondsToDecember: Double = 31_104_000
print("Invalid arg for \(arg) \(next)\nDate must be of format:", Date(timeIntervalSince1970: secondsToDecember).referenceString())
argsAreInvalid = true
}
} else if arg == "--launch-dpp-secs",
let seconds = next.integerValue {
countDownDate = Date(timeIntervalSinceNow: Double(seconds))
} else if arg == "-i" || arg == "--iso" {
let file = XGFiles.path(next)
if file.fileType == .iso {
iso = file
}
if !file.exists {
print("Invalid arg for \(arg).\nFile doesn't exist:", file.path)
argsAreInvalid = true
}
} else if arg == "-s" || arg == "--silent-logs" {
silentLogs = true
}
}
if argsAreInvalid {
ToolProcess.terminate()
}
if let isoFile = iso {
XGISO.loadISO(file: isoFile)
}
DiscordPlaysOrre().launch()
| cdea0a9034e1f2c29bd87de933eb3c76 | 22.724138 | 133 | 0.672965 | false | false | false | false |
TwoRingSoft/shared-utils | refs/heads/master | Examples/Pippin/Pods/Closures/Xcode/Closures/Source/KVO.swift | mit | 2 | /**
The MIT License (MIT)
Copyright (c) 2017 Vincent Hesener
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
extension NSObject {
public var selfDeinits: (_KeyValueCodingAndObserving) -> Bool {
return { [weak self] _ in
return self == nil
}
}
}
extension _KeyValueCodingAndObserving {
/**
This convenience method puts only a tiny bit of polish on
Swift's latest closure-based KVO implementation. Although
there aren't many obvious differences between this
method and the one in `Foundation`, there are a few helpers, which
are describe below.
First, it passes a remove condition, `until`, which is simpy a closure
that gets called to determine whether to remove the observation
closure. Returning true will remove the observer, otherwise, the
observing will continue. `Foundation`'s method
automatically removes observation when the `NSKeyValueObservation`
is released, but this requires you to save it somewhere in your
view controller as a property, thereby cluttering up your view
controller with plumbing-only members.
Second, this method attempts to slightly improve the clutter. You
do not have to save the observer. `@discardableResult` allows you
to disregard the returned object entirely.
Finally, a typical pattern is to remove observers when deinit is
called on the object that owns the observed object.
For instance, if you are observing a model object property on your
view controller, you will probably want to stop observing when the
view controller gets released from memory. Because this is a
common pattern, there's a convenient var available on all subclasses
of NSObject named `selfDeinits`. Simply pass this as a parameter
into the `until` paramaeter, and the observation will be removed
when `self` is deallocated.
* * * *
#### An example of calling this method:
```swift
<#someObject#>.observe(\.<#some.key.path#>, until: selfDeinits) { obj,change in
<#do something#>
}
```
* parameter keyPath: The keyPath you wish to observe on this object
* parameter options: The observing options
* parameter until: The closure called when this handler should stop
observing. Return true if you want to forcefully stop observing.
* parameter changeHandler: The callback that will be called when
the keyPath change has occurred.
* returns: The observer object needed to remove observation
*/
@discardableResult
public func observe<Value>(
_ keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
until removeCondition: @escaping (Self) -> Bool,
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
-> NSKeyValueObservation {
var observer: NSKeyValueObservation?
observer = self.observe(keyPath, options: options) { obj, change in
guard !removeCondition(obj) else {
observer?.invalidate()
observer = nil
return
}
changeHandler(obj, change)
}
return observer!
}
}
| f1f8bcbe72a4072edc03870503283505 | 43.505155 | 98 | 0.697475 | false | false | false | false |
WIND-FIRE-WHEEL/WFWCUSTOMIM | refs/heads/master | IMDemo/IMDemo/Profile/Macros.swift | mit | 1 | //
// Macros.swift
// IMDemo
//
// Created by 徐往 on 2017/7/25.
// Copyright © 2017年 徐往. All rights reserved.
//
import Foundation
let IM = PublicTools()
class PublicTools:NSObject {
let screenSize:CGSize = UIScreen.main.bounds.size
let screenNavHeight:CGFloat = 64.0
let screenTabHeight:CGFloat = 49.0
let defaultKeyboardHeight:CGFloat = 50.0
}
enum SendMessage :NSInteger{
case otherSend = 0
case mineSend = 1
}
extension UIView {
var xw_width:CGFloat {
get {
return self.frame.size.width
}
}
var xw_height:CGFloat {
get {
return self.frame.size.height
}
}
var xw_y:CGFloat {
get {
return self.frame.origin.y
}
}
var xw_x:CGFloat {
get {
return self.frame.origin.x
}
}
}
| 1de974da486983b0732031f1eeee84f1 | 15.823529 | 53 | 0.56993 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | refs/heads/master | TranslationEditor/SquishableStackView.swift | mit | 1 | //
// SquishableStackView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 15.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// These stack views can be squished a little when necessary
class SquishableStackView: UIStackView, Squishable
{
// ATTRIBUTES --------------
@IBInspectable var minSpacing: CGFloat = 0
private var originalSpacing: CGFloat?
// IMPLEMENTED METHODS ------
func setSquish(_ isSquished: Bool, along axis: UILayoutConstraintAxis)
{
// Can only be squished along it's own axis
if axis == self.axis
{
if isSquished
{
if originalSpacing == nil
{
originalSpacing = spacing
}
spacing = minSpacing
}
else if let originalSpacing = originalSpacing
{
spacing = originalSpacing
self.originalSpacing = nil
}
}
}
}
| 3adb6828ec8cdd41eb0b5fb9cb90d22d | 18.465116 | 71 | 0.670251 | false | false | false | false |
AlexRamey/mbird-iOS | refs/heads/master | Pods/Nuke/Sources/Cache.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
/// In-memory image cache.
///
/// The implementation must be thread safe.
public protocol Caching: class {
/// Accesses the image associated with the given key.
subscript(key: AnyHashable) -> Image? { get set }
// unfortunately there is a lot of extra work happening here because key
// types are not statically defined, might be worth rethinking cache
}
public extension Caching {
/// Accesses the image associated with the given request.
public subscript(request: Request) -> Image? {
get { return self[request.cacheKey] }
set { self[request.cacheKey] = newValue }
}
}
/// Memory cache with LRU cleanup policy (least recently used are removed first).
///
/// The elements stored in cache are automatically discarded if either *cost* or
/// *count* limit is reached. The default cost limit represents a number of bytes
/// and is calculated based on the amount of physical memory available on the
/// device. The default count limit is set to `Int.max`.
///
/// `Cache` automatically removes all stored elements when it received a
/// memory warning. It also automatically removes *most* of cached elements
/// when the app enters background.
public final class Cache: Caching {
// We don't use `NSCache` because it's not LRU
private var map = [AnyHashable: LinkedList<CachedImage>.Node]()
private let list = LinkedList<CachedImage>()
private let lock = NSLock()
/// The maximum total cost that the cache can hold.
public var costLimit: Int {
didSet { lock.sync(_trim) }
}
/// The maximum number of items that the cache can hold.
public var countLimit: Int {
didSet { lock.sync(_trim) }
}
/// The total cost of items in the cache.
public private(set) var totalCost = 0
/// The total number of items in the cache.
public var totalCount: Int {
return map.count
}
/// Shared `Cache` instance.
public static let shared = Cache()
/// Initializes `Cache`.
/// - parameter costLimit: Default value representes a number of bytes and is
/// calculated based on the amount of the phisical memory available on the device.
/// - parameter countLimit: `Int.max` by default.
public init(costLimit: Int = Cache.defaultCostLimit(), countLimit: Int = Int.max) {
self.costLimit = costLimit
self.countLimit = countLimit
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(self, selector: #selector(removeAll), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: .UIApplicationDidEnterBackground, object: nil)
#endif
}
deinit {
#if os(iOS) || os(tvOS)
NotificationCenter.default.removeObserver(self)
#endif
}
/// Returns a recommended cost limit which is computed based on the amount
/// of the phisical memory available on the device.
public static func defaultCostLimit() -> Int {
let physicalMemory = ProcessInfo.processInfo.physicalMemory
let ratio = physicalMemory <= (536_870_912 /* 512 Mb */) ? 0.1 : 0.2
let limit = physicalMemory / UInt64(1 / ratio)
return limit > UInt64(Int.max) ? Int.max : Int(limit)
}
/// Accesses the image associated with the given key.
public subscript(key: AnyHashable) -> Image? {
get {
lock.lock(); defer { lock.unlock() } // slightly faster than `sync()`
guard let node = map[key] else {
return nil
}
// bubble node up to make it last added (most recently used)
list.remove(node)
list.append(node)
return node.value.image
}
set {
lock.lock(); defer { lock.unlock() } // slightly faster than `sync()`
if let image = newValue {
_add(CachedImage(image: image, cost: cost(image), key: key))
_trim() // _trim is extremely fast, it's OK to call it each time
} else {
if let node = map[key] {
_remove(node: node)
}
}
}
}
private func _add(_ element: CachedImage) {
if let existingNode = map[element.key] {
_remove(node: existingNode)
}
map[element.key] = list.append(element)
totalCost += element.cost
}
private func _remove(node: LinkedList<CachedImage>.Node) {
list.remove(node)
map[node.value.key] = nil
totalCost -= node.value.cost
}
/// Removes all cached images.
@objc public dynamic func removeAll() {
lock.sync {
map.removeAll()
list.removeAll()
totalCost = 0
}
}
private func _trim() {
_trim(toCost: costLimit)
_trim(toCount: countLimit)
}
@objc private dynamic func didEnterBackground() {
// Remove most of the stored items when entering background.
// This behavior is similar to `NSCache` (which removes all
// items). This feature is not documented and may be subject
// to change in future Nuke versions.
lock.sync {
_trim(toCost: Int(Double(costLimit) * 0.1))
_trim(toCount: Int(Double(countLimit) * 0.1))
}
}
/// Removes least recently used items from the cache until the total cost
/// of the remaining items is less than the given cost limit.
public func trim(toCost limit: Int) {
lock.sync { _trim(toCost: limit) }
}
private func _trim(toCost limit: Int) {
_trim(while: { totalCost > limit })
}
/// Removes least recently used items from the cache until the total count
/// of the remaining items is less than the given count limit.
public func trim(toCount limit: Int) {
lock.sync { _trim(toCount: limit) }
}
private func _trim(toCount limit: Int) {
_trim(while: { totalCount > limit })
}
private func _trim(while condition: () -> Bool) {
while condition(), let node = list.first { // least recently used
_remove(node: node)
}
}
/// Returns cost for the given image by approximating its bitmap size in bytes in memory.
public var cost: (Image) -> Int = {
#if os(macOS)
return 1
#else
// bytesPerRow * height gives a rough estimation of how much memory
// image uses in bytes. In practice this algorithm combined with a
// concervative default cost limit works OK.
guard let cgImage = $0.cgImage else {
return 1
}
return cgImage.bytesPerRow * cgImage.height
#endif
}
}
private struct CachedImage {
let image: Image
let cost: Int
let key: AnyHashable
}
| 07f6550ca02df3b6bec19200902d08cc | 32.597156 | 150 | 0.615602 | false | false | false | false |
swiftix/swift.old | refs/heads/master | test/Generics/function_defs.swift | apache-2.0 | 1 | // RUN: %target-parse-verify-swift
//===----------------------------------------------------------------------===//
// Type-check function definitions
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Basic type checking
//===----------------------------------------------------------------------===//
protocol EqualComparable {
func isEqual(other: Self) -> Bool
}
func doCompare<T : EqualComparable, U : EqualComparable>(t1: T, t2: T, u: U) -> Bool {
var b1 = t1.isEqual(t2)
if b1 {
return true;
}
return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}}
// expected-note @-1 {{expected an argument list of type '(Self)'}}
}
protocol MethodLessComparable {
func isLess(other: Self) -> Bool
}
func min<T : MethodLessComparable>(x: T, y: T) -> T {
if (y.isLess(x)) { return y }
return x
}
//===----------------------------------------------------------------------===//
// Interaction with existential types
//===----------------------------------------------------------------------===//
func existential<T : EqualComparable, U : EqualComparable>(t1: T, t2: T, u: U) {
var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
eqComp = u
if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}}
// expected-note @-1 {{expected an argument list of type '(Self)'}}
if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}}
}
protocol OtherEqualComparable {
func isEqual(other: Self) -> Bool
}
func otherExistential<T : EqualComparable>(t1: T) {
var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}}
otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp
var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}}
otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp2
_ = t1 as protocol<EqualComparable, OtherEqualComparable> // expected-error{{'T' is not convertible to 'protocol<EqualComparable, OtherEqualComparable>'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
}
protocol Runcible {
func runce<A>(x: A)
func spoon(x: Self)
}
func testRuncible(x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}}
x.runce(5)
}
//===----------------------------------------------------------------------===//
// Overloading
//===----------------------------------------------------------------------===//
protocol Overload {
typealias A
typealias B
func getA() -> A
func getB() -> B
func f1(_: A) -> A
func f1(_: B) -> B
func f2(_: Int) -> A // expected-note{{found this candidate}}
func f2(_: Int) -> B // expected-note{{found this candidate}}
func f3(_: Int) -> Int // expected-note {{found this candidate}}
func f3(_: Float) -> Float // expected-note {{found this candidate}}
func f3(_: Self) -> Self // expected-note {{found this candidate}}
var prop : Self { get }
}
func testOverload<Ovl : Overload, OtherOvl : Overload>(ovl: Ovl, ovl2: Ovl,
other: OtherOvl) {
var a = ovl.getA()
var b = ovl.getB()
// Overloading based on arguments
ovl.f1(a)
a = ovl.f1(a)
ovl.f1(b)
b = ovl.f1(b)
// Overloading based on return type
a = ovl.f2(17)
b = ovl.f2(17)
ovl.f2(17) // expected-error{{ambiguous use of 'f2'}}
// Check associated types from different objects/different types.
a = ovl2.f2(17)
a = ovl2.f1(a)
other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}}
// expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}}
// Overloading based on context
var f3i : (Int) -> Int = ovl.f3
var f3f : (Float) -> Float = ovl.f3
var f3ovl_1 : (Ovl) -> Ovl = ovl.f3
var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3
var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}}
var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3
var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3
var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3
var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3
var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol Subscriptable {
typealias Index
typealias Value
func getIndex() -> Index
func getValue() -> Value
subscript (index : Index) -> Value { get set }
}
protocol IntSubscriptable {
typealias ElementType
func getElement() -> ElementType
subscript (index : Int) -> ElementType { get }
}
func subscripting<T : protocol<Subscriptable, IntSubscriptable>>(t: T) {
var index = t.getIndex()
var value = t.getValue()
var element = t.getElement()
value = t[index]
t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}}
element = t[17]
t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}}
t[value] = 17 // expected-error{{cannot subscript a value of type 'T' with an index of type 'T.Value'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Self.Index), (Int)}}
}
//===----------------------------------------------------------------------===//
// Static functions
//===----------------------------------------------------------------------===//
protocol StaticEq {
static func isEqual(x: Self, y: Self) -> Bool
}
func staticEqCheck<T : StaticEq, U : StaticEq>(t: T, u: U) {
if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}}
if T.isEqual(t, y: t) { return }
if U.isEqual(u, y: u) { return }
T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}}
// expected-note @-1 {{expected an argument list of type '(Self, y: Self)'}}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Ordered {
func <(lhs: Self, rhs: Self) -> Bool
}
func testOrdered<T : Ordered>(x: T, y: Int) {
if y < 100 || 500 < y { return }
if x < x { return }
}
//===----------------------------------------------------------------------===//
// Requires clauses
//===----------------------------------------------------------------------===//
func conformanceViaRequires<T
where T : EqualComparable, T : MethodLessComparable
>(t1: T, t2: T) -> Bool {
let b1 = t1.isEqual(t2)
if b1 || t1.isLess(t2) {
return true;
}
}
protocol GeneratesAnElement {
typealias Element : EqualComparable
func generate() -> Element
}
protocol AcceptsAnElement {
typealias Element : MethodLessComparable
func accept(e : Element)
}
func impliedSameType<T : GeneratesAnElement where T : AcceptsAnElement>(t: T) {
t.accept(t.generate())
let e = t.generate(), e2 = t.generate()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
protocol GeneratesAssoc1 {
typealias Assoc1 : EqualComparable
func get() -> Assoc1
}
protocol GeneratesAssoc2 {
typealias Assoc2 : MethodLessComparable
func get() -> Assoc2
}
func simpleSameType
<T : GeneratesAssoc1, U : GeneratesAssoc2 where T.Assoc1 == U.Assoc2>
(t: T, u: U) -> Bool
{
return t.get().isEqual(u.get()) || u.get().isLess(t.get())
}
protocol GeneratesMetaAssoc1 {
typealias MetaAssoc1 : GeneratesAnElement
func get() -> MetaAssoc1
}
protocol GeneratesMetaAssoc2 {
typealias MetaAssoc2 : AcceptsAnElement
func get() -> MetaAssoc2
}
func recursiveSameType
<T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1
where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2>
(t: T, u: U)
{
t.get().accept(t.get().generate())
let e = t.get().generate(), e2 = t.get().generate()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
// <rdar://problem/13985164>
protocol P1 {
typealias Element
}
protocol P2 {
typealias AssocP1 : P1
func getAssocP1() -> AssocP1
}
func beginsWith2<
E0: P1, E1: P1
where
E0.Element == E1.Element,
E0.Element : EqualComparable
>(e0: E0, _ e1: E1) -> Bool
{
}
func beginsWith3<
S0: P2, S1: P2
where
S0.AssocP1.Element == S1.AssocP1.Element,
S1.AssocP1.Element : EqualComparable
>(seq1: S0, _ seq2: S1) -> Bool
{
return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1())
}
// FIXME: Test same-type constraints that try to equate things we
// don't want to equate, e.g., T == U.
//===----------------------------------------------------------------------===//
// Bogus requirements
//===----------------------------------------------------------------------===//
func nonTypeReq<T where T : Wibble>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}}
func badProtocolReq<T where T : Int>(_: T) {} // expected-error{{type 'T' constrained to non-protocol type 'Int'}}
func nonTypeSameType<T where T == Wibble>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}}
func nonTypeSameType2<T where Wibble == T>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}}
func sameTypeEq<T where T = T>(_: T) {} // expected-error{{use '==' for same-type requirements rather than '='}} {{27-28===}}
func badTypeConformance1<T where Int : EqualComparable>(_: T) {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance2<T where T.Blarg : EqualComparable>(_: T) { } // expected-error{{'Blarg' is not a member type of 'T'}}
func badSameType<T, U : GeneratesAnElement, V // expected-error{{generic parameter 'V' is not used in function signature}}
where T == U.Element,
U.Element == V // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
>(_: T) {}
| ea05df5dae6a127f4d52980733468805 | 34.660194 | 393 | 0.571558 | false | false | false | false |
priya273/stockAnalyzer | refs/heads/master | Stock Analyzer/Stock Analyzer/ErrorLoginFaceBookViewController.swift | apache-2.0 | 1 | //
// ErrorLoginFaceBookViewController.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/16/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import FBSDKCoreKit
class ErrorLoginFaceBookViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.alertTheUserSomethingWentWrong("Try again", message:"Something went Wrong", actionTitle: "okay")
ShowFaceBookLogin()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Mark :- Alert Controller
func alertTheUserSomethingWentWrong(titleforController: String, message : String, actionTitle: String)
{
let controller = UIAlertController(title: titleforController , message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Cancel, handler: nil)
controller.addAction(action)
self.presentViewController(controller, animated: true, completion: nil)
}
func ShowFaceBookLogin()
{
FBSDKAccessToken.setCurrentAccessToken(nil)
let facebookloginpage = self.storyboard?.instantiateViewControllerWithIdentifier("FaceBookLoginViewController") as! FaceBookLoginViewController
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
appDel.window?.rootViewController = facebookloginpage
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 0e3d127e306101bb02ac2b70775162e1 | 33.810345 | 151 | 0.718673 | false | false | false | false |
thiagotmb/BEPiD-Challenges-2016 | refs/heads/master | 2016-04-06-Complications/WeatherForecasts/WeatherForecasts WatchKit Extension/ComplicationController.swift | mit | 2 | //
// ComplicationController.swift
// WeatherForecasts WatchKit Extension
//
// Created by Thiago-Bernardes on 4/8/16.
// Copyright © 2016 TB. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward, .Backward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let firstForecast = ForecastsModel.getArrayDictionary().firstObject
handler(firstForecast?["dateWind"] as? NSDate)
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let lastForecast = ForecastsModel.getArrayDictionary().lastObject
handler(lastForecast?["dateWind"] as? NSDate)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
let currentComplication = getComplicationTemplateForDate(complication, date: NSDate())
let entry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: currentComplication)
handler(entry)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
let foreCasts = ForecastsModel.getForecastsBefore(date)
let entries = foreCasts.flatMap { currentForecast in
CLKComplicationTimelineEntry(
date: currentForecast["dateWind"] as! NSDate,
complicationTemplate: getComplicationTemplateForDate(complication, date: currentForecast["dateWind"] as! NSDate))
}
handler(entries)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
let foreCasts = ForecastsModel.getForecastsAfter(date)
let entries = foreCasts.flatMap { currentForecast in
CLKComplicationTimelineEntry(
date: currentForecast["dateWind"] as! NSDate,
complicationTemplate: getComplicationTemplateForDate(complication, date: currentForecast["dateWind"] as! NSDate))
}
handler(entries)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
let oneDayInterval = NSTimeInterval(60*60*24)
handler(NSDate().dateByAddingTimeInterval(oneDayInterval));
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
let template = getComplicationTemplateForDate(complication, date: NSDate(),isTemplate: true)
handler(template)
}
func getComplicationTemplateForDate(complication: CLKComplication,date: NSDate, isTemplate: Bool = false) -> CLKComplicationTemplate{
var forecast = ["dateWind": NSDate(), "velocity": "30"]
if !isTemplate {
forecast = ForecastsModel.getForecastOf(date)
}
if complication.family == .ModularLarge {
let complicationTemplate = CLKComplicationTemplateModularLargeStandardBody()
complicationTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Wind Forecasts")
complicationTemplate.body1TextProvider = CLKSimpleTextProvider(text: "Speed: \((forecast["velocity"] as! NSString))")
complicationTemplate.body2TextProvider = CLKSimpleTextProvider(text: "\((forecast["dateWind"] as! NSDate))")
return complicationTemplate
}
return CLKComplicationTemplate()
}
func getTimelineAnimationBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineAnimationBehavior) -> Void) {
handler(CLKComplicationTimelineAnimationBehavior.Grouped)
}
}
| bc336aba490b8aa8237f2884189d4704 | 44.638889 | 178 | 0.706026 | false | false | false | false |
TCA-Team/iOS | refs/heads/master | TUM Campus App/News.swift | gpl-3.0 | 1 | //
// News.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import Sweeft
final class News: DataElement {
let id: String
let source: Source
let date: Date
let title: String
let link: String
let imageUrl: String?
init(id: String, source: Source, date: Date, title: String, link: String, imageUrl: String? = nil) {
self.id = id
self.source = source
self.date = date
self.title = title
self.link = link
self.imageUrl = imageUrl
}
var text: String {
get {
return title
}
}
func getCellIdentifier() -> String {
return "news"
}
func open(sender: UIViewController? = nil) {
link.url?.open(sender: sender)
}
}
extension News: Deserializable {
convenience init?(from json: JSON) {
guard let title = json["title"].string,
let source = json["src"].string.flatMap(Int.init).map(News.Source.init(identifier:)),
let link = json["link"].string,
let date = json["date"].date(using: "yyyy-MM-dd HH:mm:ss"),
let id = json["news"].string else {
return nil
}
self.init(id: id, source: source, date: date, title: title, link: link, imageUrl: json["image"].string)
}
}
extension News: Equatable {
static func == (lhs: News, rhs: News) -> Bool {
return lhs.id == rhs.id
}
}
| 40aa1ae152ca795bab64e865b7fdfd29 | 26.987013 | 111 | 0.612529 | false | false | false | false |
hironytic/Kiretan0 | refs/heads/master | Kiretan0/AppFramework/TableUI/CheckableTableCell.swift | mit | 1 | //
// CheckableTableCell.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <[email protected]>
//
// 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 RxSwift
import RxCocoa
public class CheckableTableCell: BaseTableCell<CheckableTableCellViewModel> {
private var _disposeBag: DisposeBag?
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
fatalError()
}
public override var viewModel: CheckableTableCellViewModel? {
didSet {
_disposeBag = nil
guard let viewModel = viewModel else { return }
let disposeBag = DisposeBag()
if let textLabel = textLabel {
textLabel.text = viewModel.text
}
viewModel.checked
.bind(to: Binder(self) { me, checked in
me.accessoryType = checked ? .checkmark : .none
})
.disposed(by: disposeBag)
_disposeBag = disposeBag
}
}
}
| 784cd9995ca57331d6257f7bbb1c4c4e | 35.225806 | 81 | 0.668299 | false | false | false | false |
barteljan/RocketChatAdapter | refs/heads/master | Pod/Classes/RocketChatAdapter.swift | mit | 1 | //
// RocketChatAdapter.swift
// Pods
//
// Created by Jan Bartel on 12.03.16.
//
//
import VISPER_CommandBus
import SwiftDDP
import XCGLogger
public enum RocketChatAdapterError : ErrorType {
case ServerDidResponseWithEmptyResult(fileName:String,function: String,line: Int,column: Int)
case RequiredResponseFieldWasEmpty(field:String,fileName:String,function: String,line: Int,column: Int)
}
public struct RocketChatAdapter : RocketChatAdapterProtocol{
let commandBus : CommandBusProtocol
let endPoint : String
/**
* initialiser
**/
public init(endPoint:String){
self.init(endPoint:endPoint,commandBus: nil)
}
public init(endPoint:String,commandBus: CommandBusProtocol?){
self.endPoint = endPoint
if(commandBus != nil){
self.commandBus = commandBus!
}else{
self.commandBus = CommandBus()
}
}
/**
* Connect to server
**/
public func connect(endpoint:String,callback:(() -> ())?){
Meteor.client.logLevel = .Info
Meteor.connect(endpoint,callback: callback)
}
/**
* Register user
**/
public func register(email: String,name: String,password: String,completion: ((userId: String?, error: ErrorType?) -> Void)?){
let command = RegisterCommand(email: email, name: name, password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(RegisterCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(userId: result,error: error)
}
}
/**
* Get username suggestion
**/
public func usernameSuggestion(completion:((username: String?,error:ErrorType?)->Void)?){
let command = GetUserNameSuggestionCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetUserNameSuggestionCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Set username
**/
public func setUsername(username:String,completion:((username: String?,error:ErrorType?)->Void)?){
let command = SetUserNameCommand(username:username)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SetUsernameCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Send Forgot password email
**/
public func sendForgotPasswordEmail(usernameOrMail: String, completion:((result: Int?,error: ErrorType?)->Void)?){
let command = SendForgotPasswordEMailCommand(userNameOrMail: usernameOrMail)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendForgotPasswordEMailCommandHandler())
}
try! self.commandBus.process(command) { (result: Int?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Logon
**/
public func login(userNameOrEmail: String, password: String, completion:((result: AuthorizationResultProtocol?,error:ErrorType?)->Void)?){
let command = LogonCommand(userNameOrEmail:userNameOrEmail,password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LogonCommandHandler())
}
try! self.commandBus.process(command) { (result: AuthorizationResultProtocol?, error: ErrorType?) -> Void in
completion?(result:result,error: error)
}
}
/**
* get all public channels
**/
public func channelList(completion:((result: [ChannelProtocol]?,error: ErrorType?)->Void)?){
let command = GetChannelsCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelsCommandHandler())
}
try! self.commandBus.process(command) { (result: [ChannelProtocol]?, error: ErrorType?) -> Void in
completion?(result: result, error: error)
}
}
/**
* get a channels id by its name
*/
public func getChannelId(name:String, completion:((roomId:String?, error: ErrorType?)->Void)?){
let command = GetRoomIdCommand(roomName: name)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetRoomIdCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(roomId: result, error: error)
}
}
/**
* Join a channel
**/
public func joinChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = JoinChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(JoinChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Leave a channel
**/
public func leaveChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = LeaveChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LeaveChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Get messages of a channel
**/
public func channelMessages(channelId : String, numberOfMessages:Int, start: NSDate?, end: NSDate?, completion: ((result: MessageHistoryResultProtocol?, error: ErrorType?)->Void)?){
let command = GetChannelHistoryCommand(channelId: channelId,numberOfMessages: numberOfMessages,start: start, end: end)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelHistoryCommandHandler(parser: MessageParser()))
}
try! self.commandBus.process(command) { (result: MessageHistoryResult?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Send a message in a channel
**/
public func sendMessage(channelId : String,message: String, completion: ((result: Message?, error: ErrorType?) -> Void)?){
let command = SendMessageCommand(channelId: channelId, message: message)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendMessageCommandHandler(parser:MessageParser()))
}
try! self.commandBus.process(command) { (result: Message?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Set user status
**/
public func setUserStatus(userStatus: UserStatus,completion: ((error:ErrorType?)->Void)?){
let command = SetUserStatusCommand(userStatus: userStatus)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(UserStatusCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
}
| 6c1674cdc76232562f8f082070200230 | 29.681992 | 185 | 0.600899 | false | false | false | false |
jad6/DataStore | refs/heads/master | Example/Places/PlacesViewController.swift | bsd-2-clause | 1 | //
// PlacesViewController.swift
// Places
//
// Created by Jad Osseiran on 20/06/2015.
// Copyright © 2015 Jad Osseiran. All rights reserved.
//
import UIKit
class PlacesViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Actions
@IBAction func addPlaceOption(sender: AnyObject) {
let alertController = UIAlertController(title: "Add Place", message: "Add a place into Core Data. The number of places that will be added can be set in the \"Batches\" setting.", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Coral Bay"
textField.autocapitalizationType = .Words
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveAction = UIAlertAction(title: "Save", style: .Default) { action in
// Do the actual saving here.
}
alertController.addAction(saveAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
| d56c5ee0b8d2dabc6394fcff43db31ad | 30.675676 | 210 | 0.680034 | false | false | false | false |
hGhostD/SwiftLearning | refs/heads/master | Swift设计模式/Swift设计模式/21 模板方法模式/21.playground/Contents.swift | apache-2.0 | 1 | import Cocoa
/*
> 模板方法可以允许第三方开发者,以创建子类或者定义闭包的方式,替换一个算法的某些步骤的具体实现
*/
struct Donor {
let title: String
let firstName: String
let familyName: String
let lastDonation: Float
init(_ title: String, _ first: String, _ family: String, _ last: Float) {
self.title = title
self.firstName = first
self.familyName = family
self.lastDonation = last
}
}
class DonorDatabase {
private var donors: [Donor]
init() {
donors = [Donor("Ms","Anne","Jones",0),
Donor("Mr","Bob","Smith",100),
Donor("Dr","Alice","Doe",200),
Donor("Prof","Joe","Davis",320)]
}
func generateGalaInvitations(_ maxNumber: Int) -> [String] {
var targetDonors: [Donor] = donors.filter { $0.lastDonation > 0 }
targetDonors.sort { (first, second) -> Bool in
first.lastDonation > second.lastDonation
}
if (targetDonors.count > maxNumber) {
targetDonors = Array(targetDonors[0..<maxNumber])
}
return targetDonors.map {
return "Dear \($0.title). \($0.familyName)"
}
}
}
let donorDb = DonorDatabase()
let galaInvitations = donorDb.generateGalaInvitations(2)
galaInvitations.forEach { print($0)}
| f8cf6bb5a59e32535c618511872d1586 | 25.42 | 77 | 0.569266 | false | false | false | false |
movielala/TVOSButton | refs/heads/master | TVOSButtonExample/TVOSButtonExample/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// TVOSButtonExample
//
// Created by Cem Olcay on 11/02/16.
// Copyright © 2016 MovieLaLa. All rights reserved.
//
import UIKit
import TVOSButton
// MARK: - PosterButton
class PosterButton: TVOSButton {
var posterImage: UIImage? {
didSet {
badgeImage = posterImage
}
}
var posterImageURL: String? {
didSet {
if let posterImageURL = posterImageURL {
NSURLSession.sharedSession().dataTaskWithURL(
NSURL(string: posterImageURL)!,
completionHandler: { data, response, error in
if error == nil {
if let data = data, image = UIImage(data: data) {
dispatch_async(dispatch_get_main_queue(), {
self.posterImage = image
})
}
}
}).resume()
}
}
}
override func tvosButtonStyleForState(tvosButtonState: TVOSButtonState) -> TVOSButtonStyle {
switch tvosButtonState {
case .Focused:
return TVOSButtonStyle(
scale: 1.1,
shadow: TVOSButtonShadow.Focused,
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.whiteColor()))
case .Highlighted:
return TVOSButtonStyle(
scale: 0.95,
shadow: TVOSButtonShadow.Highlighted,
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.whiteColor()))
default:
return TVOSButtonStyle(
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.blackColor()))
}
}
}
// MARK: - IconButton
class IconButton: TVOSButton {
var iconName: String? {
didSet {
handleStateDidChange()
}
}
override func tvosButtonStyleForState(tvosButtonState: TVOSButtonState) -> TVOSButtonStyle {
// custom content
let icon = UIImageView(frame: CGRect(x: 20, y: 0, width: 40, height: 40))
icon.center.y = 50
if let iconName = iconName {
let color = tvosButtonState == .Highlighted || tvosButtonState == .Focused ? "Black" : "White"
icon.image = UIImage(named: "\(iconName)\(color)")
}
switch tvosButtonState {
case .Focused:
return TVOSButtonStyle(
backgroundColor: UIColor.whiteColor(),
cornerRadius: 10,
scale: 1.1,
shadow: TVOSButtonShadow.Focused,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.blackColor()))
case .Highlighted:
return TVOSButtonStyle(
backgroundColor: UIColor.whiteColor(),
cornerRadius: 10,
scale: 0.95,
shadow: TVOSButtonShadow.Highlighted,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.blackColor()))
default:
return TVOSButtonStyle(
backgroundColor: UIColor(red: 198/255.0, green: 44/255.0, blue: 48/255.0, alpha: 1),
cornerRadius: 10,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.whiteColor()))
}
}
}
// MARK: - View Controller
class ViewController: UIViewController {
@IBOutlet var posterButton: PosterButton!
@IBOutlet var toggleButton: TVOSToggleButton!
@IBOutlet var iconButton: IconButton!
override func viewDidLoad() {
super.viewDidLoad()
// Setup poster button
posterButton.titleLabelText = "Poster"
posterButton.posterImageURL = "https://placeholdit.imgix.net/~text?txtsize=33&txt=240x360&w=240&h=360"
posterButton.addTarget(self, action: "tvosButtonPressed", forControlEvents: .PrimaryActionTriggered)
// Setup toggle button
toggleButton.didToggledAction = toggleButtonDidToggledActionHandler
// Setup icon button
iconButton.textLabelText = "Share"
iconButton.iconName = "share"
}
func toggleButtonDidToggledActionHandler(
currentState: TVOSToggleButtonState,
updateNewState: (newState: TVOSToggleButtonState) -> Void) {
switch currentState {
case .Waiting:
toggleButton.textLabelText = "..."
requestSomething({
self.toggleButton.textLabelText = "Add"
self.toggleButton.toggleState = .On
}, failure: {
self.toggleButton.textLabelText = "Remove"
self.toggleButton.toggleState = .Off
})
case .On:
toggleButton.textLabelText = "Adding"
updateNewState(newState: .Waiting)
removeSomething({
self.toggleButton.textLabelText = "Remove"
updateNewState(newState: .Off)
}, failure: {
self.toggleButton.textLabelText = "Add"
updateNewState(newState: .On)
})
case .Off:
toggleButton.textLabelText = "Removing"
updateNewState(newState: .Waiting)
addSomethingToServer({
self.toggleButton.textLabelText = "Add"
updateNewState(newState: .On)
}, failure: {
self.toggleButton.textLabelText = "Remove"
updateNewState(newState: .Off)
})
}
}
// Example request methods for simulate waiting for network
func addSomethingToServer(success: () -> Void, failure: () -> Void) {
requestSomething(success, failure: failure)
}
func removeSomething(success: () -> Void, failure: () -> Void) {
requestSomething(success, failure: failure)
}
func requestSomething(success: () -> Void, failure: () -> Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(0.5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), success)
}
// Event handler
func tvosButtonPressed() {
print("tvos button pressed")
}
}
| 4e237c9dce20cdc4f0bfb9d6a5909d13 | 28.773196 | 106 | 0.649758 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/User Profile Sheet/UserProfileUserInfoCell.swift | gpl-2.0 | 2 | class UserProfileUserInfoCell: UITableViewCell, NibReusable {
// MARK: - Properties
@IBOutlet weak var gravatarImageView: CircularImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userBioLabel: UILabel!
static let estimatedRowHeight: CGFloat = 200
// MARK: - View
override func awakeFromNib() {
super.awakeFromNib()
configureCell()
}
// MARK: - Public Methods
func configure(withUser user: LikeUser) {
nameLabel.text = user.displayName
usernameLabel.text = String(format: Constants.usernameFormat, user.username)
userBioLabel.text = user.bio
userBioLabel.isHidden = user.bio.isEmpty
downloadGravatarWithURL(user.avatarUrl)
}
}
// MARK: - Private Extension
private extension UserProfileUserInfoCell {
func configureCell() {
nameLabel.textColor = .text
nameLabel.font = WPStyleGuide.serifFontForTextStyle(.title3, fontWeight: .semibold)
usernameLabel.textColor = .textSubtle
userBioLabel.textColor = .text
}
func downloadGravatarWithURL(_ url: String?) {
// Always reset gravatar
gravatarImageView.cancelImageDownload()
gravatarImageView.image = .gravatarPlaceholderImage
guard let url = url,
let gravatarURL = URL(string: url) else {
return
}
gravatarImageView.downloadImage(from: gravatarURL, placeholderImage: .gravatarPlaceholderImage)
}
struct Constants {
static let usernameFormat = NSLocalizedString("@%1$@", comment: "Label displaying the user's username preceeded by an '@' symbol. %1$@ is a placeholder for the username.")
}
}
| a747b76080ee99aff6f321b286db2475 | 27.803279 | 179 | 0.677291 | false | false | false | false |
HaloWang/Halo | refs/heads/master | Halo/Classes/KeyboardObserver.swift | mit | 1 |
import UIKit
@objc public protocol KeyboardObserverDelegate: NSObjectProtocol {
/**
键盘在屏幕上展示的高度即将改变
- parameter height: 键盘在屏幕上的显示高度
- parameter duration: 键盘动画延时
*/
func keyboardWillChangeToHeight(_ height: CGFloat, duration: TimeInterval)
}
open class KeyboardObserver: NSObject {
fileprivate static let sharedInstance = KeyboardObserver()
/// set delegate
open static var delegate: KeyboardObserverDelegate? {
get {
return self.sharedInstance.delegate
}
set {
self.sharedInstance.delegate = newValue
}
}
/// 当前键盘显示高度
open static var currentKeyboardHeight: CGFloat {
return self.sharedInstance.currentKeyboardHeight
}
/// 当前键盘显示高度
fileprivate var currentKeyboardHeight: CGFloat = 0
fileprivate weak var delegate: KeyboardObserverDelegate?
fileprivate override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardObserver.keyboardFrameChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc func keyboardFrameChange(_ notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else {
return
}
guard let keyboardY = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.origin.y else {
return
}
guard let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue else {
return
}
let screenHeight = UIScreen.main.bounds.size.height
currentKeyboardHeight = screenHeight - keyboardY
delegate?.keyboardWillChangeToHeight(currentKeyboardHeight, duration: duration)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
}
| 3f6c22f622f3bab8cb7c32b39bddd742 | 26.863636 | 175 | 0.728657 | false | false | false | false |
ElijahButers/Swift | refs/heads/master | GestureDoubleTap/GestureDoubleTab/ViewController.swift | gpl-3.0 | 32 | //
// ViewController.swift
// GestureDoubleTab
//
// Created by Carlos Butron on 01/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleTap(sender : UIGestureRecognizer) {
if (sender.view?.contentMode == UIViewContentMode.ScaleAspectFit){
sender.view?.contentMode = UIViewContentMode.Center
}
else{
sender.view?.contentMode = UIViewContentMode.ScaleAspectFit
} }
override func viewDidLoad() {
var tapGesture = UITapGestureRecognizer(target: self, action:
"handleTap:")
tapGesture.numberOfTapsRequired = 2;
image.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
}
| b55854ceb743a4bcb63a282b87c46ee8 | 33.24 | 121 | 0.6875 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/DebugInfo/variables.swift | apache-2.0 | 11 | // RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
// Ensure that the debug info we're emitting passes the back end verifier.
// RUN: %target-swift-frontend %s -g -S -o - | %FileCheck %s --check-prefix ASM-%target-object-format
// ASM-macho: .section __DWARF,__debug_info
// ASM-elf: .section .debug_info,"",{{[@%]}}progbits
// Test variables-interpreter.swift runs this code with `swift -g -i`.
// Test variables-repl.swift runs this code with `swift -g < variables.swift`.
// CHECK-DAG: ![[TLC:.*]] = !DIModule({{.*}}, name: "variables"
// Global variables.
var glob_i8: Int8 = 8
// CHECK-DAG: !DIGlobalVariable(name: "glob_i8",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I8:[^,]+]]
var glob_i16: Int16 = 16
// CHECK-DAG: !DIGlobalVariable(name: "glob_i16",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I16:[^,]+]]
var glob_i32: Int32 = 32
// CHECK-DAG: !DIGlobalVariable(name: "glob_i32",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I32:[^,]+]]
var glob_i64: Int64 = 64
// CHECK-DAG: !DIGlobalVariable(name: "glob_i64",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I64:[^,]+]]
var glob_f: Float = 2.89
// CHECK-DAG: !DIGlobalVariable(name: "glob_f",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[F:[^,]+]]
var glob_d: Double = 3.14
// CHECK-DAG: !DIGlobalVariable(name: "glob_d",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[D:[^,]+]]
var glob_b: Bool = true
// CHECK-DAG: !DIGlobalVariable(name: "glob_b",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[B:[^,]+]]
var glob_s: String = "😄"
// CHECK-DAG: !DIGlobalVariable(name: "glob_s",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[S:[^,]+]]
// FIXME: Dreadful type-checker performance prevents this from being this single
// print expression:
// print("\(glob_v), \(glob_i8), \(glob_i16), \(glob_i32), \(glob_i64), \(glob_f), \(glob_d), \(glob_b), \(glob_s)", terminator: "")
print(", \(glob_i8)", terminator: "")
print(", \(glob_i16)", terminator: "")
print(", \(glob_i32)", terminator: "")
print(", \(glob_i64)", terminator: "")
print(", \(glob_f)", terminator: "")
print(", \(glob_d)", terminator: "")
print(", \(glob_b)", terminator: "")
print(", \(glob_s)", terminator: "")
var unused: Int32 = -1
// CHECK-DAG: ![[RT:[0-9]+]] ={{.*}}"Swift.swiftmodule"
// Stack variables.
func foo(_ dt: Float) -> Float {
// CHECK-DAG: call void @llvm.dbg.declare
// CHECK-DAG: !DILocalVariable(name: "f"
let f: Float = 9.78
// CHECK-DAG: !DILocalVariable(name: "r"
let r: Float = f*dt
return r
}
var g = foo(1.0);
// Tuple types.
var tuple: (Int, Bool) = (1, true)
// CHECK-DAG: !DIGlobalVariable(name: "tuple", linkageName: "_Tv{{9variables|4main}}5tupleTSiSb_",{{.*}} type: ![[TUPTY:[^,)]+]]
// CHECK-DAG: ![[TUPTY]] = !DICompositeType({{.*}}identifier: "_TtTSiSb_"
func myprint(_ p: (i: Int, b: Bool)) {
print("\(p.i) -> \(p.b)")
}
myprint(tuple)
// Arrays are represented as an instantiation of Array.
// CHECK-DAG: ![[ARRAYTY:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Array",
// CHECK-DAG: !DIGlobalVariable(name: "array_of_tuples",{{.*}} type: ![[ARRAYTY]]
var array_of_tuples : [(a : Int, b : Int)] = [(1,2)]
var twod : [[Int]] = [[1]]
func bar(_ x: [(a : Int, b : Int)], y: [[Int]]) {
}
// CHECK-DAG: !DIGlobalVariable(name: "P",{{.*}} type: ![[PTY:[0-9]+]]
// CHECK-DAG: ![[PTUP:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtT1xSd1ySd1zSd_",
// CHECK-DAG: ![[PTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_Tta{{9variables|4main}}5Point",{{.*}} baseType: ![[PTUP]]
typealias Point = (x: Double, y: Double, z: Double)
var P:Point = (1, 2, 3)
func myprint(_ p: (x: Double, y: Double, z: Double)) {
print("(\(p.x), \(p.y), \(p.z))")
}
myprint(P)
// CHECK-DAG: !DIGlobalVariable(name: "P2",{{.*}} type: ![[APTY:[0-9]+]]
// CHECK-DAG: ![[APTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_Tta{{9variables|4main}}13AliasForPoint",{{.*}} baseType: ![[PTY:[0-9]+]]
typealias AliasForPoint = Point
var P2:AliasForPoint = (4, 5, 6)
myprint(P2)
// Unions.
enum TriValue {
case false_
case true_
case top
}
// CHECK-DAG: !DIGlobalVariable(name: "unknown",{{.*}} type: ![[TRIVAL:[0-9]+]]
// CHECK-DAG: ![[TRIVAL]] = !DICompositeType({{.*}}name: "TriValue",
var unknown = TriValue.top
func myprint(_ value: TriValue) {
switch value {
case TriValue.false_: print("false")
case TriValue.true_: print("true")
case TriValue.top: print("⊤")
}
}
myprint(unknown)
// CHECK-DAG: !DIFile(filename: "variables.swift"
| 8e0f03dd5caf6b023a43a6be83965361 | 39.008621 | 142 | 0.575523 | false | false | false | false |
davidchiles/OSMKit-Swift | refs/heads/master | OSMKit/OSMKitTests/Tests/ParserDelegate.swift | mit | 2 | //
// ParserDelegate.swift
// OSMKit
//
// Created by David Chiles on 12/18/15.
// Copyright © 2015 David Chiles. All rights reserved.
//
import Foundation
import OSMKit_Swift
class ParserDelegate:OSMParserDelegate {
var startBlock:(parser:OSMParser) -> Void
var endBlock:(parser:OSMParser) -> Void
var nodeBlock:(parser:OSMParser,node:OSMNode) -> Void
var wayBlock:(parser:OSMParser,way:OSMWay) -> Void
var relationBlock:(parser:OSMParser,relation:OSMRelation) -> Void
var errorBlock:(parser:OSMParser,error:ErrorType?) -> Void
init(startBlock:(parser:OSMParser) -> Void,nodeBlock:(parser:OSMParser,node:OSMNode) -> Void,wayBlock:(parser:OSMParser,way:OSMWay) -> Void,relationBlock:(parser:OSMParser,relation:OSMRelation) -> Void,endBlock:(parser:OSMParser) -> Void,errorBlock:(parser:OSMParser,error:ErrorType?) -> Void) {
self.startBlock = startBlock
self.nodeBlock = nodeBlock
self.wayBlock = wayBlock
self.relationBlock = relationBlock
self.errorBlock = errorBlock
self.endBlock = endBlock
}
//MARK: OSMParserDelegate Methods
func didStartParsing(parser: OSMParser) {
self.startBlock(parser: parser)
}
func didFindElement(parser: OSMParser, element: OSMElement) {
switch element {
case let element as OSMNode:
self.nodeBlock(parser: parser, node: element)
case let element as OSMWay:
self.wayBlock(parser: parser, way: element)
case let element as OSMRelation:
self.relationBlock(parser: parser, relation: element)
default:
break
}
}
func didFinishParsing(parser: OSMParser) {
self.endBlock(parser: parser)
}
func didError(parser: OSMParser, error: ErrorType?) {
self.errorBlock(parser: parser, error: error)
}
} | d1dc85c64252296853e8898b6a0b1a08 | 33.363636 | 299 | 0.66702 | false | false | false | false |
PeterWinzell/vehicle-carsignal-examples | refs/heads/master | iphoneclient/W3CDemo_2/W3CDemo_2/W3CDemo_2/SocketIOManager.swift | gpl-3.0 | 1 | //
// SocketIOManager.swift
// W3CDemo
//
//
// The MIT License (MIT)
// Copyright (c) <09/11/16> <Peter Winzell>
//
// 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 Starscream
import SwiftyJSON
class SocketIOManager: WebSocketDelegate{
static let sharedInstance = SocketIOManager()
var socket: WebSocket!
// global access through singleton...darn ugly. Must be a better way of doing this.
var zespeed: Int!
init() {
}
func setURL(_ urlString: String){
print(urlString)
socket = WebSocket(url: URL(string: urlString)!)
socket.delegate = self
socket.connect()
}
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
// Post notification
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
let json = text;
let data = json.data(using: String.Encoding.utf8)
let jsonarray = JSON(data: data!)
let path = jsonarray["path"].string
print(text)
// check if path is correct
if (path == "Vehicle.speed"){
zespeed = jsonarray["value"].int!
if zespeed != nil{
// notify UI through notification center (GOTO ViewController)
print(zespeed)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateSpeed"), object: nil)
}
}
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
print("Received data: \(data.count)")
}
func sendMessage(message: String) {
socket.write(string: message)
}
}
| 3c6113c4efeeae73fe853345ac1b1028 | 32.152174 | 112 | 0.649508 | false | false | false | false |
soffes/Motivation | refs/heads/master | Motivation/AgeView.swift | mit | 1 | //
// AgeView.swift
// Motivation
//
// Created by Sam Soffes on 8/6/15.
// Copyright (c) 2015 Sam Soffes. All rights reserved.
//
import Foundation
import ScreenSaver
class AgeView: ScreenSaverView {
// MARK: - Properties
private let textLabel: NSTextField = {
let label = NSTextField()
label.translatesAutoresizingMaskIntoConstraints = false
label.editable = false
label.drawsBackground = false
label.bordered = false
label.bezeled = false
label.selectable = false
label.textColor = .whiteColor()
return label
}()
private lazy var configurationWindowController: NSWindowController = {
return ConfigurationWindowController()
}()
private var motivationLevel: MotivationLevel
private var birthday: NSDate? {
didSet {
updateFont()
}
}
// MARK: - Initializers
convenience init() {
self.init(frame: CGRectZero, isPreview: false)
}
override init!(frame: NSRect, isPreview: Bool) {
motivationLevel = Preferences().motivationLevel
super.init(frame: frame, isPreview: isPreview)
initialize()
}
required init?(coder: NSCoder) {
motivationLevel = Preferences().motivationLevel
super.init(coder: coder)
initialize()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - NSView
override func drawRect(rect: NSRect) {
let backgroundColor: NSColor = .blackColor()
backgroundColor.setFill()
NSBezierPath.fillRect(bounds)
}
// If the screen saver changes size, update the font
override func resizeWithOldSuperviewSize(oldSize: NSSize) {
super.resizeWithOldSuperviewSize(oldSize)
updateFont()
}
// MARK: - ScreenSaverView
override func animateOneFrame() {
if let birthday = birthday {
let age = ageForBirthday(birthday)
let format = "%0.\(motivationLevel.decimalPlaces)f"
textLabel.stringValue = String(format: format, age)
} else {
textLabel.stringValue = "Open Screen Saver Options to set your birthday."
}
}
override func hasConfigureSheet() -> Bool {
return true
}
override func configureSheet() -> NSWindow? {
return configurationWindowController.window
}
// MARK: - Private
/// Shared initializer
private func initialize() {
// Set animation time interval
animationTimeInterval = 1 / 30
// Recall preferences
birthday = Preferences().birthday
// Setup the label
addSubview(textLabel)
addConstraints([
NSLayoutConstraint(item: textLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: textLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)
])
// Listen for configuration changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "motivationLevelDidChange:", name: Preferences.motivationLevelDidChangeNotificationName, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "birthdayDidChange:", name: Preferences.birthdayDidChangeNotificationName, object: nil)
}
/// Age calculation
private func ageForBirthday(birthday: NSDate) -> Double {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
// An age is defined as the number of years you've been alive plus the number of days, seconds, and nanoseconds
// you've been alive out of that many units in the current year.
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Day, NSCalendarUnit.Second, NSCalendarUnit.Nanosecond], fromDate: birthday, toDate: now, options: [])
// We calculate these every time since the values can change when you cross a boundary. Things are too
// complicated to try to figure out when that is and cache them. NSCalendar is made for this.
let daysInYear = Double(calendar.daysInYear(now) ?? 365)
let hoursInDay = Double(calendar.rangeOfUnit(NSCalendarUnit.Hour, inUnit: NSCalendarUnit.Day, forDate: now).length)
let minutesInHour = Double(calendar.rangeOfUnit(NSCalendarUnit.Minute, inUnit: NSCalendarUnit.Hour, forDate: now).length)
let secondsInMinute = Double(calendar.rangeOfUnit(NSCalendarUnit.Second, inUnit: NSCalendarUnit.Minute, forDate: now).length)
let nanosecondsInSecond = Double(calendar.rangeOfUnit(NSCalendarUnit.Nanosecond, inUnit: NSCalendarUnit.Second, forDate: now).length)
// Now that we have all of the values, assembling them is easy. We don't get minutes and hours from the calendar
// since it will overflow nicely to seconds. We need days and years since the number of days in a year changes
// more frequently. This will handle leap seconds, days, and years.
let seconds = Double(components.second) + (Double(components.nanosecond) / nanosecondsInSecond)
let minutes = seconds / secondsInMinute
let hours = minutes / minutesInHour
let days = Double(components.day) + (hours / hoursInDay)
let years = Double(components.year) + (days / daysInYear)
return years
}
/// Motiviation level changed
@objc private func motivationLevelDidChange(notification: NSNotification?) {
motivationLevel = Preferences().motivationLevel
}
/// Birthday changed
@objc private func birthdayDidChange(notification: NSNotification?) {
birthday = Preferences().birthday
}
/// Update the font for the current size
private func updateFont() {
if birthday != nil {
textLabel.font = fontWithSize(bounds.width / 10)
} else {
textLabel.font = fontWithSize(bounds.width / 30, monospace: false)
}
}
/// Get a font
private func fontWithSize(fontSize: CGFloat, monospace: Bool = true) -> NSFont {
let font: NSFont
if #available(OSX 10.11, *) {
font = .systemFontOfSize(fontSize, weight: NSFontWeightThin)
} else {
font = NSFont(name: "HelveticaNeue-Thin", size: fontSize)!
}
let fontDescriptor: NSFontDescriptor
if monospace {
fontDescriptor = font.fontDescriptor.fontDescriptorByAddingAttributes([
NSFontFeatureSettingsAttribute: [
[
NSFontFeatureTypeIdentifierKey: kNumberSpacingType,
NSFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
]
]
])
} else {
fontDescriptor = font.fontDescriptor
}
return NSFont(descriptor: fontDescriptor, size: fontSize)!
}
}
| d404ac9bd8bf0f739cd70af79c0e90f3 | 30.566327 | 177 | 0.742686 | false | false | false | false |
littlelightwang/firefox-ios | refs/heads/master | Client/Frontend/Settings/SettingsViewController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SettingsViewController: UIViewController, ToolbarViewProtocol,
UITableViewDataSource, UITableViewDelegate, FxASignInViewControllerDelegate
{
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var settingsTableView: UITableView!
@IBOutlet weak var signOutButton: UIButton!
var profile: Profile!
let SETTING_CELL_ID = "SETTING_CELL_ID"
lazy var panels: Panels = {
return Panels(profile: self.profile)
}()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
avatarImageView.layer.cornerRadius = 50
avatarImageView.layer.masksToBounds = true
avatarImageView.isAccessibilityElement = true
avatarImageView.accessibilityLabel = NSLocalizedString("Avatar", comment: "")
settingsTableView.delegate = self
settingsTableView.dataSource = self
settingsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
settingsTableView.separatorInset = UIEdgeInsetsZero
settingsTableView.editing = true
settingsTableView.allowsSelectionDuringEditing = true
settingsTableView.backgroundColor = view.backgroundColor
settingsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: SETTING_CELL_ID)
signOutButton.layer.borderColor = UIColor.whiteColor().CGColor
signOutButton.layer.borderWidth = 1.0
signOutButton.layer.cornerRadius = 6.0
signOutButton.addTarget(self, action: "didClickLogout", forControlEvents: UIControlEvents.TouchUpInside)
}
func signInViewControllerDidCancel(vc: FxASignInViewController) {
vc.dismissViewControllerAnimated(true, completion: nil)
}
// A temporary delegate which merely updates the displayed email address on
// succesful Firefox Accounts sign in.
func signInViewControllerDidSignIn(vc: FxASignInViewController, data: JSON) {
emailLabel.text = data["email"].asString
}
// Referenced as button selector. Temporarily, we show the Firefox
// Accounts sign in view.
func didClickLogout() {
let vc = FxASignInViewController()
vc.signInDelegate = self
presentViewController(vc, animated: true, completion: nil)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let sw = cell?.editingAccessoryView as? UISwitch {
sw.setOn(!sw.on, animated: true)
panels.enablePanelAt(sw.on, position: indexPath.item)
}
return indexPath;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Subtract one so that we don't show our own panel
return panels.count - 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(SETTING_CELL_ID, forIndexPath: indexPath) as UITableViewCell
if var item = panels[indexPath.item] {
cell.textLabel?.text = item.title
cell.textLabel?.font = UIFont(name: "FiraSans-Light", size: cell.textLabel?.font.pointSize ?? 0)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = self.view.backgroundColor
cell.separatorInset = UIEdgeInsetsZero
cell.selectionStyle = UITableViewCellSelectionStyle.None
let toggle: UISwitch = UISwitch()
toggle.on = item.enabled;
cell.editingAccessoryView = toggle
}
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
panels.moveItem(sourceIndexPath.item, to: destinationIndexPath.item)
settingsTableView.setNeedsDisplay();
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews as [UIView] {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
}
| 836fc83ef43d7a9b69551ae02f92601e | 39.355556 | 140 | 0.69163 | false | false | false | false |
CodaFi/swift | refs/heads/main | benchmark/single-source/SetTests.swift | apache-2.0 | 20 | //===--- SetTests.swift ---------------------------------------------------===//
//
// 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 TestsUtils
let size = 400
let half = size / 2
let quarter = size / 4
// Construction of empty sets.
let setE: Set<Int> = []
let setOE: Set<Box<Int>> = []
// Construction kit for sets with 25% overlap
let setAB = Set(0 ..< size) // 0 ..< 400
let setCD = Set(size ..< 2 * size) // 400 ..< 800
let setBC = Set(size - quarter ..< 2 * size - quarter) // 300 ..< 700
let setB = Set(size - quarter ..< size) // 300 ..< 400
let setOAB = Set(setAB.map(Box.init))
let setOCD = Set(setCD.map(Box.init))
let setOBC = Set(setBC.map(Box.init))
let setOB = Set(setB.map(Box.init))
let countA = size - quarter // 300
let countB = quarter // 100
let countC = countA // 300
let countD = countB // 100
let countAB = size // 400
let countAC = countA + countC // 600
let countABC = countA + countB + countC // 700
let countABCD = countA + countB + countC + countD // 800
// Construction kit for sets with 50% overlap
let setXY = Set(0 ..< size) // 0 ..< 400
let setYZ = Set(half ..< size + half) // 200 ..< 600
let setY = Set(half ..< size) // 200 ..< 400
// Two sets with 100% overlap, but different bucket counts (let's not make it
// too easy...)
let setP = Set(0 ..< size)
let setQ: Set<Int> = {
var set = Set(0 ..< size)
set.reserveCapacity(2 * size)
return set
}()
// Construction of empty array.
let arrayE: Array<Int> = []
let arrayOE: Array<Box<Int>> = []
// Construction kit for arrays with 25% overlap
let arrayAB = Array(0 ..< size) // 0 ..< 400
let arrayCD = Array(size ..< 2 * size) // 400 ..< 800
let arrayBC = Array(size - quarter ..< 2 * size - quarter) // 300 ..< 700
let arrayB = Array(size - quarter ..< size) // 300 ..< 400
let arrayOAB = arrayAB.map(Box.init)
let arrayOCD = arrayCD.map(Box.init)
let arrayOBC = arrayBC.map(Box.init)
let arrayOB = arrayB.map(Box.init)
// Construction kit for arrays with 50% overlap
let arrayXY = Array(0 ..< size) // 0 ..< 400
let arrayYZ = Array(half ..< size + half) // 200 ..< 600
let arrayY = Array(half ..< size) // 200 ..< 400
let arrayP = Array(0 ..< size)
// Construction of flexible sets.
var set: Set<Int> = []
var setBox: Set<Box<Int>> = []
func set(_ size: Int) {
set = Set(0 ..< size)
}
func setBox(_ size: Int) {
setBox = Set(Set(0 ..< size).map(Box.init))
}
public let SetTests = [
// Mnemonic: number after name is percentage of common elements in input sets.
BenchmarkInfo(
name: "Set.isSubset.Empty.Int",
runFunction: { n in run_SetIsSubsetInt(setE, setAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, setAB]) }),
BenchmarkInfo(
name: "Set.isSubset.Int.Empty",
runFunction: { n in run_SetIsSubsetInt(setAB, setE, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setE]) }),
BenchmarkInfo(
name: "SetIsSubsetInt0",
runFunction: { n in run_SetIsSubsetInt(setAB, setCD, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "SetIsSubsetBox0",
runFunction: { n in run_SetIsSubsetBox(setOAB, setOCD, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "SetIsSubsetInt25",
runFunction: { n in run_SetIsSubsetInt(setB, setAB, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, setAB]) }),
BenchmarkInfo(
name: "SetIsSubsetBox25",
runFunction: { n in run_SetIsSubsetBox(setOB, setOAB, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, setOAB]) }),
BenchmarkInfo(
name: "SetIsSubsetInt50",
runFunction: { n in run_SetIsSubsetInt(setY, setXY, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, setXY]) }),
BenchmarkInfo(
name: "SetIsSubsetInt100",
runFunction: { n in run_SetIsSubsetInt(setP, setQ, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Empty.Int",
runFunction: { n in run_SetIsSubsetSeqInt(setE, arrayAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Int.Empty",
runFunction: { n in run_SetIsSubsetSeqInt(setAB, arrayE, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Int0",
runFunction: { n in run_SetIsSubsetSeqInt(setAB, arrayCD, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayCD]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Box0",
runFunction: { n in run_SetIsSubsetSeqBox(setOAB, arrayOCD, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOCD]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Int25",
runFunction: { n in run_SetIsSubsetSeqInt(setB, arrayBC, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, arrayBC]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Box25",
runFunction: { n in run_SetIsSubsetSeqBox(setOB, arrayOBC, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Int50",
runFunction: { n in run_SetIsSubsetSeqInt(setY, arrayYZ, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.isSubset.Seq.Int100",
runFunction: { n in run_SetIsSubsetSeqInt(setP, arrayP, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Empty.Int",
runFunction: { n in run_SetIsStrictSubsetInt(setE, setAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, setAB]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Int.Empty",
runFunction: { n in run_SetIsStrictSubsetInt(setAB, setE, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setE]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Int0",
runFunction: { n in run_SetIsStrictSubsetInt(setAB, setCD, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Box0",
runFunction: { n in run_SetIsStrictSubsetBox(setOAB, setOCD, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Int25",
runFunction: { n in run_SetIsStrictSubsetInt(setB, setAB, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, setAB]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Box25",
runFunction: { n in run_SetIsStrictSubsetBox(setOB, setOAB, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, setOAB]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Int50",
runFunction: { n in run_SetIsStrictSubsetInt(setY, setXY, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, setXY]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Int100",
runFunction: { n in run_SetIsStrictSubsetInt(setP, setQ, false, 5000 * n) },
tags: [.validation, .api, .Set, .skip],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Empty.Int",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setE, arrayAB, true, 5000 * n) },
tags: [.validation, .api, .Set, .skip],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Int.Empty",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setAB, arrayE, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Int0",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setAB, arrayCD, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayCD]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Box0",
runFunction: { n in run_SetIsStrictSubsetSeqBox(setOAB, arrayOCD, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOCD]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Int25",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setB, arrayBC, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, arrayBC]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Box25",
runFunction: { n in run_SetIsStrictSubsetSeqBox(setOB, arrayOBC, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Int50",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setY, arrayYZ, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.isStrictSubset.Seq.Int100",
runFunction: { n in run_SetIsStrictSubsetSeqInt(setP, arrayP, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Empty.Int",
runFunction: { n in run_SetIsSupersetSeqInt(setAB, arrayE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Int.Empty",
runFunction: { n in run_SetIsSupersetSeqInt(setE, arrayAB, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Int0",
runFunction: { n in run_SetIsSupersetSeqInt(setCD, arrayAB, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setCD, arrayAB]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Box0",
runFunction: { n in run_SetIsSupersetSeqBox(setOCD, arrayOAB, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOCD, arrayOAB]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Int25",
runFunction: { n in run_SetIsSupersetSeqInt(setB, arrayBC, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, arrayBC]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Box25",
runFunction: { n in run_SetIsSupersetSeqBox(setOB, arrayOBC, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Int50",
runFunction: { n in run_SetIsSupersetSeqInt(setY, arrayYZ, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.isSuperset.Seq.Int100",
runFunction: { n in run_SetIsSupersetSeqInt(setP, arrayP, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Empty.Int",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setAB, arrayE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Int.Empty",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setE, arrayAB, false, 5000 * n) },
tags: [.validation, .api, .Set, .skip],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Int0",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setCD, arrayAB, false, 500 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setCD, arrayAB]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Box0",
runFunction: { n in run_SetIsStrictSupersetSeqBox(setOCD, arrayOAB, false, 500 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOCD, arrayOAB]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Int25",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setB, arrayBC, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, arrayBC]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Box25",
runFunction: { n in run_SetIsStrictSupersetSeqBox(setOB, arrayOBC, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Int50",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setY, arrayYZ, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.isStrictSuperset.Seq.Int100",
runFunction: { n in run_SetIsStrictSupersetSeqInt(setP, arrayP, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Empty.Int",
runFunction: { n in run_SetIsDisjointInt(setE, setAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, setAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Int.Empty",
runFunction: { n in run_SetIsDisjointInt(setAB, setE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setE]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Empty.Box",
runFunction: { n in run_SetIsDisjointBox(setOE, setOAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOE, setOAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Box.Empty",
runFunction: { n in run_SetIsDisjointBox(setOAB, setOE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOE]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Int0",
runFunction: { n in run_SetIsDisjointInt(setAB, setCD, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Box0",
runFunction: { n in run_SetIsDisjointBox(setOAB, setOCD, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Int25",
runFunction: { n in run_SetIsDisjointInt(setB, setAB, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, setAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Box25",
runFunction: { n in run_SetIsDisjointBox(setOB, setOAB, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, setOAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Int50",
runFunction: { n in run_SetIsDisjointInt(setY, setXY, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, setXY]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Int100",
runFunction: { n in run_SetIsDisjointInt(setP, setQ, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Empty.Int",
runFunction: { n in run_SetIsDisjointSeqInt(setE, arrayAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Int.Empty",
runFunction: { n in run_SetIsDisjointSeqInt(setAB, arrayE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Empty.Box",
runFunction: { n in run_SetIsDisjointSeqBox(setOE, arrayOAB, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOE, arrayOAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Box.Empty",
runFunction: { n in run_SetIsDisjointSeqBox(setOAB, arrayOE, true, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOE]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Int0",
runFunction: { n in run_SetIsDisjointSeqInt(setAB, arrayCD, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayCD]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Box0",
runFunction: { n in run_SetIsDisjointSeqBox(setOAB, arrayOCD, true, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOCD]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Int25",
runFunction: { n in run_SetIsDisjointSeqInt(setB, arrayAB, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setB, arrayAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Box25",
runFunction: { n in run_SetIsDisjointSeqBox(setOB, arrayOAB, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOB, arrayOAB]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Int50",
runFunction: { n in run_SetIsDisjointSeqInt(setY, arrayXY, false, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setY, arrayXY]) }),
BenchmarkInfo(
name: "Set.isDisjoint.Seq.Int100",
runFunction: { n in run_SetIsDisjointSeqInt(setP, arrayP, false, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceInt0",
runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceBox0",
runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceInt25",
runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setBC, countAC, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setBC]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceBox25",
runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOBC, countAC, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOBC]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceInt50",
runFunction: { n in run_SetSymmetricDifferenceInt(setXY, setYZ, size, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, setYZ]) }),
BenchmarkInfo(
name: "SetSymmetricDifferenceInt100",
runFunction: { n in run_SetSymmetricDifferenceInt(setP, setQ, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "SetIntersectionInt0",
runFunction: { n in run_SetIntersectionInt(setAB, setCD, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "SetIntersectionBox0",
runFunction: { n in run_SetIntersectionBox(setOAB, setOCD, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "SetIntersectionInt25",
runFunction: { n in run_SetIntersectionInt(setAB, setBC, countB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setBC]) }),
BenchmarkInfo(
name: "SetIntersectionBox25",
runFunction: { n in run_SetIntersectionBox(setOAB, setOBC, countB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOBC]) }),
BenchmarkInfo(
name: "SetIntersectionInt50",
runFunction: { n in run_SetIntersectionInt(setXY, setYZ, half, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, setYZ]) }),
BenchmarkInfo(
name: "SetIntersectionInt100",
runFunction: { n in run_SetIntersectionInt(setP, setQ, size, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Int0",
runFunction: { n in run_SetIntersectionSeqInt(setAB, arrayCD, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayCD]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Box0",
runFunction: { n in run_SetIntersectionSeqBox(setOAB, arrayOCD, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOCD]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Int25",
runFunction: { n in run_SetIntersectionSeqInt(setAB, arrayBC, countB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayBC]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Box25",
runFunction: { n in run_SetIntersectionSeqBox(setOAB, arrayOBC, countB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Int50",
runFunction: { n in run_SetIntersectionSeqInt(setXY, arrayYZ, half, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.intersection.Seq.Int100",
runFunction: { n in run_SetIntersectionSeqInt(setP, arrayP, size, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "SetUnionInt0",
runFunction: { n in run_SetUnionInt(setAB, setCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "SetUnionBox0",
runFunction: { n in run_SetUnionBox(setOAB, setOCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "SetUnionInt25",
runFunction: { n in run_SetUnionInt(setAB, setBC, countABC, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setBC]) }),
BenchmarkInfo(
name: "SetUnionBox25",
runFunction: { n in run_SetUnionBox(setOAB, setOBC, countABC, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOBC]) }),
BenchmarkInfo(
name: "SetUnionInt50",
runFunction: { n in run_SetUnionInt(setXY, setYZ, size + half, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, setYZ]) }),
BenchmarkInfo(
name: "SetUnionInt100",
runFunction: { n in run_SetUnionInt(setP, setQ, size, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.subtracting.Empty.Int",
runFunction: { n in run_SetSubtractingInt(setE, setAB, 0, 1000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, setAB]) }),
BenchmarkInfo(
name: "Set.subtracting.Int.Empty",
runFunction: { n in run_SetSubtractingInt(setAB, setE, countAB, 1000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setE]) }),
BenchmarkInfo(
name: "Set.subtracting.Empty.Box",
runFunction: { n in run_SetSubtractingBox(setOE, setOAB, 0, 1000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOE, setOAB]) }),
BenchmarkInfo(
name: "Set.subtracting.Box.Empty",
runFunction: { n in run_SetSubtractingBox(setOAB, setOE, countAB, 1000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOE]) }),
BenchmarkInfo(
name: "SetSubtractingInt0",
runFunction: { n in run_SetSubtractingInt(setAB, setCD, countAB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }),
BenchmarkInfo(
name: "SetSubtractingBox0",
runFunction: { n in run_SetSubtractingBox(setOAB, setOCD, countAB, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }),
BenchmarkInfo(
name: "SetSubtractingInt25",
runFunction: { n in run_SetSubtractingInt(setAB, setBC, countA, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setBC]) }),
BenchmarkInfo(
name: "SetSubtractingBox25",
runFunction: { n in run_SetSubtractingBox(setOAB, setOBC, countA, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOBC]) }),
BenchmarkInfo(
name: "SetSubtractingInt50",
runFunction: { n in run_SetSubtractingInt(setXY, setYZ, half, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, setYZ]) }),
BenchmarkInfo(
name: "SetSubtractingInt100",
runFunction: { n in run_SetSubtractingInt(setP, setQ, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, setQ]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Empty.Int",
runFunction: { n in run_SetSubtractingSeqInt(setE, arrayAB, 0, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setE, arrayAB]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Int.Empty",
runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayE, countAB, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayE]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Empty.Box",
runFunction: { n in run_SetSubtractingSeqBox(setOE, arrayOAB, 0, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOE, arrayOAB]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Box.Empty",
runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOE, countAB, 5000 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOE]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Int0",
runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayCD, countAB, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayCD]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Box0",
runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOCD, countAB, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOCD]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Int25",
runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayBC, countA, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, arrayBC]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Box25",
runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOBC, countA, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, arrayOBC]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Int50",
runFunction: { n in run_SetSubtractingSeqInt(setXY, arrayYZ, half, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setXY, arrayYZ]) }),
BenchmarkInfo(
name: "Set.subtracting.Seq.Int100",
runFunction: { n in run_SetSubtractingSeqInt(setP, arrayP, 0, 50 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setP, arrayP]) }),
BenchmarkInfo(
name: "Set.filter.Int50.16k",
runFunction: { n in run_SetFilterInt50(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(16_000) }),
BenchmarkInfo(
name: "Set.filter.Int50.20k",
runFunction: { n in run_SetFilterInt50(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(20_000) }),
BenchmarkInfo(
name: "Set.filter.Int50.24k",
runFunction: { n in run_SetFilterInt50(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(24_000) }),
BenchmarkInfo(
name: "Set.filter.Int50.28k",
runFunction: { n in run_SetFilterInt50(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(28_000) }),
BenchmarkInfo(
name: "Set.filter.Int100.16k",
runFunction: { n in run_SetFilterInt100(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(16_000) }),
BenchmarkInfo(
name: "Set.filter.Int100.20k",
runFunction: { n in run_SetFilterInt100(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(20_000) }),
BenchmarkInfo(
name: "Set.filter.Int100.24k",
runFunction: { n in run_SetFilterInt100(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(24_000) }),
BenchmarkInfo(
name: "Set.filter.Int100.28k",
runFunction: { n in run_SetFilterInt100(n) },
tags: [.validation, .api, .Set],
setUpFunction: { set(28_000) }),
// Legacy benchmarks, kept for continuity with previous releases.
BenchmarkInfo(
name: "SetExclusiveOr", // ~"SetSymmetricDifferenceInt0"
runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10),
BenchmarkInfo(
name: "SetExclusiveOr_OfObjects", // ~"SetSymmetricDifferenceBox0"
runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }, legacyFactor: 10),
BenchmarkInfo(
name: "SetIntersect", // ~"SetIntersectionInt0"
runFunction: { n in run_SetIntersectionInt(setAB, setCD, 0, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10),
BenchmarkInfo(
name: "SetUnion", // ~"SetUnionInt0"
runFunction: { n in run_SetUnionInt(setAB, setCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10),
BenchmarkInfo(
name: "SetUnion_OfObjects", // ~"SetUnionBox0"
runFunction: { n in run_SetUnionBox(setOAB, setOCD, countABCD, 10 * n) },
tags: [.validation, .api, .Set],
setUpFunction: { blackHole([setOAB, setOCD]) }, legacyFactor: 10),
]
@inline(never)
public func run_SetIsSubsetInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSubset = a.isSubset(of: identity(b))
CheckResults(isSubset == r)
}
}
@inline(never)
public func run_SetIsSubsetSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSubset = a.isSubset(of: identity(b))
CheckResults(isSubset == r)
}
}
@inline(never)
public func run_SetIsStrictSubsetInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSubset = a.isStrictSubset(of: identity(b))
CheckResults(isStrictSubset == r)
}
}
@inline(never)
public func run_SetIsStrictSubsetSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSubset = a.isStrictSubset(of: identity(b))
CheckResults(isStrictSubset == r)
}
}
@inline(never)
public func run_SetIsSupersetSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSuperset = a.isSuperset(of: identity(b))
CheckResults(isSuperset == r)
}
}
@inline(never)
public func run_SetIsStrictSupersetSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSuperset = a.isStrictSuperset(of: identity(b))
CheckResults(isStrictSuperset == r)
}
}
@inline(never)
public func run_SetSymmetricDifferenceInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let diff = a.symmetricDifference(identity(b))
CheckResults(diff.count == r)
}
}
@inline(never)
public func run_SetUnionInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let or = a.union(identity(b))
CheckResults(or.count == r)
}
}
@inline(never)
public func run_SetIntersectionInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.intersection(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
public func run_SetIntersectionSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.intersection(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
public func run_SetSubtractingInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.subtracting(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
public func run_SetSubtractingSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.subtracting(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
public func run_SetIsDisjointInt(
_ a: Set<Int>,
_ b: Set<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isDisjoint = a.isDisjoint(with: identity(b))
CheckResults(isDisjoint == r)
}
}
@inline(never)
public func run_SetIsDisjointSeqInt(
_ a: Set<Int>,
_ b: Array<Int>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isDisjoint = a.isDisjoint(with: identity(b))
CheckResults(isDisjoint == r)
}
}
@inline(never)
public func run_SetFilterInt50(_ n: Int) {
for _ in 0 ..< n {
let half = set.filter { $0 % 2 == 0 }
CheckResults(set.count == half.count * 2)
}
}
@inline(never)
public func run_SetFilterInt100(_ n: Int) {
for _ in 0 ..< n {
let copy = set.filter { _ in true }
CheckResults(set.count == copy.count)
}
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
func run_SetIsSubsetBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSubset = a.isSubset(of: identity(b))
CheckResults(isSubset == r)
}
}
@inline(never)
func run_SetIsSubsetSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSubset = a.isSubset(of: identity(b))
CheckResults(isSubset == r)
}
}
@inline(never)
func run_SetIsStrictSubsetBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSubset = a.isStrictSubset(of: identity(b))
CheckResults(isStrictSubset == r)
}
}
@inline(never)
func run_SetIsStrictSubsetSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSubset = a.isStrictSubset(of: identity(b))
CheckResults(isStrictSubset == r)
}
}
@inline(never)
func run_SetIsSupersetSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isSuperset = a.isSuperset(of: identity(b))
CheckResults(isSuperset == r)
}
}
@inline(never)
func run_SetIsStrictSupersetSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isStrictSuperset = a.isStrictSuperset(of: identity(b))
CheckResults(isStrictSuperset == r)
}
}
@inline(never)
func run_SetSymmetricDifferenceBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let diff = a.symmetricDifference(identity(b))
CheckResults(diff.count == r)
}
}
@inline(never)
func run_SetUnionBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let or = a.union(identity(b))
CheckResults(or.count == r)
}
}
@inline(never)
func run_SetIntersectionBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.intersection(b)
CheckResults(and.count == r)
}
}
@inline(never)
func run_SetIntersectionSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.intersection(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
func run_SetSubtractingBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.subtracting(b)
CheckResults(and.count == r)
}
}
@inline(never)
func run_SetSubtractingSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Int,
_ n: Int) {
for _ in 0 ..< n {
let and = a.subtracting(identity(b))
CheckResults(and.count == r)
}
}
@inline(never)
func run_SetIsDisjointBox(
_ a: Set<Box<Int>>,
_ b: Set<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isDisjoint = a.isDisjoint(with: identity(b))
CheckResults(isDisjoint == r)
}
}
@inline(never)
func run_SetIsDisjointSeqBox(
_ a: Set<Box<Int>>,
_ b: Array<Box<Int>>,
_ r: Bool,
_ n: Int) {
for _ in 0 ..< n {
let isDisjoint = a.isDisjoint(with: identity(b))
CheckResults(isDisjoint == r)
}
}
| 04a79d4a583db14b4fceb65988c29091 | 33.538043 | 91 | 0.628482 | false | false | false | false |
tkach/SimpleRedditClient | refs/heads/master | SimpleRedditClient/Common/Router/AppRouter.swift | mit | 1 | //
// Created by Alexander Tkachenko on 9/9/17.
//
import UIKit
final class AppRouter {
struct Constants {
static let rootNavigationRestorationID = "RootNavigationController"
}
fileprivate let modulesAssembly: ModulesAssembly
fileprivate lazy var navigationController: UINavigationController = {
let controller = UINavigationController(rootViewController: self.modulesAssembly.entriesListViewController())
controller.restorationIdentifier = Constants.rootNavigationRestorationID
return controller
}()
init(modulesAssembly: ModulesAssembly) {
self.modulesAssembly = modulesAssembly
}
func rootViewController() -> UIViewController {
return navigationController
}
func restoreController(with identifier: String, coder: NSCoder) -> UIViewController? {
if (identifier == Constants.rootNavigationRestorationID) {
return navigationController
}
else {
return modulesAssembly.restoreController(with: identifier, coder: coder)
}
}
}
extension AppRouter: EntriesListRouter {
func route(to item: EntryItem) {
let controller = modulesAssembly.entryDetailsViewController(with: item)
navigationController.pushViewController(controller, animated: true)
}
}
| c5f8012ac3157e85b110b01873bf567c | 31.268293 | 117 | 0.71353 | false | false | false | false |
xuzhuoxi/SearchKit | refs/heads/master | Source/cs/cacheconfig/CacheConfig.swift | mit | 1 | //
// CacheConfig.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/19.
//
//
import Foundation
/**
*
* @author xuzhuoxi
*
*/
open class CacheConfig {
open static let instance: CacheConfig = CacheConfig()
fileprivate var map = Dictionary<String, CacheInfo>()
fileprivate let currentBundle = Bundle(for: CacheConfig.self)
/**
* 缓存配置<br>
* resourcePath路径在实际使用时补充绝对路径,如要取消这种做法,请修改CachePool类<br>
* initialCapacity的配置应该根据实际情况进行配置<br>
* 计算方法:缓存数的下一个2的n次幂<br>
*/
fileprivate init(){
addConfig(CacheNames.PINYIN_WORD, "SearchKit.CharacterLibraryImpl", true, 32768, "word_pinyin", "UTF-8", ValueCodingType.pinyin_WORD)
addConfig(CacheNames.WUBI_WORD, "SearchKit.CharacterLibraryImpl", true, 8192, "word_wubi", "UTF-8", ValueCodingType.wubi_WORD)
}
fileprivate func toMultiPath(_ path: String?) ->[String]? {
if nil == path || path!.isEmpty {
return nil
}
return path!.components(separatedBy: ";")
}
fileprivate func addConfig(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourcePaths: String?, _ charsetName: String?, _ valueCodingType: ValueCodingType?) {
if map.has(cacheName) {
return
}
var urls : [URL]? = nil
if let paths = toMultiPath(resourcePaths) {
urls = []
for path in paths {
urls!.append(currentBundle.url(forResource: path, withExtension: "properites")!)
}
}
map[cacheName] = CacheInfo(cacheName, cacheClassName, isSingleton, initialCapacity, urls, charsetName, valueCodingType: valueCodingType)
}
fileprivate func addConfig(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingClassName: String?) {
if map.has(cacheName) {
return
}
map[cacheName] = CacheInfo(cacheName, cacheClassName, isSingleton, initialCapacity, resourceURLs, charsetName, valueCodingClassName:valueCodingClassName)
}
open func supplyConfig(_ cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, charsetName: String?, valueCodingClassName: String?) {
addConfig(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, charsetName, valueCodingClassName: valueCodingClassName)
}
open func getCacheInfo(_ cacheName : String) ->CacheInfo? {
return map[cacheName]
}
open func getCacheInfos() ->[CacheInfo] {
return [CacheInfo](map.values)
}
}
| bd159ded70f7aa8b1bb82de67d398998 | 36.583333 | 212 | 0.657428 | false | true | false | false |
therealbnut/swift | refs/heads/master | stdlib/public/core/Unicode.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
///
/// - SeeAlso: `UnicodeCodec.decode(next:)`
@_fixed_layout
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(UnicodeScalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `UnicodeScalar` type to work with
/// decoded Unicode scalar values.
///
/// - SeeAlso: `UTF8`, `UTF16`, `UTF32`, `UnicodeScalar`
public protocol UnicodeCodec {
/// A type that can hold code unit values for this encoding.
associatedtype CodeUnit
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
public struct UTF8 : UnicodeCodec {
// See Unicode 8.0.0, Ch 3.9, UTF-8.
// http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt8
/// Creates an instance of the UTF-8 codec.
public init() {}
/// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at MSB,
/// and bytes are read at LSB. Note that we need to use a buffer, because
/// in case of invalid subsequences we sometimes don't know whether we should
/// consume a certain byte before looking at it.
internal var _decodeBuffer: UInt32 = 0
/// The number of bits in `_decodeBuffer` that are current filled.
internal var _bitsInBuffer: UInt8 = 0
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
// Bufferless ASCII fastpath.
if _fastPath(_bitsInBuffer == 0) {
guard let codeUnit = input.next() else { return .emptyInput }
// ASCII, return immediately.
if codeUnit & 0x80 == 0 {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_decodeBuffer = UInt32(codeUnit)
_bitsInBuffer = 8
} else if _decodeBuffer & 0x80 == 0 {
// ASCII in buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
let codeUnit = _decodeBuffer & 0xff
_decodeBuffer >>= 8
_bitsInBuffer = _bitsInBuffer &- 8
return .scalarValue(UnicodeScalar(_unchecked: codeUnit))
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
_sanityCheck(_bitsInBuffer < 32)
repeat {
if let codeUnit = input.next() {
// We know _bitsInBuffer < 32 so we use `& 0x1f` (31) to make the
// compiler omit a bounds check branch for the bitshift.
_decodeBuffer |= (UInt32(codeUnit) << UInt32(_bitsInBuffer & 0x1f))
_bitsInBuffer = _bitsInBuffer &+ 8
} else {
if _bitsInBuffer == 0 { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _bitsInBuffer < 32
// Decode one unicode scalar.
// Note our empty bytes are always 0x00, which is required for this call.
let (result, length) = UTF8._decodeOne(_decodeBuffer)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let bitsConsumed = 8 &* length
_sanityCheck(1...4 ~= length && bitsConsumed <= _bitsInBuffer)
// Swift doesn't allow shifts greater than or equal to the type width.
// _decodeBuffer >>= UInt32(bitsConsumed) // >>= 32 crashes.
// Mask with 0x3f (63) to let the compiler omit the '>= 64' bounds check.
_decodeBuffer = UInt32(truncatingBitPattern:
UInt64(_decodeBuffer) >> (UInt64(bitsConsumed) & 0x3f))
_bitsInBuffer = _bitsInBuffer &- bitsConsumed
guard _fastPath(result != nil) else { return .error }
return .scalarValue(UnicodeScalar(_unchecked: result!))
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ … … … CU0 ].
let value = buffer & 0xff
return (value, 1)
}
// Determine sequence length using high 5 bits of 1st byte. We use a
// look-up table to branch less. 1-byte sequences are handled above.
//
// case | pattern | description
// ----------------------------
// 00 | 110xx | 2-byte sequence
// 01 | 1110x | 3-byte sequence
// 10 | 11110 | 4-byte sequence
// 11 | other | invalid
//
// 11xxx 10xxx 01xxx 00xxx
let lut0: UInt32 = 0b1011_0000__1111_1111__1111_1111__1111_1111
let lut1: UInt32 = 0b1100_0000__1111_1111__1111_1111__1111_1111
let index = (buffer >> 3) & 0x1f
let bit0 = (lut0 >> index) & 1
let bit1 = (lut1 >> index) & 1
switch (bit1, bit0) {
case (0, 0): // 2-byte sequence, buffer: [ … … CU1 CU0 ].
// Require 10xx xxxx 110x xxxx.
if _slowPath(buffer & 0xc0e0 != 0x80c0) { return (nil, 1) }
// Disallow xxxx xxxx xxx0 000x (<= 7 bits case).
if _slowPath(buffer & 0x001e == 0x0000) { return (nil, 1) }
// Extract data bits.
let value = (buffer & 0x3f00) >> 8
| (buffer & 0x001f) << 6
return (value, 2)
case (0, 1): // 3-byte sequence, buffer: [ … CU2 CU1 CU0 ].
// Disallow xxxx xxxx xx0x xxxx xxxx 0000 (<= 11 bits case).
if _slowPath(buffer & 0x00200f == 0x000000) { return (nil, 1) }
// Disallow xxxx xxxx xx1x xxxx xxxx 1101 (surrogate code points).
if _slowPath(buffer & 0x00200f == 0x00200d) { return (nil, 1) }
// Require 10xx xxxx 10xx xxxx 1110 xxxx.
if _slowPath(buffer & 0xc0c0f0 != 0x8080e0) {
if buffer & 0x00c000 != 0x008000 { return (nil, 1) }
return (nil, 2) // All checks on CU0 & CU1 passed.
}
// Extract data bits.
let value = (buffer & 0x3f0000) >> 16
| (buffer & 0x003f00) >> 2
| (buffer & 0x00000f) << 12
return (value, 3)
case (1, 0): // 4-byte sequence, buffer: [ CU3 CU2 CU1 CU0 ].
// Disallow xxxx xxxx xxxx xxxx xx00 xxxx xxxx x000 (<= 16 bits case).
if _slowPath(buffer & 0x00003007 == 0x00000000) { return (nil, 1) }
// If xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx.
if buffer & 0x00000004 == 0x00000004 {
// Require xxxx xxxx xxxx xxxx xx00 xxxx xxxx xx00 (<= 0x10FFFF).
if _slowPath(buffer & 0x00003003 != 0x00000000) { return (nil, 1) }
}
// Require 10xx xxxx 10xx xxxx 10xx xxxx 1111 0xxx.
if _slowPath(buffer & 0xc0c0c0f8 != 0x808080f0) {
if buffer & 0x0000c000 != 0x00008000 { return (nil, 1) }
// All other checks on CU0, CU1 & CU2 passed.
if buffer & 0x00c00000 != 0x00800000 { return (nil, 2) }
return (nil, 3)
}
// Extract data bits.
// FIXME(integers): remove extra type casts
let value = (buffer & 0x3f000000) >> (24 as UInt32)
| (buffer & 0x003f0000) >> (10 as UInt32)
| (buffer & 0x00003f00) << (4 as UInt32)
| (buffer & 0x00000007) << (18 as UInt32)
return (value, 4)
default: // Invalid sequence (CU0 invalid).
return (nil, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var c = UInt32(input)
var buf3 = UInt8(c & 0xFF)
if c >= UInt32(1<<7) {
c >>= 6
buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx
var buf2 = UInt8(c & 0xFF)
if c < UInt32(1<<5) {
buf2 |= 0xC0 // 110xxxxx
}
else {
c >>= 6
buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx
var buf1 = UInt8(c & 0xFF)
if c < UInt32(1<<4) {
buf1 |= 0xE0 // 1110xxxx
}
else {
c >>= 6
buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx
processCodeUnit(UInt8(c | 0xF0)) // 11110xxx
}
processCodeUnit(buf1)
}
processCodeUnit(buf2)
}
processCodeUnit(buf3)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
// Relying on a permissive memory model in C.
let cstr = unsafeBitCast(input, to: UnsafePointer<CChar>.self)
return Int(_swift_stdlib_strlen(cstr))
}
// Support parsing C strings as-if they are UTF8 strings.
public static func _nullCodeUnitOffset(in input: UnsafePointer<CChar>) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
public struct UTF16 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt16
/// Creates an instance of the UTF-16 codec.
public init() {}
/// A lookahead buffer for one UTF-16 code unit.
internal var _decodeLookahead: UInt16?
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
// Note: maximal subpart of ill-formed sequence for UTF-16 can only have
// length 1. Length 0 does not make sense. Neither does length 2 -- in
// that case the sequence is valid.
let unit0: UInt16
if _fastPath(_decodeLookahead == nil) {
guard let next = input.next() else { return .emptyInput }
unit0 = next
} else { // Consume lookahead first.
unit0 = _decodeLookahead!
_decodeLookahead = nil
}
// A well-formed pair of surrogates looks like this:
// high-surrogate low-surrogate
// [1101 10xx xxxx xxxx] [1101 11xx xxxx xxxx]
// Common case first, non-surrogate -- just a sequence of 1 code unit.
if _fastPath((unit0 >> 11) != 0b1101_1) {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(unit0)))
}
// Ensure `unit0` is a high-surrogate.
guard _fastPath((unit0 >> 10) == 0b1101_10) else { return .error }
// We already have a high-surrogate, so there should be a next code unit.
guard let unit1 = input.next() else { return .error }
// `unit0` is a high-surrogate, so `unit1` should be a low-surrogate.
guard _fastPath((unit1 >> 10) == 0b1101_11) else {
// Invalid sequence, discard `unit0` and store `unit1` for the next call.
_decodeLookahead = unit1
return .error
}
// We have a well-formed surrogate pair, decode it.
let result = 0x10000 + ((UInt32(unit0 & 0x03ff) << 10) | UInt32(unit1 & 0x03ff))
return .scalarValue(UnicodeScalar(_unchecked: result))
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
let scalarValue: UInt32 = UInt32(input)
if scalarValue <= UInt32(UInt16.max) {
processCodeUnit(UInt16(scalarValue))
}
else {
let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10)
processCodeUnit(UInt16(lead_offset + (scalarValue >> 10)))
processCodeUnit(UInt16(0xdc00 + (scalarValue & 0x3ff)))
}
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
public struct UTF32 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt32
/// Creates an instance of the UTF-32 codec.
public init() {}
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `UnicodeScalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard let x = input.next() else { return .emptyInput }
// Check code unit is valid: not surrogate-reserved and within range.
guard _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff)
else { return .error }
// x is a valid scalar.
return .scalarValue(UnicodeScalar(_unchecked: x))
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
public func transcode<Input, InputEncoding, OutputEncoding>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var inputDecoder = inputEncoding.init()
var hadError = false
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
OutputEncoding.encode(us, into: processCodeUnit)
case .emptyInput:
break loop
case .error:
hadError = true
if stopOnError {
break loop
}
OutputEncoding.encode("\u{fffd}", into: processCodeUnit)
}
}
return hadError
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
internal func _transcodeSomeUTF16AsUTF8<Input>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk)
where
Input : Collection,
Input.Iterator.Element == UInt16 {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = MemoryLayout<_UTF8Chunk>.size
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.IndexDistance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) << shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u >> 6
r |= (u & 0b11_1111) << 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u >> 12
r |= ((u >> 6) & 0b11_1111) << 8
r |= (u & 0b11_1111) << 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(input.index(nextIndex, offsetBy: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[input.index(nextIndex, offsetBy: 1)])
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v >> 18
r |= ((v >> 12) & 0b11_1111) << 8
r |= ((v >> 6) & 0b11_1111) << 16
r |= (v & 0b11_1111) << 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) << shift
utf8Count += scalarUtf8Length
}
nextIndex = input.index(nextIndex, offsetBy: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < MemoryLayout.size(ofValue: result) {
result |= ~0 << numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: UnicodeScalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: UnicodeScalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: UnicodeScalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.trailSurrogate(_:)`
public static func leadSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func trailSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit(
(x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1)
) + 0xDC00
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<Input, Encoding>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where
Input : IteratorProtocol,
Encoding : UnicodeCodec,
Encoding.CodeUnit == Input.Element {
var input = input
var count = 0
var isAscii = true
var inputDecoder = Encoding()
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
if us.value > 0x7f {
isAscii = false
}
count += width(us)
case .emptyInput:
break loop
case .error:
if !repairingIllFormedSequences {
return nil
}
isAscii = false
count += width(UnicodeScalar(0xfffd)!)
}
}
return (count, isAscii)
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension UnicodeScalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec where CodeUnit : UnsignedInteger {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
fatalError("_nullCodeUnitOffset(in:) implementation should be provided")
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
extension UnicodeCodec {
@available(*, unavailable, renamed: "encode(_:into:)")
public static func encode(
_ input: UnicodeScalar,
output put: (CodeUnit) -> Void
) {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
/// A namespace for Unicode utilities.
internal enum _Unicode {}
| c6e9fe66499fa92548cf108299bc4419 | 36.819949 | 106 | 0.625712 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Generics/derived_via_concrete_in_protocol.swift | apache-2.0 | 6 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s 2>&1 | %FileCheck %s
protocol P24 {
associatedtype C: P20
}
protocol P20 { }
struct X24<T: P20> : P24 {
typealias C = T
}
protocol P26 {
associatedtype C: X3
}
struct X26<T: X3> : P26 {
typealias C = T
}
class X3 { }
// CHECK-LABEL: .P25a@
// CHECK-NEXT: Requirement signature: <Self where Self.[P25a]A == X24<Self.[P25a]B>, Self.[P25a]B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P25a]A == X24<τ_0_0.[P25a]B>, τ_0_0.[P25a]B : P20>
protocol P25a {
associatedtype A: P24 // expected-warning{{redundant conformance constraint 'X24<Self.B>' : 'P24'}}
associatedtype B: P20 where A == X24<B>
}
// CHECK-LABEL: .P25b@
// CHECK-NEXT: Requirement signature: <Self where Self.[P25b]A == X24<Self.[P25b]B>, Self.[P25b]B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P25b]A == X24<τ_0_0.[P25b]B>, τ_0_0.[P25b]B : P20>
protocol P25b {
associatedtype A
associatedtype B: P20 where A == X24<B>
}
// CHECK-LABEL: .P27a@
// CHECK-NEXT: Requirement signature: <Self where Self.[P27a]A == X26<Self.[P27a]B>, Self.[P27a]B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P27a]A == X26<τ_0_0.[P27a]B>, τ_0_0.[P27a]B : X3>
protocol P27a {
associatedtype A: P26 // expected-warning{{redundant conformance constraint 'X26<Self.B>' : 'P26'}}
associatedtype B: X3 where A == X26<B>
}
// CHECK-LABEL: .P27b@
// CHECK-NEXT: Requirement signature: <Self where Self.[P27b]A == X26<Self.[P27b]B>, Self.[P27b]B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P27b]A == X26<τ_0_0.[P27b]B>, τ_0_0.[P27b]B : X3>
protocol P27b {
associatedtype A
associatedtype B: X3 where A == X26<B>
}
| 15b259a89c418592e717b20f671a967a | 32.436364 | 118 | 0.665579 | false | false | false | false |
mortorqrobotics/morscout-ios | refs/heads/master | MorScout/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// MorScout
//
// Created by Farbod Rafezy on 1/8/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import UIKit
import Kingfisher
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// set navigation bar color
UINavigationBar.appearance().barTintColor = UIColorFromHex("#FFC547")
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().isTranslucent = false
// this is so we can set the initial view controller to either
// the login screen on the home screen depending on login
// status upon opening the app.
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let revealVC : UIViewController! = mainStoryboard.instantiateViewController(withIdentifier: "reveal")
let loginVC : UIViewController! = mainStoryboard.instantiateViewController(withIdentifier: "login")
if let _ = storage.string(forKey: "connect.sid"){
//logged in
if storage.bool(forKey: "noTeam") {
logoutSilently()
self.window?.rootViewController = loginVC
} else {
self.window?.rootViewController = revealVC
}
} else {
//not logged in
self.window?.rootViewController = loginVC
}
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:.
}
}
| 23872f529eb952b9036a87cdfed98d5a | 45.070423 | 285 | 0.7059 | false | false | false | false |
madhusamuel/MovieBrowser | refs/heads/master | MovieBrowser/thirdparty/ObjectMapper_v0.14/Core/Mapper.swift | epl-1.0 | 2 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
// Copyright (c) 2014 hearst. All rights reserved.
//
import Foundation
public protocol Mappable {
static func newInstance() -> Mappable
mutating func mapping(map: Map)
}
public enum MappingType {
case FromJSON
case ToJSON
}
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
var JSONDictionary: [String : AnyObject] = [:]
var currentValue: AnyObject?
var currentKey: String?
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
private init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
currentKey = key
// break down the components of the key
currentValue = valueFor(ArraySlice(key.characters.split { $0 == "." }.map { String($0) }), dictionary: JSONDictionary)
return self
}
// MARK: Immutable Mapping
public func value<T>() -> T? {
return currentValue as? T
}
/// Returns whether the receiver is success or failure.
public var isValid: Bool {
return failedCount == 0
}
}
/// Fetch value from JSON dictionary, loop through them until we reach the desired object.
private func valueFor(keyPathComponents: ArraySlice<String>, dictionary: [String : AnyObject]) -> AnyObject? {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return nil
}
if let object: AnyObject = dictionary[keyPathComponents.first!] {
switch object {
case is NSNull:
return nil
case let dict as [String : AnyObject] where keyPathComponents.count > 1:
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
default:
return object
}
}
return nil
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public init(){
}
// MARK: Mapping functions that map to an existing object toObject
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
object.mapping(map)
return object
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
if let string = JSONString as? String {
return map(string)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
if var object = N.newInstance() as? N {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
object.mapping(map)
return object
}
return nil
}
//MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N] {
let parsedJSON: AnyObject? = parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return []
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N] {
// map every element in JSON array to type N
return JSONArray.filterMap(map)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N] {
// map every value in dictionary to type N
return JSONDictionary.filterMap(map)
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]] {
// map every value in dictionary to type N
return JSONDictionary.filterMap({ mapArray($0) })
}
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(var object: N) -> [String : AnyObject] {
let map = Map(mappingType: .ToJSON, JSONDictionary: [:])
object.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string
public func toJSONString(object: N, prettyPrint: Bool) -> String? {
let JSONDict = toJSON(object)
var err: NSError?
if NSJSONSerialization.isValidJSONObject(JSONDict) {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
let JSONData: NSData?
do {
JSONData = try NSJSONSerialization.dataWithJSONObject(JSONDict, options: options)
} catch let error as NSError {
err = error
JSONData = nil
}
if let error = err {
print(error)
}
if let JSON = JSONData {
return NSString(data: JSON, encoding: NSUTF8StringEncoding) as? String
}
}
return nil
}
// MARK: Private utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
private func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = parseJSONString(JSON)
return parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
private func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
if let JSONDict = JSON as? [String : AnyObject] {
return JSONDict
}
return nil
}
/// Convert a JSON String into an Object using NSJSONSerialization
private func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
var error: NSError?
let parsedJSON: AnyObject?
do {
parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
} catch let error1 as NSError {
error = error1
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Array {
internal func filterMap<U>(@noescape f: Element -> U?) -> [U] {
var mapped = [U]()
for value in self {
if let newValue = f(value) {
mapped.append(newValue)
}
}
return mapped
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
if let newValue = f(value){
mapped[key] = newValue
}
}
return mapped
}
}
| d149fbc859b57a9e212e67c0a0911eb9 | 27.392857 | 123 | 0.698984 | false | false | false | false |
touchopia/Codementor-Swift-201 | refs/heads/master | SourceCode/StickersApp-Final/StickersApp/PinchZoomImageView.swift | mit | 1 | //
// PinchZoomImageView
// PinchZoomImageView
//
// Created by Phil Wright on 8/22/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
class PinchZoomImageView: UIImageView, UIGestureRecognizerDelegate {
var originalTransform = CGAffineTransformIdentity
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
override init(image: UIImage?) {
super.init(image: image)
self.initialize()
}
func initialize() {
// Important for allowing user interaction
self.userInteractionEnabled = true
self.multipleTouchEnabled = true
self.exclusiveTouch = true
// Aspect Fit the Image
self.contentMode = .ScaleAspectFit
// Important: One gesture recognizer type is required to monitor this UIImageView
// 1. Add the Tap Gesture
let tapGesture = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
// 2. Add the Pan Gesture
let panGesture = UIPanGestureRecognizer(target: self, action:Selector("handlePan:"))
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
// 3. Add the Pinch Gesture
let pinchGesture = UIPinchGestureRecognizer(target: self, action:Selector("handlePinch:"))
pinchGesture.delegate = self
self.addGestureRecognizer(pinchGesture)
// 4. Add the Rotate Gesture
let rotateGesture = UIRotationGestureRecognizer(target: self, action:Selector("handleRotate:"))
rotateGesture.delegate = self
self.addGestureRecognizer(rotateGesture)
}
// Mark - Gesture Methods
func handleTap(recognizer: UITapGestureRecognizer) {
if let view = recognizer.view {
view.superview!.bringSubviewToFront(self)
}
}
func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(recognizer.view)
if let view = recognizer.view {
view.transform = CGAffineTransformTranslate(view.transform, translation.x, translation.y)
}
recognizer.setTranslation(CGPointZero, inView: self)
}
func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
}
// Needed to allow multiple touches (i.e. zoom and pinch)
func gestureRecognizer(_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
return true
}
}
| 13a3fadff9683ab2fc2bedbeb561d05a | 29.558559 | 103 | 0.638267 | false | false | false | false |
ibm-bluemix-push-notifications/bms-samples-swift-login | refs/heads/master | userIdBasedSwift/MessageViewController.swift | apache-2.0 | 1 | //
// MessageViewController.swift
// userIdBasedSwift
//
// Created by Anantha Krishnan K G on 25/07/16.
// Copyright © 2016 Ananth. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController, PopupContentViewController {
var closeHandler: (() -> Void)?
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
@IBOutlet var pushNotificationMessage: UILabel!
@IBOutlet weak var button: UIButton! {
didSet {
button.layer.borderColor = UIColor(red: 242/255, green: 105/255, blue: 100/255, alpha: 1.0).CGColor
button.layer.borderWidth = 1.5
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.frame.size = CGSizeMake(250,200)
pushNotificationMessage.text = appDelegate.message
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class func instance() -> MessageViewController {
let storyboard = UIStoryboard(name: "DemoPopupViewController1", bundle: nil)
return storyboard.instantiateInitialViewController() as! MessageViewController
}
func sizeForPopup(popupController: PopupController, size: CGSize, showingKeyboard: Bool) -> CGSize {
return CGSizeMake(300,300)
}
@IBAction func didTapCloseButton(sender: AnyObject) {
closeHandler?()
}
}
| 265c644165b0891e9fdd435a3e1fab25 | 29.96 | 111 | 0.669251 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanViewController.swift | gpl-2.0 | 1 | import UIKit
import WordPressFlux
class JetpackScanViewController: UIViewController, JetpackScanView {
private let blog: Blog
lazy var coordinator: JetpackScanCoordinator = {
return JetpackScanCoordinator(blog: blog, view: self)
}()
// Table View
@IBOutlet weak var tableView: UITableView!
let refreshControl = UIRefreshControl()
// Loading / Errors
private var noResultsViewController: NoResultsViewController?
// MARK: - Initializers
@objc init(blog: Blog) {
self.blog = blog
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Methods
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Scan", comment: "Title of the view")
extendedLayoutIncludesOpaqueBars = true
configureTableView()
coordinator.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("History", comment: "Title of a navigation button that opens the scan history view"),
style: .plain,
target: self,
action: #selector(showHistory))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
WPAnalytics.track(.jetpackScanAccessed)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
coordinator.viewWillDisappear()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.tableView.beginUpdates()
self.tableView.endUpdates()
})
}
// MARK: - JetpackScanView
func render() {
updateNoResults(nil)
refreshControl.endRefreshing()
tableView.reloadData()
}
func toggleHistoryButton(_ isEnabled: Bool) {
navigationItem.rightBarButtonItem?.isEnabled = isEnabled
}
func showLoading() {
let model = NoResultsViewController.Model(title: NoResultsText.loading.title,
accessoryView: NoResultsViewController.loadingAccessoryView())
updateNoResults(model)
}
func showGenericError() {
let model = NoResultsViewController.Model(title: NoResultsText.error.title,
subtitle: NoResultsText.error.subtitle,
buttonText: NoResultsText.contactSupportButtonText)
updateNoResults(model)
}
func showNoConnectionError() {
let model = NoResultsViewController.Model(title: NoResultsText.noConnection.title,
subtitle: NoResultsText.noConnection.subtitle,
buttonText: NoResultsText.tryAgainButtonText)
updateNoResults(model)
}
func showScanStartError() {
let model = NoResultsViewController.Model(title: NoResultsText.scanStartError.title,
subtitle: NoResultsText.scanStartError.subtitle,
buttonText: NoResultsText.contactSupportButtonText)
updateNoResults(model)
}
func showMultisiteNotSupportedError() {
let model = NoResultsViewController.Model(title: NoResultsText.multisiteError.title,
subtitle: NoResultsText.multisiteError.subtitle,
imageName: NoResultsText.multisiteError.imageName)
updateNoResults(model)
refreshControl.endRefreshing()
}
func vaultPressActiveOnSite() {
let model = NoResultsViewController.Model(title: NoResultsText.vaultPressError.title,
subtitle: NoResultsText.vaultPressError.subtitle,
buttonText: NoResultsText.vaultPressError.buttonLabel,
imageName: NoResultsText.multisiteError.imageName)
updateNoResults(model)
noResultsViewController?.actionButtonHandler = { [weak self] in
let dashboardURL = URL(string: "https://dashboard.vaultpress.com/")!
let webViewController = WebViewControllerFactory.controller(url: dashboardURL, source: "jetpack_backup")
let webViewNavigationController = UINavigationController(rootViewController: webViewController)
self?.present(webViewNavigationController, animated: true)
}
refreshControl.endRefreshing()
}
func presentAlert(_ alert: UIAlertController) {
present(alert, animated: true, completion: nil)
}
func presentNotice(with title: String, message: String?) {
displayNotice(title: title, message: message)
}
func showIgnoreThreatSuccess(for threat: JetpackScanThreat) {
navigationController?.popViewController(animated: true)
coordinator.refreshData()
let model = JetpackScanThreatViewModel(threat: threat)
let notice = Notice(title: model.ignoreSuccessTitle)
ActionDispatcher.dispatch(NoticeAction.post(notice))
}
func showIgnoreThreatError(for threat: JetpackScanThreat) {
navigationController?.popViewController(animated: true)
coordinator.refreshData()
let model = JetpackScanThreatViewModel(threat: threat)
let notice = Notice(title: model.ignoreErrorTitle)
ActionDispatcher.dispatch(NoticeAction.post(notice))
}
func showJetpackSettings(with siteID: Int) {
guard let controller = JetpackWebViewControllerFactory.settingsController(siteID: siteID) else {
let title = NSLocalizedString("Unable to visit Jetpack settings for site", comment: "Message displayed when visiting the Jetpack settings page fails.")
displayNotice(title: title)
return
}
let navigationVC = UINavigationController(rootViewController: controller)
present(navigationVC, animated: true)
}
// MARK: - Actions
@objc func showHistory() {
let viewController = JetpackScanHistoryViewController(blog: blog)
navigationController?.pushViewController(viewController, animated: true)
}
// MARK: - Private:
private func configureTableView() {
tableView.register(JetpackScanStatusCell.defaultNib, forCellReuseIdentifier: Constants.statusCellIdentifier)
tableView.register(JetpackScanThreatCell.defaultNib, forCellReuseIdentifier: Constants.threatCellIdentifier)
tableView.register(ActivityListSectionHeaderView.defaultNib,
forHeaderFooterViewReuseIdentifier: ActivityListSectionHeaderView.identifier)
tableView.tableFooterView = UIView()
tableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(userRefresh), for: .valueChanged)
}
@objc func userRefresh() {
coordinator.refreshData()
}
// MARK: - Private: Config
private struct Constants {
static let statusCellIdentifier = "StatusCell"
static let threatCellIdentifier = "ThreatCell"
/// The number of header rows, used to get the threat rows
static let tableHeaderCountOffset = 1
}
}
extension JetpackScanViewController: JetpackScanThreatDetailsViewControllerDelegate {
func willFixThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController) {
navigationController?.popViewController(animated: true)
coordinator.fixThreat(threat: threat)
}
func willIgnoreThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController) {
coordinator.ignoreThreat(threat: threat)
}
}
// MARK: - Table View
extension JetpackScanViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
let count = coordinator.sections?.count ?? 0
return count + Constants.tableHeaderCountOffset
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section < Constants.tableHeaderCountOffset {
return 1
}
guard let historySection = threatSection(for: section) else {
return 0
}
return historySection.threats.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let title = threatSection(for: section)?.title,
let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: ActivityListSectionHeaderView.identifier) as? ActivityListSectionHeaderView else {
return UIView(frame: .zero)
}
cell.titleLabel.text = title
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if threatSection(for: section)?.title == nil {
return 0
}
return ActivityListSectionHeaderView.height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell
if let threat = threat(for: indexPath) {
let threatCell = tableView.dequeueReusableCell(withIdentifier: Constants.threatCellIdentifier) as? JetpackScanThreatCell ?? JetpackScanThreatCell(style: .default, reuseIdentifier: Constants.threatCellIdentifier)
configureThreatCell(cell: threatCell, threat: threat)
cell = threatCell
} else {
let statusCell = tableView.dequeueReusableCell(withIdentifier: Constants.statusCellIdentifier) as? JetpackScanStatusCell ?? JetpackScanStatusCell(style: .default, reuseIdentifier: Constants.statusCellIdentifier)
configureStatusCell(cell: statusCell)
cell = statusCell
}
return cell
}
private func configureStatusCell(cell: JetpackScanStatusCell) {
guard let model = JetpackScanStatusViewModel(coordinator: coordinator) else {
// TODO: handle error
return
}
cell.configure(with: model)
}
private func configureThreatCell(cell: JetpackScanThreatCell, threat: JetpackScanThreat) {
let model = JetpackScanThreatViewModel(threat: threat)
cell.configure(with: model)
}
private func threatSection(for index: Int) -> JetpackThreatSection? {
let adjustedIndex = index - Constants.tableHeaderCountOffset
guard
adjustedIndex >= 0, let section = coordinator.sections?[adjustedIndex] else {
return nil
}
return section
}
private func threat(for indexPath: IndexPath) -> JetpackScanThreat? {
guard let section = threatSection(for: indexPath.section) else {
return nil
}
return section.threats[indexPath.row]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let threat = threat(for: indexPath), threat.status != .fixing else {
return
}
let threatDetailsVC = JetpackScanThreatDetailsViewController(blog: blog,
threat: threat,
hasValidCredentials: coordinator.hasValidCredentials)
threatDetailsVC.delegate = self
self.navigationController?.pushViewController(threatDetailsVC, animated: true)
WPAnalytics.track(.jetpackScanThreatListItemTapped, properties: ["threat_signature": threat.signature, "section": "scanner"])
}
}
// MARK: - Loading / Errors
extension JetpackScanViewController: NoResultsViewControllerDelegate {
func updateNoResults(_ viewModel: NoResultsViewController.Model?) {
if let noResultsViewModel = viewModel {
showNoResults(noResultsViewModel)
} else {
noResultsViewController?.view.isHidden = true
tableView.reloadData()
}
}
private func showNoResults(_ viewModel: NoResultsViewController.Model) {
if noResultsViewController == nil {
noResultsViewController = NoResultsViewController.controller()
noResultsViewController?.delegate = self
guard let noResultsViewController = noResultsViewController else {
return
}
if noResultsViewController.view.superview != tableView {
tableView.addSubview(noResultsViewController.view)
}
addChild(noResultsViewController)
noResultsViewController.view.translatesAutoresizingMaskIntoConstraints = false
}
noResultsViewController?.bindViewModel(viewModel)
noResultsViewController?.didMove(toParent: self)
tableView.pinSubviewToSafeArea(noResultsViewController!.view)
noResultsViewController?.view.isHidden = false
}
func actionButtonPressed() {
coordinator.noResultsButtonPressed()
}
private struct NoResultsText {
struct loading {
static let title = NSLocalizedString("Loading Scan...", comment: "Text displayed while loading the scan section for a site")
}
struct scanStartError {
static let title = NSLocalizedString("Something went wrong", comment: "Title for the error view when the scan start has failed")
static let subtitle = NSLocalizedString("Jetpack Scan couldn't complete a scan of your site. Please check to see if your site is down – if it's not, try again. If it is, or if Jetpack Scan is still having problems, contact our support team.", comment: "Error message shown when the scan start has failed.")
}
struct multisiteError {
static let title = NSLocalizedString("WordPress multisites are not supported", comment: "Title for label when the user's site is a multisite.")
static let subtitle = NSLocalizedString("We're sorry, Jetpack Scan is not compatible with multisite WordPress installations at this time.", comment: "Description for label when the user's site is a multisite.")
static let imageName = "jetpack-scan-state-error"
}
struct vaultPressError {
static let title = NSLocalizedString("Your site has VaultPress", comment: "Title for label when the user has VaultPress enabled.")
static let subtitle = NSLocalizedString("Your site already is protected by VaultPress. You can find a link to your VaultPress dashboard below.", comment: "Description for label when the user has a site with VaultPress.")
static let buttonLabel = NSLocalizedString("Visit Dashboard", comment: "Text of a button that links to the VaultPress dashboard.")
static let imageName = "jetpack-scan-state-error"
}
struct error {
static let title = NSLocalizedString("Oops", comment: "Title for the view when there's an error loading scan status")
static let subtitle = NSLocalizedString("There was an error loading the scan status", comment: "Text displayed when there is a failure loading the status")
}
struct noConnection {
static let title = NSLocalizedString("No connection", comment: "Title for the error view when there's no connection")
static let subtitle = NSLocalizedString("An active internet connection is required to view Jetpack Scan", comment: "Error message shown when trying to view the scan status and there is no internet connection.")
}
static let tryAgainButtonText = NSLocalizedString("Try again", comment: "Button label for trying to retrieve the scan status again")
static let contactSupportButtonText = NSLocalizedString("Contact support", comment: "Button label for contacting support")
}
}
| b28bfd4ad3c87a8c3762814b5147643f | 40.577215 | 318 | 0.662912 | false | false | false | false |
baodvu/dashtag | refs/heads/master | dashtag/RegisterViewController.swift | mit | 1 | //
// RegisterViewController.swift
// dashtag
//
// Created by Bao Vu on 10/16/16.
// Copyright © 2016 Dashtag. All rights reserved.
//
import UIKit
import FirebaseAuth
class RegisterViewController: UIViewController {
@IBOutlet weak var fullNameTF: UITextField!
@IBOutlet weak var emailTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var confirmPasswordTF: UITextField!
var fullName: String {
get {
return fullNameTF.text ?? ""
}
}
var email: String {
get {
let s = emailTF.text ?? ""
return isValidEmail(s) ? s : ""
}
}
var password: String {
get {
return (passwordTF.text ?? "" == confirmPasswordTF.text ?? "") ? passwordTF.text! : ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(testStr)
}
@IBAction func createAccount(sender: UIButton) {
if email == "" {
showAlert("Please check the email field")
return
}
if fullName == "" {
showAlert("Please check the name field")
return
}
if password == "" {
showAlert("Please check the password again")
return
}
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
if (error != nil) {
print(error)
let alert = UIAlertController(title: "Registration failed", message: "Please make sure you entered all fields correctly", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = self.fullName
changeRequest.commitChangesWithCompletion { error in
if error != nil {
// An error happened.
} else {
// Profile updated.
}
}
self.performSegueWithIdentifier("SegueRegisterToLogin", sender: self)
}
}
}
}
func showAlert(message: String) -> Void {
let alert = UIAlertController(title: "Registration failed", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| f7a12e57ffba49028d44ab0795fa3b3d | 33.486726 | 183 | 0.573518 | false | false | false | false |
Eveets/cryptick | refs/heads/master | cryptick/Model/Ticker.swift | apache-2.0 | 1 | //
// Ticker.swift
// cryptick
//
// Created by Steeve Monniere on 20-07-2017.
// Copyright © 2017 Steeve Monniere. All rights reserved.
//
import UIKit
class Ticker: NSObject {
//Pair Info
var base:String?
var quote:String?
var active : Bool = false
//Info
var price:Double?
var ask:Double?
var bid:Double?
var low:Double?
var high:Double?
var volume:Double?
var openPrice:Double?
var vwap:Double?
var unchanged:Bool = true
var up:Bool = false
//Calculated value
var pairName:String {
get{return String.localizedStringWithFormat("%@%@", base!, quote!)}
set{}
}
var percentChange:Double {
get{
if(price != nil && openPrice != nil && openPrice != 0.0){
return price!/openPrice!;
}
else
{
return 0.00
}
}
set{}
}
static func ticker (base:String, quote:String) -> Ticker
{
let t = Ticker.init()
t.base = base
t.quote = quote
return t
}
}
| 5664f91bb86ab6e5da6f16c9c912734b | 18.20339 | 75 | 0.518976 | false | false | false | false |
BPerlakiH/Swift4Cart | refs/heads/master | SwiftCart/Model/FX.swift | mit | 1 | //
// FX.swift
// SwiftCart
//
// Created by Balazs Perlaki-Horvath on 07/07/2017.
// Copyright © 2017 perlakidigital. All rights reserved.
//
import Foundation
import UIKit
class FX {
let apiKey : String
let activeCurrencies : [String]
var response : FxResponse?
init() {
apiKey = Bundle.main.object(forInfoDictionaryKey: "FX_API_Key") as! String
activeCurrencies = Bundle.main.object(forInfoDictionaryKey: "FX_Active_Currencies") as! [String]
}
func all() -> Dictionary<String, Float>? {
return self.response?.quotes
}
func refresh(completion: () -> Void) {
let downloader = FXDownloader()
downloader.downloadRates(apiKey: apiKey, currencies: activeCurrencies) { (data, error) in
if let _ = error {
NSLog("other api error", error.debugDescription)
return
}
guard let jsonData = data else {
NSLog("no data has been returned")
return
}
let decoder = JSONDecoder()
self.response = try? decoder.decode(FxResponse.self, from: jsonData)
}
}
func rateOf(currency: String) -> Float? {
assert(currency.count == 3)
assert(activeCurrencies.contains(currency))
return self.response?.quotes["USD\(currency)"]
}
func priceOf(price: Float, inCurrency: String) -> Float {
assert(inCurrency.count == 3)
assert(inCurrency == "USD" || activeCurrencies.contains(inCurrency))
if let rate = self.response?.quotes["USD\(inCurrency)"] {
return rate * price
} else {
return price
}
}
func _getJsonData() -> Data {
let fxData = """
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timestamp": 1499431446,
"source": "USD",
"quotes": {
"USDAUD": 1.315016,
"USDCAD": 1.291402,
"USDCHF": 0.96167,
"USDEUR": 0.87505,
"USDGBP": 0.77495,
"USDHUF": 269.619995,
"USDPLN": 3.704299
}
}
""".data(using: .utf8)!
return fxData
}
}
| 9a4612fcbab634120a8043c45b7ad92c | 27.573171 | 104 | 0.536492 | false | false | false | false |
airbnb/lottie-ios | refs/heads/master | Sources/Private/Model/DotLottie/Zip/ZipArchive.swift | apache-2.0 | 2 | //
// Archive.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
// MARK: - ZipArchive
final class ZipArchive: Sequence {
// MARK: Lifecycle
/// Initializes a new ZIP `Archive`.
///
/// You can use this initalizer to create new archive files or to read and update existing ones.
/// - Parameters:
/// - url: File URL to the receivers backing file.
/// - Returns: An archive initialized with a backing file at the passed in file URL and the given access mode
/// or `nil` if the following criteria are not met:
init?(url: URL) {
self.url = url
guard let config = ZipArchive.makeBackingConfiguration(for: url) else { return nil }
archiveFile = config.file
endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
setvbuf(archiveFile, nil, _IOFBF, Int(Self.defaultPOSIXBufferSize))
}
deinit {
fclose(self.archiveFile)
}
// MARK: Internal
typealias LocalFileHeader = ZipEntry.LocalFileHeader
typealias DataDescriptor = ZipEntry.DefaultDataDescriptor
typealias ZIP64DataDescriptor = ZipEntry.ZIP64DataDescriptor
typealias CentralDirectoryStructure = ZipEntry.CentralDirectoryStructure
/// An error that occurs during reading, creating or updating a ZIP file.
enum ArchiveError: Error {
/// Thrown when an archive file is either damaged or inaccessible.
case unreadableArchive
/// Thrown when an archive is either opened with AccessMode.read or the destination file is unwritable.
case unwritableArchive
/// Thrown when the path of an `Entry` cannot be stored in an archive.
case invalidEntryPath
/// Thrown when an `Entry` can't be stored in the archive with the proposed compression method.
case invalidCompressionMethod
/// Thrown when the stored checksum of an `Entry` doesn't match the checksum during reading.
case invalidCRC32
/// Thrown when an extract, add or remove operation was canceled.
case cancelledOperation
/// Thrown when an extract operation was called with zero or negative `bufferSize` parameter.
case invalidBufferSize
/// Thrown when uncompressedSize/compressedSize exceeds `Int64.max` (Imposed by file API).
case invalidEntrySize
/// Thrown when the offset of local header data exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderDataOffset
/// Thrown when the size of local header exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderSize
/// Thrown when the offset of central directory exceeds `Int64.max` (Imposed by file API).
case invalidCentralDirectoryOffset
/// Thrown when the size of central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectorySize
/// Thrown when number of entries in central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectoryEntryCount
/// Thrown when an archive does not contain the required End of Central Directory Record.
case missingEndOfCentralDirectoryRecord
}
struct EndOfCentralDirectoryRecord: DataSerializable {
let endOfCentralDirectorySignature = UInt32(endOfCentralDirectoryStructSignature)
let numberOfDisk: UInt16
let numberOfDiskStart: UInt16
let totalNumberOfEntriesOnDisk: UInt16
let totalNumberOfEntriesInCentralDirectory: UInt16
let sizeOfCentralDirectory: UInt32
let offsetToStartOfCentralDirectory: UInt32
let zipFileCommentLength: UInt16
let zipFileCommentData: Data
static let size = 22
}
// MARK: - Helpers
typealias EndOfCentralDirectoryStructure = (EndOfCentralDirectoryRecord, ZIP64EndOfCentralDirectory?)
struct BackingConfiguration {
let file: FILEPointer
let endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
let zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
init(
file: FILEPointer,
endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord,
zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?)
{
self.file = file
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = zip64EndOfCentralDirectory
}
}
static let defaultPOSIXBufferSize = Int(16 * 1024)
static let minEndOfCentralDirectoryOffset = Int64(22)
static let endOfCentralDirectoryStructSignature = 0x06054b50
/// The default chunk size when reading entry data from an archive.
static let defaultReadChunkSize = Int(16 * 1024)
/// URL of an Archive's backing file.
let url: URL
var archiveFile: FILEPointer
var endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
var zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
var totalNumberOfEntriesInCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.totalNumberOfEntriesInCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.totalNumberOfEntriesInCentralDirectory)
}
var sizeOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.sizeOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.sizeOfCentralDirectory)
}
var offsetToStartOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.offsetToStartOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory)
}
static func scanForEndOfCentralDirectoryRecord(in file: FILEPointer)
-> EndOfCentralDirectoryStructure?
{
var eocdOffset: UInt64 = 0
var index = minEndOfCentralDirectoryOffset
fseeko(file, 0, SEEK_END)
let archiveLength = Int64(ftello(file))
while eocdOffset == 0, index <= archiveLength {
fseeko(file, off_t(archiveLength - index), SEEK_SET)
var potentialDirectoryEndTag = UInt32()
fread(&potentialDirectoryEndTag, 1, MemoryLayout<UInt32>.size, file)
if potentialDirectoryEndTag == UInt32(endOfCentralDirectoryStructSignature) {
eocdOffset = UInt64(archiveLength - index)
guard let eocd: EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: eocdOffset) else {
return nil
}
let zip64EOCD = scanForZIP64EndOfCentralDirectory(in: file, eocdOffset: eocdOffset)
return (eocd, zip64EOCD)
}
index += 1
}
return nil
}
static func makeBackingConfiguration(for url: URL) -> BackingConfiguration? {
let fileManager = FileManager()
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard
let archiveFile = fopen(fileSystemRepresentation, "rb"),
let (eocdRecord, zip64EOCD) = ZipArchive.scanForEndOfCentralDirectoryRecord(in: archiveFile) else
{
return nil
}
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD)
}
func makeIterator() -> AnyIterator<ZipEntry> {
let totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var directoryIndex = offsetToStartOfCentralDirectory
var index = 0
return AnyIterator {
guard index < totalNumberOfEntriesInCD else { return nil }
guard
let centralDirStruct: CentralDirectoryStructure = Data.readStruct(
from: self.archiveFile,
at: directoryIndex) else
{
return nil
}
let offset = UInt64(centralDirStruct.effectiveRelativeOffsetOfLocalHeader)
guard
let localFileHeader: LocalFileHeader = Data.readStruct(
from: self.archiveFile,
at: offset) else { return nil }
var dataDescriptor: DataDescriptor?
var zip64DataDescriptor: ZIP64DataDescriptor?
if centralDirStruct.usesDataDescriptor {
let additionalSize = UInt64(localFileHeader.fileNameLength) + UInt64(localFileHeader.extraFieldLength)
let isCompressed = centralDirStruct.compressionMethod != 0
let dataSize = isCompressed
? centralDirStruct.effectiveCompressedSize
: centralDirStruct.effectiveUncompressedSize
let descriptorPosition = offset + UInt64(LocalFileHeader.size) + additionalSize + dataSize
if centralDirStruct.isZIP64 {
zip64DataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
} else {
dataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
}
}
defer {
directoryIndex += UInt64(CentralDirectoryStructure.size)
directoryIndex += UInt64(centralDirStruct.fileNameLength)
directoryIndex += UInt64(centralDirStruct.extraFieldLength)
directoryIndex += UInt64(centralDirStruct.fileCommentLength)
index += 1
}
return ZipEntry(
centralDirectoryStructure: centralDirStruct,
localFileHeader: localFileHeader,
dataDescriptor: dataDescriptor,
zip64DataDescriptor: zip64DataDescriptor)
}
}
/// Retrieve the ZIP `Entry` with the given `path` from the receiver.
///
/// - Note: The ZIP file format specification does not enforce unique paths for entries.
/// Therefore an archive can contain multiple entries with the same path. This method
/// always returns the first `Entry` with the given `path`.
///
/// - Parameter path: A relative file path identifying the corresponding `Entry`.
/// - Returns: An `Entry` with the given `path`. Otherwise, `nil`.
subscript(path: String) -> ZipEntry? {
first { $0.path == path }
}
/// Read a ZIP `Entry` from the receiver and write it to `url`.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - url: The destination file URL.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
func extract(_ entry: ZipEntry, to url: URL, bufferSize: Int = defaultReadChunkSize) throws -> UInt32 {
guard bufferSize > 0 else { throw ArchiveError.invalidBufferSize }
let fileManager = FileManager()
try fileManager.createParentDirectoryStructure(for: url)
let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard let destinationFile: FILEPointer = fopen(destinationRepresentation, "wb+") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(destinationFile) }
guard bufferSize > 0 else { throw ArchiveError.invalidBufferSize }
guard entry.dataOffset <= .max else { throw ArchiveError.invalidLocalHeaderDataOffset }
fseeko(archiveFile, off_t(entry.dataOffset), SEEK_SET)
let attributes = FileManager.attributes(from: entry)
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
let size = entry.centralDirectoryStructure.effectiveCompressedSize
guard size <= .max else { throw ArchiveError.invalidEntrySize }
return try Data.decompress(size: Int64(size), bufferSize: bufferSize, provider: { _, chunkSize -> Data in
try Data.readChunk(of: chunkSize, from: self.archiveFile)
}, consumer: { data in
_ = try Data.write(chunk: data, to: destinationFile)
})
}
// MARK: Private
private static func scanForZIP64EndOfCentralDirectory(in file: FILEPointer, eocdOffset: UInt64)
-> ZIP64EndOfCentralDirectory?
{
guard UInt64(ZIP64EndOfCentralDirectoryLocator.size) < eocdOffset else {
return nil
}
let locatorOffset = eocdOffset - UInt64(ZIP64EndOfCentralDirectoryLocator.size)
guard UInt64(ZIP64EndOfCentralDirectoryRecord.size) < locatorOffset else {
return nil
}
let recordOffset = locatorOffset - UInt64(ZIP64EndOfCentralDirectoryRecord.size)
guard
let locator: ZIP64EndOfCentralDirectoryLocator = Data.readStruct(from: file, at: locatorOffset),
let record: ZIP64EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: recordOffset) else
{
return nil
}
return ZIP64EndOfCentralDirectory(record: record, locator: locator)
}
}
// MARK: - Zip64
extension ZipArchive {
struct ZIP64EndOfCentralDirectory {
let record: ZIP64EndOfCentralDirectoryRecord
let locator: ZIP64EndOfCentralDirectoryLocator
}
struct ZIP64EndOfCentralDirectoryRecord: DataSerializable {
let zip64EOCDRecordSignature = UInt32(zip64EOCDRecordStructSignature)
let sizeOfZIP64EndOfCentralDirectoryRecord: UInt64
let versionMadeBy: UInt16
let versionNeededToExtract: UInt16
let numberOfDisk: UInt32
let numberOfDiskStart: UInt32
let totalNumberOfEntriesOnDisk: UInt64
let totalNumberOfEntriesInCentralDirectory: UInt64
let sizeOfCentralDirectory: UInt64
let offsetToStartOfCentralDirectory: UInt64
let zip64ExtensibleDataSector: Data
static let size = 56
}
struct ZIP64EndOfCentralDirectoryLocator: DataSerializable {
let zip64EOCDLocatorSignature = UInt32(zip64EOCDLocatorStructSignature)
let numberOfDiskWithZIP64EOCDRecordStart: UInt32
let relativeOffsetOfZIP64EOCDRecord: UInt64
let totalNumberOfDisk: UInt32
static let size = 20
}
static let zip64EOCDRecordStructSignature = 0x06064b50
static let zip64EOCDLocatorStructSignature = 0x07064b50
}
extension ZipArchive.ZIP64EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == ZipArchive.ZIP64EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDRecordSignature else { return nil }
sizeOfZIP64EndOfCentralDirectoryRecord = data.scanValue(start: 4)
versionMadeBy = data.scanValue(start: 12)
versionNeededToExtract = data.scanValue(start: 14)
// Version Needed to Extract: 4.5 - File uses ZIP64 format extensions
guard versionNeededToExtract >= 45 else { return nil }
numberOfDisk = data.scanValue(start: 16)
numberOfDiskStart = data.scanValue(start: 20)
totalNumberOfEntriesOnDisk = data.scanValue(start: 24)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 32)
sizeOfCentralDirectory = data.scanValue(start: 40)
offsetToStartOfCentralDirectory = data.scanValue(start: 48)
zip64ExtensibleDataSector = Data()
}
init(
record: ZipArchive.ZIP64EndOfCentralDirectoryRecord,
numberOfEntriesOnDisk: UInt64,
numberOfEntriesInCD: UInt64,
sizeOfCentralDirectory: UInt64,
offsetToStartOfCD: UInt64)
{
sizeOfZIP64EndOfCentralDirectoryRecord = record.sizeOfZIP64EndOfCentralDirectoryRecord
versionMadeBy = record.versionMadeBy
versionNeededToExtract = record.versionNeededToExtract
numberOfDisk = record.numberOfDisk
numberOfDiskStart = record.numberOfDiskStart
totalNumberOfEntriesOnDisk = numberOfEntriesOnDisk
totalNumberOfEntriesInCentralDirectory = numberOfEntriesInCD
self.sizeOfCentralDirectory = sizeOfCentralDirectory
offsetToStartOfCentralDirectory = offsetToStartOfCD
zip64ExtensibleDataSector = record.zip64ExtensibleDataSector
}
// MARK: Internal
var data: Data {
var zip64EOCDRecordSignature = zip64EOCDRecordSignature
var sizeOfZIP64EOCDRecord = sizeOfZIP64EndOfCentralDirectoryRecord
var versionMadeBy = versionMadeBy
var versionNeededToExtract = versionNeededToExtract
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCD = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var data = Data()
withUnsafePointer(to: &zip64EOCDRecordSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionMadeBy) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionNeededToExtract) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zip64ExtensibleDataSector)
return data
}
}
extension ZipArchive.ZIP64EndOfCentralDirectoryLocator {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == ZipArchive.ZIP64EndOfCentralDirectoryLocator.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDLocatorSignature else { return nil }
numberOfDiskWithZIP64EOCDRecordStart = data.scanValue(start: 4)
relativeOffsetOfZIP64EOCDRecord = data.scanValue(start: 8)
totalNumberOfDisk = data.scanValue(start: 16)
}
// MARK: Internal
var data: Data {
var zip64EOCDLocatorSignature = zip64EOCDLocatorSignature
var numberOfDiskWithZIP64EOCD = numberOfDiskWithZIP64EOCDRecordStart
var offsetOfZIP64EOCDRecord = relativeOffsetOfZIP64EOCDRecord
var totalNumberOfDisk = totalNumberOfDisk
var data = Data()
withUnsafePointer(to: &zip64EOCDLocatorSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskWithZIP64EOCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
return data
}
}
extension ZipArchive.EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == ZipArchive.EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == endOfCentralDirectorySignature else { return nil }
numberOfDisk = data.scanValue(start: 4)
numberOfDiskStart = data.scanValue(start: 6)
totalNumberOfEntriesOnDisk = data.scanValue(start: 8)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 10)
sizeOfCentralDirectory = data.scanValue(start: 12)
offsetToStartOfCentralDirectory = data.scanValue(start: 16)
zipFileCommentLength = data.scanValue(start: 20)
guard let commentData = try? provider(Int(zipFileCommentLength)) else { return nil }
guard commentData.count == Int(zipFileCommentLength) else { return nil }
zipFileCommentData = commentData
}
// MARK: Internal
var data: Data {
var endOfCDSignature = endOfCentralDirectorySignature
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCentralDirectory = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var zipFileCommentLength = zipFileCommentLength
var data = Data()
withUnsafePointer(to: &endOfCDSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCentralDirectory) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &zipFileCommentLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zipFileCommentData)
return data
}
}
| 39f23b7261d4b098feea5012a4134b18 | 42.683544 | 112 | 0.750797 | false | false | false | false |
khizkhiz/swift | refs/heads/master | test/SourceKit/CodeFormat/indent-basic.swift | apache-2.0 | 1 | class Foo {
var test : Int
func foo() {
test = 1
}
}
func foo(a a: [Int: Int]) {}
foo(a: [
3: 3
])
// RUN: %sourcekitd-test -req=format -line=1 -length=1 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=2 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=9 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=13 -length=1 %s >>%t.response
// RUN: FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: "class Foo {"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: " var test : Int"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: " func foo() {"
// CHECK: key.sourcetext: " test = 1"
// CHECK: key.sourcetext: " }"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: "}"
// "foo(a: ["
// CHECK: key.sourcetext: " 3: 3"
| 6aa7c37bef40c135364efee0c9722077 | 33.394737 | 72 | 0.601377 | false | true | false | false |
haibtdt/FileTransfer | refs/heads/master | FileTransfer/DownloadTaskTracker.swift | mit | 1 | //
// DownloadTaskTracker.swift
// FileTransfer
//
// Created by Bui Hai on 10/11/15.
// Copyright © 2015 Hai Bui. All rights reserved.
//
import UIKit
protocol DownloadTaskTrackerObserver : class {
func downloadTaskMetaDataChanged (task: DownloadTask, tracker : DownloadTaskTracker)
}
/// Maintain download task's status
class DownloadTaskTracker : DownloadTaskObserver {
var downloadTask : DownloadTask? = nil
var downloadTaskMetaData : DownloadTaskMetaData? = nil
weak var trackerObserver : DownloadTaskTrackerObserver? = nil
init(task: DownloadTask, meta : DownloadTaskMetaData) {
downloadTask = task
downloadTaskMetaData = meta
task.observer = self
}
func taskStarted(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.InProgress.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
func taskDone(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.Done.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
func taskFailed(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.Failed.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
}
| cd730020cd0e567ef95135d4b69ab815 | 23.813559 | 88 | 0.665984 | false | false | false | false |
appcodev/Let-Swift-Code | refs/heads/master | BeyondTheBasic-Swift/BeyondTheBasic-Swift/main.swift | apache-2.0 | 1 | //
// main.swift
// BeyondTheBasic-Swift
//
// Created by Chalermchon Samana on 6/6/14.
// Copyright (c) 2014 Onzondev Innovation Co., Ltd. All rights reserved.
//
import Foundation
println("Beyond the Basic")
var dic = ["A":"123","B":"122"]
let c:String? = dic["C"]
//let c = dic["C"]
//print(c)
//Unwrapping an Optional
if let cValue = c {
println(cValue)
}else{
println("c is nil")
}
let numberOfLegs = ["ant":6, "snake":0, "cheetah":4, "big":1]
//ถ้าเราดึงค่าของ key ที่ไม่มีอยู่ใน dictionary จะเกิดอะไรขึ้น?
println(numberOfLegs["dog"])
//output nil
//Querying an Optional
let possibleLegCount: Int? = numberOfLegs["dogg"]
println(possibleLegCount)
//output nil
if possibleLegCount == nil {
println("Not found")
}else {
let legCount: Int = possibleLegCount!
println(legCount)
}
/////// ? และ ! คืออะไร ใช้อย่างไร
//ลดการเขียนโค้ดจากด้านบน
if possibleLegCount {
let legCount = possibleLegCount!
println(legCount)
}
//Unwrapping an Optional
if let legCount = possibleLegCount {
println(legCount)
}
//IF Statement
var legCount = numberOfLegs["big"]
if legCount == 0 { //จะใช้แบบ if(legCount==0) ก็ได้
println("It slithers and slides around")
}else {
println("It walks")
}
//It walks
//More Complex If Statements
if legCount == 0 { //จะใช้แบบ if(legCount==0) ก็ได้
println("It slithers and slides around")
}else if legCount == 1 {
println("It hops")
}else {
println("It walks")
}
//It hops
//if-statement enum
enum Day {
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
let myDay = Day.Monday
let yourDay = Day.Monday
if myDay == yourDay {
println("Same")
}else {
println("Difference")
}
let myName = "Swift"
if myName == "Swift" {
println("Equal")
}else{
println("Not Equal")
}
//Equal
//Switch
switch legCount! {
case 0:
println("It slither and slides around")
case "1":
println("It hop 1")
println("It hop 2")
println("It hop 3")
println("It hop 4")
case 1:
println("It hop 1 number")
println("It hop 2 number")
println("It hop 3 number")
default:
println("It walks")
}
/*
It hop 1 number
It hop 2 number
It hop 3 number
*/
//switch ต้องมี default ตลอดไม่ยังนั้นจะคอมไพล์ไม่ผ่าน error: switch muct be exhaustive [safe]
//switch สามารถเปรียบเทียบตัวแปรที่เป็น Object Class ก็ได้
//switch ใช้ กับจำนวนหรือ Object หลายๆ อันได้
var letter = "5K"
switch letter {
case "1","0",0:
println("member in 1 0 0")
case "5","5K",5:
println("member in 5 5K 5")
default:
println("not member")
}
//member in 5 5K 5
let myDay2 = Day.Friday
switch myDay2 {
case Day.Monday:
println("On Monday")
case Day.Tuesday:
println("On Tuesday")
case Day.Wednesday:
println("On Wednesday")
case Day.Thursday:
println("On Thursday")
case Day.Friday:
println("On Friday")
case Day.Saturday:
println("On Saturday")
case Day.Sunday:
println("On Sunday")
// default:
// println("On otherday")
}
println(myDay2)
//On Friday
//Matching Value Range
let myScore = 80
switch myScore {
case 80...100:
println("get A")
case 70..80:
println("get B")
case 60..70:
println("get C")
case 50..60:
println("get D")
default:
println("get E")
}
//49.0001 => get D
//49.0 => get E
//** การอัพเดทของ Range อัพเดทเป็นตัวเลขจำนวนเต็ม เท่านั้น
//Function
func sayHello(){
println("Hello")
}
//call
sayHello()
//Hello
func sayHello(name:String){
println("Hello \(name)")
}
sayHello("Let Swift")
//Hello Let Swift
//Returning Values
func buildGreeting(name:String = "Let Swift") -> String {
return "Hi! " + name
}
let greeting = buildGreeting()
let greet:String = buildGreeting(name:"Toa")//เวลาจะใส่พารามิเตอร์ ต้องใส่ชื่ออากูเมนลงไปด้วย
println("\(greeting) | \(greet)")
//Hi! Let Swift | Hi! Toa
//Tuples
//Tuples นี้สามารถเอามาเป็นค่าที่จะ return ออกไปได้ จะทำให้เราสามารถ return ออกไปได้หลายค่านั้นเอง
/*
(3.4,3.5,4.3) //(Double, Double, Double)
(404,"Not Found") //(Int, String)
(2,"banana",0.99) //(Int, String, Double)
*/
//Returning Multiple Values
func refreshWebPage() -> (code:Int, message:String) {
//...
return (404,"Not Found")
}
//Decomposition a Tuples
//var (code,desc) = refreshWebPage()
var (code:Int,desc:String) = refreshWebPage()
println("-- \(code) \(desc)")
//-- 404 Not Found
//ประกาศตัวแปรมารับค่า ค่าที่ return จาก tuples จะต้องใส่ชื่อในตัวแปรด้วยจะได้เรียกใช้ผ่านชื่อนั้นได้
let status = refreshWebPage()
println("received \(status.code) \(status.message)")
//received 404 Not Found
//Tuple Decomposition for Enumeration
let numbers = ["A":5, "B":19, "C":90]
for (alphabet,number) in numbers {
println("\(alphabet) ->> \(number)")
}
/*
output
C ->> 90
A ->> 5
B ->> 19
*/
//Closures
let greetingPrinter = {
println("Let Swift!")
}
//Closures จะคล้ายกับการประกาศฟังก์ชั่น ดังนั้นเวลาเรียกใช้จึงเรียกเหมือนฟังก์ชั่น ไม่ใช่เรียกเป็นตัวแปร
/*
let greetingPrinter: ()->() = {
}
same
func greetingPrinter() -> (){
}
*/
greetingPrinter()
//Let Swift!
//Closures as Parameters
//การส่งค่า Closures ไปเป็นพารามิเตอร์ของฟังก์ชั่น
func repeat(count: Int, task: ()->()) {
for i in 0..count {
task()
}
}
repeat(4,{
println("Hello!!")
});
/*
Hello!!
Hello!!
Hello!!
Hello!!
*/
//Closure ใช้ประโยชน์อย่างไรบ้าง Closure มีพารามิเตอร์ได้มั้ย มีรูปแบบอย่างไรหากมีพารามิเตอร์ ใช้งานอย่างไร
| 94cff56fdc0f17537b484fa224d6a4d1 | 18.64539 | 107 | 0.626715 | false | false | false | false |
kperryua/swift | refs/heads/master | test/IDE/complete_value_expr.swift | apache-2.0 | 3 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_3 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_4 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_5 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_1 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_2 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_3 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_4 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF1 | %FileCheck %s -check-prefix=VF1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF2 | %FileCheck %s -check-prefix=VF2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS | %FileCheck %s -check-prefix=BASE_MEMBERS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS_STATIC | %FileCheck %s -check-prefix=BASE_MEMBERS_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_4 | %FileCheck %s -check-prefix=PROTO_MEMBERS_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_0 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_4 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_5 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_6 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_7 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_8 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_8
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_9 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_9
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_10 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_10
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_11
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_12
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_OVERLOADED_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_OVERLOADED_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_4 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_5 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_6 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_2 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_1 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_2 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_3 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_1 | %FileCheck %s -check-prefix=CHAINED_CALLS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_2 | %FileCheck %s -check-prefix=CHAINED_CALLS_2
// Disabled because we aren't handling failures well.
// FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_3 | %FileCheck %s -check-prefix=CHAINED_CALLS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_ERROR_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_ERROR_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_1 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_2 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_3 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_4 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_MODULES_1 | %FileCheck %s -check-prefix=RESOLVE_MODULES_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INTERPOLATED_STRING_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_WILLCONFORMP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_WILLCONFORMP1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_T_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_T_DOT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL | %FileCheck %s -check-prefix=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS1 | %FileCheck %s -check-prefix=THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS2 | %FileCheck %s -check-prefix=THROWS2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS1 | %FileCheck %s -check-prefix=MEMBER_THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS2 | %FileCheck %s -check-prefix=MEMBER_THROWS2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS3 | %FileCheck %s -check-prefix=MEMBER_THROWS3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_THROWS1 | %FileCheck %s -check-prefix=INIT_THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE1 > %t.autoclosure1
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE2 > %t.autoclosure2
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE3 > %t.autoclosure3
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE4 > %t.autoclosure4
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE5 > %t.autoclosure5
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DEPRECATED_1 | %FileCheck %s -check-prefix=DEPRECATED_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_1 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_2 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_2
// Test code completion of expressions that produce a value.
struct FooStruct {
lazy var lazyInstanceVar = 0
var instanceVar = 0
mutating
func instanceFunc0() {}
mutating
func instanceFunc1(_ a: Int) {}
mutating
func instanceFunc2(_ a: Int, b: inout Double) {}
mutating
func instanceFunc3(_ a: Int, _: (Float, Double)) {}
mutating
func instanceFunc4(_ a: Int?, b: Int!, c: inout Int?, d: inout Int!) {}
mutating
func instanceFunc5() -> Int? {}
mutating
func instanceFunc6() -> Int! {}
mutating
func instanceFunc7(a a: Int) {}
mutating
func instanceFunc8(_ a: (Int, Int)) {}
mutating
func instanceFunc9(@autoclosure a: () -> Int) {}
mutating
func varargInstanceFunc0(_ v: Int...) {}
mutating
func varargInstanceFunc1(_ a: Float, v: Int...) {}
mutating
func varargInstanceFunc2(_ a: Float, b: Double, v: Int...) {}
mutating
func overloadedInstanceFunc1() -> Int {}
mutating
func overloadedInstanceFunc1() -> Double {}
mutating
func overloadedInstanceFunc2(_ x: Int) -> Int {}
mutating
func overloadedInstanceFunc2(_ x: Double) -> Int {}
mutating
func builderFunc1(_ a: Int) -> FooStruct { return self }
subscript(i: Int) -> Double {
get {
return Double(i)
}
set(v) {
instanceVar = i
}
}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
set(v) {
instanceVar = i + j
}
}
mutating
func selectorVoidFunc1(_ a: Int, b x: Float) {}
mutating
func selectorVoidFunc2(_ a: Int, b x: Float, c y: Double) {}
mutating
func selectorVoidFunc3(_ a: Int, b _: (Float, Double)) {}
mutating
func selectorStringFunc1(_ a: Int, b x: Float) -> String {}
mutating
func selectorStringFunc2(_ a: Int, b x: Float, c y: Double) -> String {}
mutating
func selectorStringFunc3(_ a: Int, b _: (Float, Double)) -> String{}
struct NestedStruct {}
class NestedClass {}
enum NestedEnum {}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
static var staticVar: Int = 4
static func staticFunc0() {}
static func staticFunc1(_ a: Int) {}
static func overloadedStaticFunc1() -> Int {}
static func overloadedStaticFunc1() -> Double {}
static func overloadedStaticFunc2(_ x: Int) -> Int {}
static func overloadedStaticFunc2(_ x: Double) -> Int {}
}
extension FooStruct {
var extProp: Int {
get {
return 42
}
set(v) {}
}
mutating
func extFunc0() {}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
static func extStaticFunc0() {}
struct ExtNestedStruct {}
class ExtNestedClass {}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
typealias ExtNestedTypealias = Int
}
var fooObject: FooStruct
// FOO_OBJECT_DOT: Begin completions
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Double#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: extProp[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: End completions
// FOO_OBJECT_NO_DOT: Begin completions
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6()[#Int!#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}, {#Int#}][#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .extProp[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: BuiltinOperator/None: = {#Foo
// FOO_OBJECT_NO_DOT-NEXT: End completions
// FOO_STRUCT_DOT: Begin completions
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: NestedClass[#FooStruct.NestedClass#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Double#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]; name=init(lazyInstanceVar: Int?, instanceVar: Int){{$}}
// FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init()[#FooStruct#]; name=init(){{$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: extStaticProp[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: extStaticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: ExtNestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: End completions
// FOO_STRUCT_NO_DOT: Begin completions
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .NestedClass[#FooStruct.NestedClass#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .NestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Double#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .extStaticProp[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .extStaticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .ExtNestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: End completions
func testObjectExpr() {
fooObject.#^FOO_OBJECT_DOT_1^#
}
func testDotDotTokenSplitWithCodeCompletion() {
fooObject.#^FOO_OBJECT_DOT_2^#.bar
}
func testObjectExprBuilderStyle1() {
fooObject
.#^FOO_OBJECT_DOT_3^#
}
func testObjectExprBuilderStyle2() {
fooObject
.builderFunc1(42).#^FOO_OBJECT_DOT_4^#
}
func testObjectExprBuilderStyle3() {
fooObject
.builderFunc1(42)
.#^FOO_OBJECT_DOT_5^#
}
func testObjectExprWithoutDot() {
fooObject#^FOO_OBJECT_NO_DOT_1^#
}
func testObjectExprWithoutSpaceAfterCodeCompletion() {
fooObject#^FOO_OBJECT_NO_DOT_2^#.bar
}
func testMetatypeExpr() {
FooStruct.#^FOO_STRUCT_DOT_1^#
}
func testMetatypeExprWithoutDot() {
FooStruct#^FOO_STRUCT_NO_DOT_1^#
}
func testImplicitlyCurriedFunc(_ fs: inout FooStruct) {
FooStruct.instanceFunc0(&fs)#^IMPLICITLY_CURRIED_FUNC_0^#
// IMPLICITLY_CURRIED_FUNC_0: Begin completions
// IMPLICITLY_CURRIED_FUNC_0-NEXT: Pattern/ExprSpecific: ()[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_0-NEXT: End completions
FooStruct.instanceFunc1(&fs)#^IMPLICITLY_CURRIED_FUNC_1^#
// IMPLICITLY_CURRIED_FUNC_1: Begin completions
// IMPLICITLY_CURRIED_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Int#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_1-NEXT: End completions
FooStruct.instanceFunc2(&fs)#^IMPLICITLY_CURRIED_FUNC_2^#
// IMPLICITLY_CURRIED_FUNC_2: Begin completions
// IMPLICITLY_CURRIED_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_2-NEXT: End completions
FooStruct.varargInstanceFunc0(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_0^#
// IMPLICITLY_CURRIED_VARARG_FUNC_0: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: Pattern/ExprSpecific: ({#(v): Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: End completions
FooStruct.varargInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_1^#
// IMPLICITLY_CURRIED_VARARG_FUNC_1: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: End completions
FooStruct.varargInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_2^#
// IMPLICITLY_CURRIED_VARARG_FUNC_2: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: End completions
// This call is ambiguous, and the expression is invalid.
// Ensure that we don't suggest to call the result.
FooStruct.overloadedInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_1^#
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_1: found code completion token
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_1-NOT: Begin completions
// This call is ambiguous, and the expression is invalid.
// Ensure that we don't suggest to call the result.
FooStruct.overloadedInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_2^#
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_2: found code completion token
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_2-NOT: Begin completions
}
//===---
//===--- Test that we can complete inside 'case'.
//===---
func testSwitch1() {
switch fooObject {
case #^IN_SWITCH_CASE_1^#
}
switch fooObject {
case 1, #^IN_SWITCH_CASE_2^#
}
switch unknown_var {
case #^IN_SWITCH_CASE_3^#
}
switch {
case #^IN_SWITCH_CASE_4^#
}
}
// IN_SWITCH_CASE: Begin completions
// IN_SWITCH_CASE-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// IN_SWITCH_CASE-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// IN_SWITCH_CASE: End completions
//===--- Helper types that are used in this test
struct FooGenericStruct<T> {
init(t: T) { fooInstanceVarT = t }
var fooInstanceVarT: T
var fooInstanceVarTBrackets: [T]
mutating
func fooVoidInstanceFunc1(_ a: T) {}
mutating
func fooTInstanceFunc1(_ a: T) -> T { return a }
mutating
func fooUInstanceFunc1<U>(_ a: U) -> U { return a }
static var fooStaticVarT: Int = 0
static var fooStaticVarTBrackets: [Int] = [0]
static func fooVoidStaticFunc1(_ a: T) {}
static func fooTStaticFunc1(_ a: T) -> T { return a }
static func fooUInstanceFunc1<U>(_ a: U) -> U { return a }
}
class FooClass {
var fooClassInstanceVar = 0
func fooClassInstanceFunc0() {}
func fooClassInstanceFunc1(_ a: Int) {}
}
enum FooEnum {
}
protocol FooProtocol {
var fooInstanceVar1: Int { get set }
var fooInstanceVar2: Int { get }
typealias FooTypeAlias1
func fooInstanceFunc0() -> Double
func fooInstanceFunc1(_ a: Int) -> Double
subscript(i: Int) -> Double { get set }
}
class FooProtocolImpl : FooProtocol {
var fooInstanceVar1 = 0
val fooInstanceVar2 = 0
typealias FooTypeAlias1 = Float
init() {}
func fooInstanceFunc0() -> Double {
return 0.0
}
func fooInstanceFunc1(_ a: Int) -> Double {
return Double(a)
}
subscript(i: Int) -> Double {
return 0.0
}
}
protocol FooExProtocol : FooProtocol {
func fooExInstanceFunc0() -> Double
}
protocol BarProtocol {
var barInstanceVar: Int { get set }
typealias BarTypeAlias1
func barInstanceFunc0() -> Double
func barInstanceFunc1(_ a: Int) -> Double
}
protocol BarExProtocol : BarProtocol {
func barExInstanceFunc0() -> Double
}
protocol BazProtocol {
func bazInstanceFunc0() -> Double
}
typealias BarBazProtocolComposition = BarProtocol & BazProtocol
let fooProtocolInstance: FooProtocol = FooProtocolImpl()
let fooBarProtocolInstance: FooProtocol & BarProtocol
let fooExBarExProtocolInstance: FooExProtocol & BarExProtocol
typealias FooTypealias = Int
//===--- Test that we can code complete inside function calls.
func testInsideFunctionCall0() {
ERROR(#^INSIDE_FUNCTION_CALL_0^#
// INSIDE_FUNCTION_CALL_0: Begin completions
// INSIDE_FUNCTION_CALL_0-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_0: End completions
}
func testInsideFunctionCall1() {
var a = FooStruct()
a.instanceFunc0(#^INSIDE_FUNCTION_CALL_1^#
// There should be no other results here because the function call
// unambiguously resolves to overload that takes 0 arguments.
// INSIDE_FUNCTION_CALL_1: Begin completions
// INSIDE_FUNCTION_CALL_1-NEXT: Pattern/ExprSpecific: ['('])[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_1-NEXT: End completions
}
func testInsideFunctionCall2() {
var a = FooStruct()
a.instanceFunc1(#^INSIDE_FUNCTION_CALL_2^#
// INSIDE_FUNCTION_CALL_2: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_2-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_2: End completions
}
func testInsideFunctionCall3() {
FooStruct().instanceFunc1(42, #^INSIDE_FUNCTION_CALL_3^#
// INSIDE_FUNCTION_CALL_3: Begin completions
// FIXME: There should be no results here because the function call
// unambiguously resolves to overload that takes 1 argument.
// INSIDE_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_3: End completions
}
func testInsideFunctionCall4() {
var a = FooStruct()
a.instanceFunc2(#^INSIDE_FUNCTION_CALL_4^#
// INSIDE_FUNCTION_CALL_4: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_4-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_4-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_4: End completions
}
func testInsideFunctionCall5() {
FooStruct().instanceFunc2(42, #^INSIDE_FUNCTION_CALL_5^#
// INSIDE_FUNCTION_CALL_5: Begin completions
// INSIDE_FUNCTION_CALL_5-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_5: End completions
}
func testInsideFunctionCall6() {
var a = FooStruct()
a.instanceFunc7(#^INSIDE_FUNCTION_CALL_6^#
// INSIDE_FUNCTION_CALL_6: Begin completions
// INSIDE_FUNCTION_CALL_6-NEXT: Pattern/ExprSpecific: ['(']{#a: Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_6-NEXT: End completions
}
func testInsideFunctionCall7() {
var a = FooStruct()
a.instanceFunc8(#^INSIDE_FUNCTION_CALL_7^#
// INSIDE_FUNCTION_CALL_7: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_7: Pattern/ExprSpecific: ['(']{#(Int, Int)#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_7: End completions
}
func testInsideFunctionCall8(_ x: inout FooStruct) {
x.instanceFunc0(#^INSIDE_FUNCTION_CALL_8^#)
// Since we already have '()', there is no pattern to complete.
// INSIDE_FUNCTION_CALL_8-NOT: Pattern/{{.*}}:
}
func testInsideFunctionCall9(_ x: inout FooStruct) {
x.instanceFunc1(#^INSIDE_FUNCTION_CALL_9^#)
// Annotated ')'
// INSIDE_FUNCTION_CALL_9: Begin completions
// INSIDE_FUNCTION_CALL_9-DAG: Pattern/ExprSpecific: ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_9-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_9: End completions
}
func testInsideFunctionCall10(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_10^#)
// Annotated ')'
// INSIDE_FUNCTION_CALL_10: Begin completions
// INSIDE_FUNCTION_CALL_10-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_10-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_10: End completions
}
func testInsideFunctionCall11(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_11^#,
// INSIDE_FUNCTION_CALL_11-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#}
}
func testInsideFunctionCall12(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_12^#<#placeholder#>
// INSIDE_FUNCTION_CALL_12-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#}
}
func testInsideVarargFunctionCall1() {
var a = FooStruct()
a.varargInstanceFunc0(#^INSIDE_VARARG_FUNCTION_CALL_1^#
// INSIDE_VARARG_FUNCTION_CALL_1: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Pattern/ExprSpecific: ['(']{#Int...#})[#Void#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_1: End completions
}
func testInsideVarargFunctionCall2() {
FooStruct().varargInstanceFunc0(42, #^INSIDE_VARARG_FUNCTION_CALL_2^#
// INSIDE_VARARG_FUNCTION_CALL_2: Begin completions
// INSIDE_VARARG_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_2: End completions
}
func testInsideVarargFunctionCall3() {
FooStruct().varargInstanceFunc0(42, 4242, #^INSIDE_VARARG_FUNCTION_CALL_3^#
// INSIDE_VARARG_FUNCTION_CALL_3: Begin completions
// INSIDE_VARARG_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_3: End completions
}
func testInsideOverloadedFunctionCall1() {
var a = FooStruct()
a.overloadedInstanceFunc2(#^INSIDE_OVERLOADED_FUNCTION_CALL_1^#
// INSIDE_OVERLOADED_FUNCTION_CALL_1: Begin completions
// FIXME: produce call patterns here.
// INSIDE_OVERLOADED_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_OVERLOADED_FUNCTION_CALL_1: End completions
}
func testInsideFunctionCallOnClassInstance1(_ a: FooClass) {
a.fooClassInstanceFunc1(#^INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1^#
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: End completions
}
//===--- Variables that have function types.
class FuncTypeVars {
var funcVar1: () -> Double
var funcVar2: (a: Int) -> Double // adding the label is erroneous.
}
var funcTypeVarsObject: FuncTypeVars
func testFuncTypeVars() {
funcTypeVarsObject.funcVar1#^VF1^#
// VF1: Begin completions
// VF1-NEXT: Pattern/ExprSpecific: ()[#Double#]{{; name=.+$}}
// VF1-NEXT: BuiltinOperator/None: = {#() -> Double##() -> Double#}[#Void#]
// VF1-NEXT: End completions
funcTypeVarsObject.funcVar2#^VF2^#
// VF2: Begin completions
// VF2-NEXT: Pattern/ExprSpecific: ({#Int#})[#Double#]{{; name=.+$}}
// VF2-NEXT: BuiltinOperator/None: = {#(Int) -> Double##(Int) -> Double#}[#Void#]
// VF2-NEXT: End completions
}
//===--- Check that we look into base classes.
class MembersBase {
var baseVar = 0
func baseInstanceFunc() {}
class func baseStaticFunc() {}
}
class MembersDerived : MembersBase {
var derivedVar = 0
func derivedInstanceFunc() {}
class func derivedStaticFunc() {}
}
var membersDerived: MembersDerived
func testLookInBase() {
membersDerived.#^BASE_MEMBERS^#
// BASE_MEMBERS: Begin completions
// BASE_MEMBERS-NEXT: Decl[InstanceVar]/CurrNominal: derivedVar[#Int#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceVar]/Super: baseVar[#Int#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: End completions
}
func testLookInBaseStatic() {
MembersDerived.#^BASE_MEMBERS_STATIC^#
// BASE_MEMBERS_STATIC: Begin completions
// BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc({#self: MembersDerived#})[#() -> Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: derivedStaticFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[Constructor]/CurrNominal: init()[#MembersDerived#]; name=init(){{$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc({#self: MembersBase#})[#() -> Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/Super: baseStaticFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: End completions
}
//===--- Check that we can look into protocols.
func testLookInProtoNoDot1() {
fooProtocolInstance#^PROTO_MEMBERS_NO_DOT_1^#
// PROTO_MEMBERS_NO_DOT_1: Begin completions
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: End completions
}
func testLookInProtoNoDot2() {
fooBarProtocolInstance#^PROTO_MEMBERS_NO_DOT_2^#
// PROTO_MEMBERS_NO_DOT_2: Begin completions
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: End completions
}
func testLookInProtoNoDot3() {
fooExBarExProtocolInstance#^PROTO_MEMBERS_NO_DOT_3^#
// PROTO_MEMBERS_NO_DOT_3: Begin completions
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .barExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[Subscript]/Super: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: End completions
}
func testLookInProto1() {
fooProtocolInstance.#^PROTO_MEMBERS_1^#
// PROTO_MEMBERS_1: Begin completions
// PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: End completions
}
func testLookInProto2() {
fooBarProtocolInstance.#^PROTO_MEMBERS_2^#
// PROTO_MEMBERS_2: Begin completions
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: End completions
}
func testLookInProto3() {
fooExBarExProtocolInstance.#^PROTO_MEMBERS_3^#
// PROTO_MEMBERS_3: Begin completions
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: barExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: End completions
}
func testLookInProto4(_ a: FooProtocol & BarBazProtocolComposition) {
a.#^PROTO_MEMBERS_4^#
// PROTO_MEMBERS_4: Begin completions
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: bazInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4: End completions
}
//===--- Check that we can resolve function parameters.
func testResolveFuncParam1(_ fs: FooStruct) {
fs.#^RESOLVE_FUNC_PARAM_1^#
}
class TestResolveFuncParam2 {
func testResolveFuncParam2a(_ fs: FooStruct) {
fs.#^RESOLVE_FUNC_PARAM_2^#
}
}
func testResolveFuncParam3<Foo : FooProtocol>(_ foo: Foo) {
foo.#^RESOLVE_FUNC_PARAM_3^#
// RESOLVE_FUNC_PARAM_3: Begin completions
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: End completions
}
func testResolveFuncParam4<FooBar : FooProtocol & BarProtocol>(_ fooBar: FooBar) {
fooBar.#^RESOLVE_FUNC_PARAM_4^#
// RESOLVE_FUNC_PARAM_4: Begin completions
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: End completions
}
func testResolveFuncParam5<FooExBarEx : FooExProtocol & BarExProtocol>(_ a: FooExBarEx) {
a.#^RESOLVE_FUNC_PARAM_5^#
// RESOLVE_FUNC_PARAM_5: Begin completions
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barExInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: End completions
}
func testResolveFuncParam6<Foo : FooProtocol where Foo : FooClass>(_ foo: Foo) {
foo.#^RESOLVE_FUNC_PARAM_6^#
// RESOLVE_FUNC_PARAM_6: Begin completions
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooClassInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc0()[#Void#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: End completions
}
class TestResolveConstructorParam1 {
init(fs: FooStruct) {
fs.#^RESOLVE_CONSTRUCTOR_PARAM_1^#
}
}
class TestResolveConstructorParam2 {
init<Foo : FooProtocol>(foo: Foo) {
foo.#^RESOLVE_CONSTRUCTOR_PARAM_2^#
// RESOLVE_CONSTRUCTOR_PARAM_2: Begin completions
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: End completions
}
}
class TestResolveConstructorParam3<Foo : FooProtocol> {
init(foo: Foo) {
foo.#^RESOLVE_CONSTRUCTOR_PARAM_3^#
// RESOLVE_CONSTRUCTOR_PARAM_3: Begin completions
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: End completions
}
}
//===--- Check that we can handle ParenPattern in function arguments.
struct FuncParenPattern {
init(_: Int) {}
init(_: (Int, Int)) {}
mutating
func instanceFunc(_: Int) {}
subscript(_: Int) -> Int {
get {
return 0
}
}
}
func testFuncParenPattern1(_ fpp: FuncParenPattern) {
fpp#^FUNC_PAREN_PATTERN_1^#
// FUNC_PAREN_PATTERN_1: Begin completions
// FUNC_PAREN_PATTERN_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#Int#})[#Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_1-NEXT: End completions
}
func testFuncParenPattern2(_ fpp: FuncParenPattern) {
FuncParenPattern#^FUNC_PAREN_PATTERN_2^#
// FUNC_PAREN_PATTERN_2: Begin completions
// FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#Int#})[#FuncParenPattern#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#(Int, Int)#})[#FuncParenPattern#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: &FuncParenPattern#})[#(Int) -> Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: End completions
}
func testFuncParenPattern3(_ fpp: inout FuncParenPattern) {
fpp.instanceFunc#^FUNC_PAREN_PATTERN_3^#
// FUNC_PAREN_PATTERN_3: Begin completions
// FUNC_PAREN_PATTERN_3-NEXT: Pattern/ExprSpecific: ({#Int#})[#Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_3-NEXT: End completions
}
//===--- Check that we can code complete after function calls
struct SomeBuilder {
init(a: Int) {}
func doFoo() -> SomeBuilder { return self }
func doBar() -> SomeBuilder { return self }
func doBaz(_ z: Double) -> SomeBuilder { return self }
}
func testChainedCalls1() {
SomeBuilder(42)#^CHAINED_CALLS_1^#
// CHAINED_CALLS_1: Begin completions
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1: End completions
}
func testChainedCalls2() {
SomeBuilder(42).doFoo()#^CHAINED_CALLS_2^#
// CHAINED_CALLS_2: Begin completions
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2: End completions
}
func testChainedCalls3() {
// doBaz() takes a Double. Check that we can recover.
SomeBuilder(42).doFoo().doBaz(SomeBuilder(24))#^CHAINED_CALLS_3^#
// CHAINED_CALLS_3: Begin completions
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#z: Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3: End completions
}
//===--- Check that we can code complete expressions that have generic parameters
func testResolveGenericParams1() {
FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_1^#
// RESOLVE_GENERIC_PARAMS_1: Begin completions
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: End completions
FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_1_STATIC^#
// RESOLVE_GENERIC_PARAMS_1_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: End completions
}
func testResolveGenericParams2<Foo : FooProtocol>(_ foo: Foo) {
FooGenericStruct<Foo>()#^RESOLVE_GENERIC_PARAMS_2^#
// RESOLVE_GENERIC_PARAMS_2: Begin completions
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooProtocol]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: End completions
FooGenericStruct<Foo>#^RESOLVE_GENERIC_PARAMS_2_STATIC^#
// RESOLVE_GENERIC_PARAMS_2_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooProtocol#})[#FooGenericStruct<FooProtocol>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: End completions
}
struct TestResolveGenericParams3_4<T> {
func testResolveGenericParams3() {
FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_3^#
// RESOLVE_GENERIC_PARAMS_3: Begin completions
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: End completions
FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_3_STATIC^#
// RESOLVE_GENERIC_PARAMS_3_STATIC: Begin completions, 9 items
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#FooStruct -> FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: End completions
}
func testResolveGenericParams4(_ t: T) {
FooGenericStruct<T>(t)#^RESOLVE_GENERIC_PARAMS_4^#
// RESOLVE_GENERIC_PARAMS_4: Begin completions
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[T]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): T#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): T#})[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: End completions
FooGenericStruct<T>#^RESOLVE_GENERIC_PARAMS_4_STATIC^#
// RESOLVE_GENERIC_PARAMS_4_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: T#})[#FooGenericStruct<T>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<T>#})[#T -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<T>#})[#T -> T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<T>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): T#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): T#})[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: End completions
}
func testResolveGenericParams5<U>(_ u: U) {
FooGenericStruct<U>(u)#^RESOLVE_GENERIC_PARAMS_5^#
// RESOLVE_GENERIC_PARAMS_5: Begin completions
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[U]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): U#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: End completions
FooGenericStruct<U>#^RESOLVE_GENERIC_PARAMS_5_STATIC^#
// RESOLVE_GENERIC_PARAMS_5_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: U#})[#FooGenericStruct<U>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<U>#})[#U -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<U>#})[#U -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<U>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): U#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: End completions
}
}
func testResolveGenericParamsError1() {
// There is no type 'Foo'. Check that we don't crash.
// FIXME: we could also display correct completion results here, because
// swift does not have specialization, and the set of completion results does
// not depend on the generic type argument.
FooGenericStruct<NotDefinedType>()#^RESOLVE_GENERIC_PARAMS_ERROR_1^#
// RESOLVE_GENERIC_PARAMS_ERROR_1: found code completion token
// RESOLVE_GENERIC_PARAMS_ERROR_1-NOT: Begin completions
}
//===--- Check that we can code complete expressions that have unsolved type variables.
class BuilderStyle<T> {
var count = 0
func addString(_ s: String) -> BuilderStyle<T> {
count += 1
return self
}
func add(_ t: T) -> BuilderStyle<T> {
count += 1
return self
}
func get() -> Int {
return count
}
}
func testTypeCheckWithUnsolvedVariables1() {
BuilderStyle().#^TC_UNSOLVED_VARIABLES_1^#
}
// TC_UNSOLVED_VARIABLES_1: Begin completions
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: End completions
func testTypeCheckWithUnsolvedVariables2() {
BuilderStyle().addString("abc").#^TC_UNSOLVED_VARIABLES_2^#
}
// TC_UNSOLVED_VARIABLES_2: Begin completions
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: End completions
func testTypeCheckWithUnsolvedVariables3() {
BuilderStyle().addString("abc").add(42).#^TC_UNSOLVED_VARIABLES_3^#
}
// TC_UNSOLVED_VARIABLES_3: Begin completions
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<Int>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): Int#})[#BuilderStyle<Int>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: End completions
func testTypeCheckNil() {
nil#^TC_UNSOLVED_VARIABLES_4^#
}
// TC_UNSOLVED_VARIABLES_4-NOT: Decl{{.*}}: .{{[a-zA-Z]}}
//===--- Check that we can look up into modules
func testResolveModules1() {
Swift#^RESOLVE_MODULES_1^#
// RESOLVE_MODULES_1: Begin completions
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int8[#Int8#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int16[#Int16#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int32[#Int32#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int64[#Int64#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Bool[#Bool#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[TypeAlias]/OtherModule[Swift]: .Float32[#Float#]{{; name=.+$}}
// RESOLVE_MODULES_1: End completions
}
//===--- Check that we can complete inside interpolated string literals
func testInterpolatedString1() {
"\(fooObject.#^INTERPOLATED_STRING_1^#)"
}
// FOO_OBJECT_DOT1: Begin completions
// FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}}
//===--- Check protocol extensions
struct WillConformP1 {
}
protocol P1 {
func reqP1()
}
protocol P2 : P1 {
func reqP2()
}
protocol P3 : P1, P2 {
}
extension P1 {
final func extP1() {}
}
extension P2 {
final func extP2() {}
}
extension P3 {
final func reqP1() {}
final func reqP2() {}
final func extP3() {}
}
extension WillConformP1 : P1 {
func reqP1() {}
}
struct DidConformP2 : P2 {
func reqP1() {}
func reqP2() {}
}
struct DidConformP3 : P3 {
}
func testProtocol1(_ x: P1) {
x.#^PROTOCOL_EXT_P1^#
}
// PROTOCOL_EXT_P1: Begin completions
// PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P1: End completions
func testProtocol2(_ x: P2) {
x.#^PROTOCOL_EXT_P2^#
}
// PROTOCOL_EXT_P2: Begin completions
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2: End completions
func testProtocol3(_ x: P3) {
x.#^PROTOCOL_EXT_P3^#
}
// PROTOCOL_EXT_P3: Begin completions
// FIXME: the next two should both be "CurrentNominal"
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/CurrNominal: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3: End completions
func testConformingConcrete1(_ x: WillConformP1) {
x.#^PROTOCOL_EXT_WILLCONFORMP1^#
}
// PROTOCOL_EXT_WILLCONFORMP1: Begin completions
// PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_WILLCONFORMP1: End completions
func testConformingConcrete2(_ x: DidConformP2) {
x.#^PROTOCOL_EXT_DIDCONFORMP2^#
}
// PROTOCOL_EXT_DIDCONFORMP2: Begin completions
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2: End completions
func testConformingConcrete3(_ x: DidConformP3) {
x.#^PROTOCOL_EXT_DIDCONFORMP3^#
}
// PROTOCOL_EXT_DIDCONFORMP3: Begin completions
// FIXME: the next two should both be "CurrentNominal"
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3: End completions
func testGenericConforming1<T: P1>(x: T) {
x.#^PROTOCOL_EXT_GENERICP1^#
}
// PROTOCOL_EXT_GENERICP1: Begin completions
// PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP1: End completions
func testGenericConforming2<T: P2>(x: T) {
x.#^PROTOCOL_EXT_GENERICP2^#
}
// PROTOCOL_EXT_GENERICP2: Begin completions
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2: End completions
func testGenericConforming3<T: P3>(x: T) {
x.#^PROTOCOL_EXT_GENERICP3^#
}
// PROTOCOL_EXT_GENERICP3: Begin completions
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3: End completions
struct OnlyMe {}
protocol P4 {
associatedtype T
}
extension P4 where Self.T : P1 {
final func extP4WhenP1() {}
final var x: Int { return 1 }
init() {}
}
extension P4 where Self.T : P1 {
init(x: Int) {}
}
extension P4 where Self.T == OnlyMe {
final func extP4OnlyMe() {}
final subscript(x: Int) -> Int { return 2 }
}
struct Concrete1 : P4 {
typealias T = WillConformP1
}
struct Generic1<S: P1> : P4 {
typealias T = S
}
struct Concrete2 : P4 {
typealias T = OnlyMe
}
struct Generic2<S> : P4 {
typealias T = S
}
func testConstrainedP4(_ x: P4) {
x.#^PROTOCOL_EXT_P4^#
}
// PROTOCOL_EXT_P4-NOT: extP4
func testConstrainedConcrete1(_ x: Concrete1) {
x.#^PROTOCOL_EXT_CONCRETE1^#
}
func testConstrainedConcrete2(_ x: Generic1<WillConformP1>) {
x.#^PROTOCOL_EXT_CONCRETE2^#
}
func testConstrainedGeneric1<S: P1>(x: Generic1<S>) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_1^#
}
func testConstrainedGeneric2<S: P4 where S.T : P1>(x: S) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_2^#
}
extension Concrete1 {
func testInsideConstrainedConcrete1_1() {
#^PROTOCOL_EXT_INSIDE_CONCRETE1_1^#
}
func testInsideConstrainedConcrete1_2() {
self.#^PROTOCOL_EXT_INSIDE_CONCRETE1_2^#
}
}
// PROTOCOL_EXT_P4_P1: Begin completions
// PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe()
// PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceMethod]/Super: extP4WhenP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceVar]/Super: x[#Int#]{{; name=.+$}}
// PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe()
// PROTOCOL_EXT_P4_P1: End completions
func testConstrainedConcrete3(_ x: Concrete2) {
x.#^PROTOCOL_EXT_CONCRETE3^#
}
func testConstrainedConcrete3_sub(_ x: Concrete2) {
x#^PROTOCOL_EXT_CONCRETE3_SUB^#
}
func testConstrainedConcrete4(_ x: Generic2<OnlyMe>) {
x.#^PROTOCOL_EXT_CONCRETE4^#
}
func testConstrainedGeneric1<S: P4 where S.T == OnlyMe>(x: S) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3^#
}
func testConstrainedGeneric1_sub<S: P4 where S.T == OnlyMe>(x: S) {
x#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB^#
}
extension Concrete2 {
func testInsideConstrainedConcrete2_1() {
#^PROTOCOL_EXT_INSIDE_CONCRETE2_1^#
}
func testInsideConstrainedConcrete2_2() {
self.#^PROTOCOL_EXT_INSIDE_CONCRETE2_2^#
}
}
// PROTOCOL_EXT_P4_ONLYME: Begin completions
// PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#]
// PROTOCOL_EXT_P4_ONLYME-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#]
// PROTOCOL_EXT_P4_ONLYME: End completions
// PROTOCOL_EXT_P4_ONLYME_SUB: Begin completions
// PROTOCOL_EXT_P4_ONLYME_SUB: Decl[Subscript]/Super: [{#Int#}][#Int#]{{; name=.+$}}
// PROTOCOL_EXT_P4_ONLYME_SUB: End completions
func testTypealias1() {
Concrete1.#^PROTOCOL_EXT_TA_1^#
}
func testTypealias1<S: P4 where S.T == WillConformP1>() {
S.#^PROTOCOL_EXT_TA_2^#
}
// PROTOCOL_EXT_TA: Begin completions
// PROTOCOL_EXT_TA_2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T
// PROTOCOL_EXT_TA: End completions
func testProtExtInit1() {
Concrete1(#^PROTOCOL_EXT_INIT_1^#
}
// PROTOCOL_EXT_INIT_1: Begin completions
// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['('])[#Concrete1#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['(']{#x: Int#})[#Concrete1#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_1: End completions
func testProtExtInit2<S: P4 where S.T : P1>() {
S(#^PROTOCOL_EXT_INIT_2^#
}
// PROTOCOL_EXT_INIT_2: Begin completions
// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['('])[#P4#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['(']{#x: Int#})[#P4#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_2: End completions
extension P4 where Self.T == OnlyMe {
final func test1() {
self.#^PROTOCOL_EXT_P4_DOT_1^#
}
final func test2() {
#^PROTOCOL_EXT_P4_DOT_2^#
}
}
// PROTOCOL_EXT_P4_DOT: Begin completions
// PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_DOT-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_DOT: End completions
extension P4 where Self.T == WillConformP1 {
final func test() {
T.#^PROTOCOL_EXT_P4_T_DOT_1^#
}
}
// PROTOCOL_EXT_P4_T_DOT_1: Begin completions
// PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/Super: extP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_T_DOT_1: End completions
protocol PWithT {
associatedtype T
func foo(_ x: T) -> T
}
extension PWithT {
final func bar(_ x: T) -> T {
return x
}
}
// Note: PWithT cannot actually be used as an existential type because it has
// an associated type. But we should still be able to give code completions.
func testUnusableProtExt(_ x: PWithT) {
x.#^PROTOCOL_EXT_UNUSABLE_EXISTENTIAL^#
}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Begin completions
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: foo({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: bar({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: End completions
protocol dedupP {
associatedtype T
func foo() -> T
var bar: T {get}
subscript(x: T) -> T {get}
}
extension dedupP {
func foo() -> T { return T() }
var bar: T { return T() }
subscript(x: T) -> T { return T() }
}
struct dedupS : dedupP {
func foo() -> Int { return T() }
var bar: Int = 5
subscript(x: Int) -> Int { return 10 }
}
func testDeDuped(_ x: dedupS) {
x#^PROTOCOL_EXT_DEDUP_1^#
// PROTOCOL_EXT_DEDUP_1: Begin completions, 3 items
// PROTOCOL_EXT_DEDUP_1: Decl[InstanceMethod]/CurrNominal: .foo()[#Int#]; name=foo()
// PROTOCOL_EXT_DEDUP_1: Decl[InstanceVar]/CurrNominal: .bar[#Int#]; name=bar
// PROTOCOL_EXT_DEDUP_1: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]; name=[Int]
// PROTOCOL_EXT_DEDUP_1: End completions
}
func testDeDuped2(_ x: dedupP) {
x#^PROTOCOL_EXT_DEDUP_2^#
// PROTOCOL_EXT_DEDUP_2: Begin completions, 4 items
// PROTOCOL_EXT_DEDUP_2: Decl[InstanceMethod]/CurrNominal: .foo()[#dedupP.T#]; name=foo()
// PROTOCOL_EXT_DEDUP_2: Decl[InstanceVar]/CurrNominal: .bar[#dedupP.T#]; name=bar
// PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T]
// FIXME: duplicate subscript on protocol type rdar://problem/22086900
// PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T]
// PROTOCOL_EXT_DEDUP_2: End completions
}
func testDeDuped3<T : dedupP where T.T == Int>(_ x: T) {
x#^PROTOCOL_EXT_DEDUP_3^#
// PROTOCOL_EXT_DEDUP_3: Begin completions, 3 items
// PROTOCOL_EXT_DEDUP_3: Decl[InstanceMethod]/Super: .foo()[#Int#]; name=foo()
// PROTOCOL_EXT_DEDUP_3: Decl[InstanceVar]/Super: .bar[#Int#]; name=bar
// PROTOCOL_EXT_DEDUP_3: Decl[Subscript]/Super: [{#Self.T#}][#Self.T#]; name=[Self.T]
// PROTOCOL_EXT_DEDUP_3: End completions
}
//===--- Check calls that may throw
func globalFuncThrows() throws {}
func globalFuncRethrows(_ x: () throws -> ()) rethrows {}
struct HasThrowingMembers {
func memberThrows() throws {}
func memberRethrows(_ x: () throws -> ()) rethrows {}
init() throws {}
init(x: () throws -> ()) rethrows {}
}
func testThrows001() {
globalFuncThrows#^THROWS1^#
// THROWS1: Begin completions
// THROWS1: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws
// THROWS1: End completions
}
func testThrows002() {
globalFuncRethrows#^THROWS2^#
// THROWS2: Begin completions
// THROWS2: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
// THROWS2: End completions
}
func testThrows003(_ x: HasThrowingMembers) {
x.#^MEMBER_THROWS1^#
// MEMBER_THROWS1: Begin completions
// MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberThrows()[' throws'][#Void#]
// MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberRethrows({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]
// MEMBER_THROWS1: End completions
}
func testThrows004(_ x: HasThrowingMembers) {
x.memberThrows#^MEMBER_THROWS2^#
// MEMBER_THROWS2: Begin completions
// MEMBER_THROWS2: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws
// MEMBER_THROWS2: End completions
}
func testThrows005(_ x: HasThrowingMembers) {
x.memberRethrows#^MEMBER_THROWS3^#
// MEMBER_THROWS3: Begin completions
// MEMBER_THROWS3: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
// MEMBER_THROWS3: End completions
}
func testThrows006() {
HasThrowingMembers(#^INIT_THROWS1^#
// INIT_THROWS1: Begin completions
// INIT_THROWS1: Decl[Constructor]/CurrNominal: ['('])[' throws'][#HasThrowingMembers#]
// INIT_THROWS1: Decl[Constructor]/CurrNominal: ['(']{#x: () throws -> ()##() throws -> ()#})[' rethrows'][#HasThrowingMembers#]
// INIT_THROWS1: End completions
}
// rdar://21346928
// Just sample some String API to sanity check.
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#]
func testWithAutoClosure1(_ x: String?) {
(x ?? "autoclosure").#^AUTOCLOSURE1^#
}
func testWithAutoClosure2(_ x: String?) {
let y = (x ?? "autoclosure").#^AUTOCLOSURE2^#
}
func testWithAutoClosure3(_ x: String?) {
let y = (x ?? "autoclosure".#^AUTOCLOSURE3^#)
}
func testWithAutoClosure4(_ x: String?) {
let y = { let z = (x ?? "autoclosure").#^AUTOCLOSURE4^# }
}
func testWithAutoClosure5(_ x: String?) {
if let y = (x ?? "autoclosure").#^AUTOCLOSURE5^# {
}
}
func testGenericTypealias1() {
typealias MyPair<T> = (T, T)
var x: MyPair<Int>
x.#^GENERIC_TYPEALIAS_1^#
}
// GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 0[#Int#];
// GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 1[#Int#];
func testGenericTypealias2() {
struct Enclose {
typealias MyPair<T> = (T, T)
}
Enclose.#^GENERIC_TYPEALIAS_2^#
}
// GENERIC_TYPEALIAS_2: Decl[TypeAlias]/CurrNominal: MyPair[#(T, T)#];
struct Deprecated {
@available(*, deprecated)
func deprecated(x: Deprecated) {
x.#^DEPRECATED_1^#
}
}
// DEPRECATED_1: Decl[InstanceMethod]/CurrNominal/NotRecommended: deprecated({#x: Deprecated#})[#Void#];
struct Person {
var firstName: String
}
class Other { var nameFromOther: Int = 1 }
class TestDotExprWithNonNominal {
var other: Other
func test1() {
let person = Person(firstName: other.#^DOT_EXPR_NON_NOMINAL_1^#)
// DOT_EXPR_NON_NOMINAL_1-NOT: Instance
// DOT_EXPR_NON_NOMINAL_1: Decl[InstanceVar]/CurrNominal: nameFromOther[#Int#];
// DOT_EXPR_NON_NOMINAL_1-NOT: Instance
}
func test2() {
let person = Person(firstName: 1.#^DOT_EXPR_NON_NOMINAL_2^#)
// DOT_EXPR_NON_NOMINAL_2-NOT: other
// DOT_EXPR_NON_NOMINAL_2-NOT: firstName
// DOT_EXPR_NON_NOMINAL_2: Decl[InstanceVar]/CurrNominal: hashValue[#Int#];
// DOT_EXPR_NON_NOMINAL_2-NOT: other
// DOT_EXPR_NON_NOMINAL_2-NOT: firstName
}
}
| e8594b6b0a66487d324e69d2eadf53bc | 57.247916 | 202 | 0.695824 | false | true | false | false |
D8Ge/Jchat | refs/heads/master | Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/Google_Protobuf_Timestamp_Extensions.swift | mit | 1 | // ProtobufRuntime/Sources/Protobuf/Google_Protobuf_Timestamp_Extensions.swift - Timestamp extensions
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Extend the generated Timestamp message with customized JSON coding,
/// arithmetic operations, and convenience methods.
///
// -----------------------------------------------------------------------------
import Swift
// TODO: Add convenience methods to interoperate with standard
// date/time classes: an initializer that accepts Unix timestamp as
// Int or Double, an easy way to convert to/from Foundation's
// NSDateTime (on Apple platforms only?), others?
private func FormatInt(n: Int32, digits: Int) -> String {
if n < 0 {
return FormatInt(n: -n, digits: digits)
} else if digits <= 0 {
return ""
} else if digits == 1 && n < 10 {
return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n)]
} else {
return FormatInt(n: n / 10, digits: digits - 1) + ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n % 10)]
}
}
private func fromAscii2(_ digit0: Int, _ digit1: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 10 + digit1 - 528
}
private func fromAscii4(_ digit0: Int, _ digit1: Int, _ digit2: Int, _ digit3: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if (digit0 < zero || digit0 > nine
|| digit1 < zero || digit1 > nine
|| digit2 < zero || digit2 > nine
|| digit3 < zero || digit3 > nine) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 1000 + digit1 * 100 + digit2 * 10 + digit3 - 53328
}
// Parse an RFC3339 timestamp into a pair of seconds-since-1970 and nanos.
private func parseTimestamp(s: String) throws -> (Int64, Int32) {
// Convert to an array of integer character values
let value = s.utf8.map{Int($0)}
if value.count < 20 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Since the format is fixed-layout, we can just decode
// directly as follows.
let zero = Int(48)
let nine = Int(57)
let dash = Int(45)
let colon = Int(58)
let plus = Int(43)
let letterT = Int(84)
let letterZ = Int(90)
let period = Int(46)
// Year: 4 digits followed by '-'
let year = try fromAscii4(value[0], value[1], value[2], value[3])
if value[4] != dash || year < Int(1) || year > Int(9999) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Month: 2 digits followed by '-'
let month = try fromAscii2(value[5], value[6])
if value[7] != dash || month < Int(1) || month > Int(12) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Day: 2 digits followed by 'T'
let mday = try fromAscii2(value[8], value[9])
if value[10] != letterT || mday < Int(1) || mday > Int(31) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Hour: 2 digits followed by ':'
let hour = try fromAscii2(value[11], value[12])
if value[13] != colon || hour > Int(23) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Minute: 2 digits followed by ':'
let minute = try fromAscii2(value[14], value[15])
if value[16] != colon || minute > Int(59) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Second: 2 digits (following char is checked below)
let second = try fromAscii2(value[17], value[18])
if second > Int(61) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// timegm() is almost entirely useless. It's nonexistent on
// some platforms, broken on others. Everything else I've tried
// is even worse. Hence the code below.
// (If you have a better way to do this, try it and see if it
// passes the test suite on both Linux and OS X.)
// Day of year
let mdayStart: [Int] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
var yday = Int64(mdayStart[month - 1])
let isleap = (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))
if isleap && (month > 2) {
yday += 1
}
yday += Int64(mday - 1)
// Days since start of epoch (including leap days)
var daysSinceEpoch = yday
daysSinceEpoch += Int64(365 * year) - Int64(719527)
daysSinceEpoch += Int64((year - 1) / 4)
daysSinceEpoch -= Int64((year - 1) / 100)
daysSinceEpoch += Int64((year - 1) / 400)
// Second within day
var daySec = Int64(hour)
daySec *= 60
daySec += Int64(minute)
daySec *= 60
daySec += Int64(second)
// Seconds since start of epoch
let t = daysSinceEpoch * Int64(86400) + daySec
// After seconds, comes various optional bits
var pos = 19
var nanos: Int32 = 0
if value[pos] == period { // "." begins fractional seconds
pos += 1
var digitValue = 100000000
while pos < value.count && value[pos] >= zero && value[pos] <= nine {
nanos += digitValue * (value[pos] - zero)
digitValue /= 10
pos += 1
}
}
var seconds: Int64 = 0
if value[pos] == plus || value[pos] == dash { // "+" or "-" starts Timezone offset
if pos + 6 > value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
let hourOffset = try fromAscii2(value[pos + 1], value[pos + 2])
let minuteOffset = try fromAscii2(value[pos + 4], value[pos + 5])
if hourOffset > Int(13) || minuteOffset > Int(59) || value[pos + 3] != colon {
throw ProtobufDecodingError.malformedJSONTimestamp
}
var adjusted: Int64 = t
if value[pos] == plus {
adjusted -= Int64(hourOffset) * Int64(3600)
adjusted -= Int64(minuteOffset) * Int64(60)
} else {
adjusted += Int64(hourOffset) * Int64(3600)
adjusted += Int64(minuteOffset) * Int64(60)
}
if adjusted < -62135596800 || adjusted > 253402300799 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
seconds = adjusted
pos += 6
} else if value[pos] == letterZ { // "Z" indicator for UTC
seconds = t
pos += 1
} else {
throw ProtobufDecodingError.malformedJSONTimestamp
}
if pos != value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return (seconds, nanos)
}
private func formatTimestamp(seconds: Int64, nanos: Int32) -> String? {
if ((seconds < 0 && nanos > 0)
|| (seconds > 0 && nanos < 0)
|| (seconds < -62135596800)
|| (seconds == -62135596800 && nanos < 0)
|| (seconds >= 253402300800)) {
return nil
}
// Can't just use gmtime() here because time_t is sometimes 32 bits. Ugh.
let secondsSinceStartOfDay = (Int32(seconds % 86400) + 86400) % 86400
let sec = secondsSinceStartOfDay % 60
let min = (secondsSinceStartOfDay / 60) % 60
let hour = secondsSinceStartOfDay / 3600
// The following implements Richards' algorithm (see the Wikipedia article
// for "Julian day").
// If you touch this code, please test it exhaustively by playing with
// Test_Timestamp.testJSON_range.
let julian = (seconds + 210866803200) / 86400
let f = julian + 1401 + (((4 * julian + 274277) / 146097) * 3) / 4 - 38
let e = 4 * f + 3
let g = e % 1461 / 4
let h = 5 * g + 2
let mday = Int32(h % 153 / 5 + 1)
let month = (h / 153 + 2) % 12 + 1
let year = e / 1461 - 4716 + (12 + 2 - month) / 12
// We can't use strftime here (it varies with locale)
// We can't use strftime_l here (it's not portable)
// The following is crude, but it works.
// TODO: If String(format:) works, that might be even better
// (it was broken on Linux a while back...)
let result = (FormatInt(n: Int32(year), digits: 4)
+ "-"
+ FormatInt(n: Int32(month), digits: 2)
+ "-"
+ FormatInt(n: mday, digits: 2)
+ "T"
+ FormatInt(n: hour, digits: 2)
+ ":"
+ FormatInt(n: min, digits: 2)
+ ":"
+ FormatInt(n: sec, digits: 2))
if nanos == 0 {
return "\(result)Z"
} else {
var digits: Int
var fraction: Int
if nanos % 1000000 == 0 {
fraction = Int(nanos) / 1000000
digits = 3
} else if nanos % 1000 == 0 {
fraction = Int(nanos) / 1000
digits = 6
} else {
fraction = Int(nanos)
digits = 9
}
var formatted_fraction = ""
while digits > 0 {
formatted_fraction = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][fraction % 10] + formatted_fraction
fraction /= 10
digits -= 1
}
return "\(result).\(formatted_fraction)Z"
}
}
public extension Google_Protobuf_Timestamp {
public init(secondsSinceEpoch: Int64, nanos: Int32 = 0) {
self.init()
self.seconds = secondsSinceEpoch
self.nanos = nanos
}
public mutating func decodeFromJSONToken(token: ProtobufJSONToken) throws {
if case .string(let s) = token {
let timestamp = try parseTimestamp(s: s)
seconds = timestamp.0
nanos = timestamp.1
} else {
throw ProtobufDecodingError.schemaMismatch
}
}
public func serializeJSON() throws -> String {
let s = seconds
let n = nanos
if let formatted = formatTimestamp(seconds: s, nanos: n) {
return "\"\(formatted)\""
} else {
throw ProtobufEncodingError.timestampJSONRange
}
}
func serializeAnyJSON() throws -> String {
let value = try serializeJSON()
return "{\"@type\":\"\(anyTypeURL)\",\"value\":\(value)}"
}
}
private func normalizedTimestamp(seconds: Int64, nanos: Int32) -> Google_Protobuf_Timestamp {
var s = seconds
var n = nanos
if n >= 1000000000 || n <= -1000000000 {
s += Int64(n) / 1000000000
n = n % 1000000000
}
if s > 0 && n < 0 {
n += 1000000000
s -= 1
} else if s < 0 && n > 0 {
n -= 1000000000
s += 1
}
return Google_Protobuf_Timestamp(seconds: s, nanos: n)
}
public func -(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds - rhs.seconds, nanos: lhs.nanos - rhs.nanos)
}
public func+(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds + rhs.seconds, nanos: lhs.nanos + rhs.nanos)
}
| 28d5c26f4d3e82821887ad1dc398b1c9 | 33.84472 | 122 | 0.580481 | false | false | false | false |
liuweihaocool/iOS_06_liuwei | refs/heads/master | 新浪微博_swift/新浪微博_swift/class/Main/Compare/Controller/LWCompareController.swift | apache-2.0 | 1 | //
// LWCompareController.swift
// 新浪微博_swift
//
// Created by LiuWei on 15/12/5.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
class LWCompareController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 设置viw的背景颜色
view.backgroundColor = UIColor(white: 0.5, alpha: 1)
// 设置导航栏
prepareUI()
}
/// 准备UI
private func prepareUI() {
/// 导航栏
setupNavigationBar()
/// 文本框
setupTextView()
/// 工具条
setupToolBar()
}
/// 设置文本
func setupTextView() {
/// 添加子控制器
view.addSubview(textView)
/// 去除系统的约束
textView.translatesAutoresizingMaskIntoConstraints = false
/// 自定义约束
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0))
// 设置代理来监听文本的改变
textView.delegate = self
}
/// 设置导航栏按钮
private func setupNavigationBar(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWindow")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendMessage")
setupTitle()
// 设置发送按钮不可用
navigationItem.rightBarButtonItem?.enabled = false
}
/// 设置导航栏标题
private func setupTitle(){
if let name = LWUserAccount.loadUserAccount()?.screen_name {
// 创建label
let label = UILabel()
// 设置字体
label.font = UIFont.systemFontOfSize(14)
// 设置文字
label.text = name + "\n" + "发送的微博"
// 设置字体颜色
label.textColor = UIColor.redColor()
// 换行
label.numberOfLines = 0
let attText = NSMutableAttributedString(string: label.text!)
let nameRange = (name as NSString).rangeOfString(name)
attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: nameRange)
label.attributedText = attText
label.textAlignment = NSTextAlignment.Center
// 适应大小
label.sizeToFit()
// 为title赋值
navigationItem.titleView = label
} else {
navigationItem.title = "发送微博"
}
}
/// 关闭控制器 @obj修饰 private
@objc private func closeWindow() {
dismissViewControllerAnimated(true, completion: nil)
}
/// 发送微博的实现
@objc private func sendMessage() {
print("发送微博")
}
// private lazy var textView:LWPlaceholdView = {
// // 实例化对象
// let textView = LWPlaceholdView()
// // 设置背景颜色
// textView.backgroundColor = UIColor.lightTextColor()
// // 字体
// textView.font = UIFont.systemFontOfSize(20)
//// // 滚动条
// textView.alwaysBounceVertical = true
//
//
// let placeHolderLabel = UILabel()
//
// placeHolderLabel.textColor = UIColor.lightTextColor()
// placeHolderLabel.font = textView.font
//
// placeHolderLabel.text = "分享新鲜事"
//
// placeHolderLabel.sizeToFit()
//
//
////
//// // 拖拽的时候会 退出键盘
// textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
////
//// // 站位文本
//
//
// return textView
// }()
private lazy var textView:LWPlaceholdView = {
let tv = LWPlaceholdView()
tv.backgroundColor = UIColor.brownColor()
tv.alwaysBounceVertical = true
tv.placeholder = "分享新鲜事"
return tv
}()
private func setupToolBar() {
/// 添加toolbar到 view
view.addSubview(toolBar)
/// 去掉系统的自动约束
toolBar.translatesAutoresizingMaskIntoConstraints = false
// 约束 X轴
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
// 约束 Y轴
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
// 约束宽度
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
// 约束高度
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
// 添加item对应的图片名称
let itemSettings = [["imageName":"compose_toolbar_picture","action":"picture"],
["imageName":"compose_trendbutton_background","action":"trend"],
["imageName":"compose_mentionbutton_background","action":"mention"],
["imageName":"compose_emoticonbutton_background","action":"emotion"],
["imageName":"compose_addbutton_background","action":"add"]]
// 存放UIBarButtonItem
var items = [UIBarButtonItem]()
// 通过for循环遍历数组的图片名称
for dict in itemSettings {
let imageName = dict["imageName"]
let item = UIBarButtonItem(image: imageName!)
let action = dict["action"]
// 获取UIBarbutton的customView 是一个按钮
let button = item.customView as! UIButton
// 添加点击事件
button.addTarget(self, action: Selector(action!), forControlEvents: UIControlEvents.TouchUpInside)
// 填加到数组
items.append(item)
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
}
items.removeLast()
toolBar.items = items
}
/// 懒加载
private lazy var toolBar:UIToolbar = {
// 实例化uitoolBar
let tool = UIToolbar()
tool.backgroundColor = UIColor.redColor()
return tool
}()
func picture() {
print("fff")
}
func trend() {
print("fff")
}
func mention() {
print("fff")
}
func emotion() {
print("fff")
}
func add() {
print("fff")
}
}
// 扩展当前控制器 实现UItextViewDelegate 来监听文本值得改变
extension LWCompareController:UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
// 设置导航栏右边按钮的状态
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
}
}
| a5ac16e30d15fda21f62c587f4988a57 | 33.436937 | 222 | 0.607325 | false | false | false | false |
blinker13/Geometry | refs/heads/main | Sources/Primitives/Angle.swift | mit | 1 |
public struct Angle : Arithmetic, Codable, Comparable {
@usableFromInline internal let rawValue: Scalar
@usableFromInline internal init(_ value: Scalar) {
rawValue = value
}
}
// MARK: -
public extension Angle {
@inlinable static var zero: Self { .radians(.zero) }
@inlinable static var half: Self { .radians(.pi) }
@inlinable static var full: Self { .radians(.pi * 2) }
@inlinable static prefix func - (value: Self) -> Self { .init(value.rawValue) }
@inlinable static func + (left: Self, right: Self) -> Self { .init(left.rawValue + right.rawValue) }
@inlinable static func - (left: Self, right: Self) -> Self { .init(left.rawValue - right.rawValue) }
@inlinable static func * (left: Self, right: Self) -> Self { .init(left.rawValue * right.rawValue) }
@inlinable static func / (left: Self, right: Self) -> Self { .init(left.rawValue / right.rawValue) }
@inlinable static func < (left: Self, right: Self) -> Bool { left.rawValue < right.rawValue }
@inlinable static func degrees(_ value: Scalar) -> Self { .init(degrees: value) }
@inlinable static func radians(_ value: Scalar) -> Self { .init(radians: value) }
@inlinable var degrees: Scalar { rawValue * 180.0 / .pi }
@inlinable var radians: Scalar { rawValue }
@inlinable init(degrees: Scalar) { rawValue = degrees / 180.0 * .pi }
@inlinable init(radians: Scalar) { rawValue = radians }
@inlinable init(from decoder: Decoder) throws {
rawValue = try Scalar(from: decoder)
}
@inlinable func encode(to encoder: Encoder) throws {
try rawValue.encode(to: encoder)
}
@inlinable func rounded(_ rule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
.init(rawValue.rounded(rule))
}
}
| 1d3ef850cc5e69f326c1a55fd917c3cb | 34.270833 | 101 | 0.691081 | false | false | false | false |
aiwalle/LiveProject | refs/heads/master | LiveProject/Rank/Controller/LJWeeklyRankViewController.swift | mit | 1 | //
// LJWeeklyRankViewController.swift
// LiveProject
//
// Created by liang on 2017/10/26.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
let kLJWeeklyRankViewCell = "LJWeeklyRankViewCell"
class LJWeeklyRankViewController: LJDetailRankViewController {
fileprivate lazy var weeklyRankVM: LJWeeklyRankViewModel = LJWeeklyRankViewModel()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "LJWeeklyRankViewCell", bundle: nil), forCellReuseIdentifier: kLJWeeklyRankViewCell)
}
override init(rankType: LJRankType) {
super.init(rankType: rankType)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LJWeeklyRankViewController {
override func loadData() {
weeklyRankVM.loadWeeklyRankData(rankType) {
self.tableView.reloadData()
}
}
}
extension LJWeeklyRankViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return weeklyRankVM.weeklyRanks.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weeklyRankVM.weeklyRanks[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kLJWeeklyRankViewCell) as! LJWeeklyRankViewCell
cell.weekly = weeklyRankVM.weeklyRanks[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "主播周星榜" : "富豪周星榜"
}
}
| 527fa0f7f724aa85fb1fe203f59c00d5 | 27.677419 | 126 | 0.699663 | false | false | false | false |
xuzizhou/WeChatActivities-in-iOS-8-with-Swift | refs/heads/master | WeChatSharing/WeChatActivityGeneral.swift | mit | 1 | //
// WeChatActivityGeneral.swift
// SuperBoard
//
// Created by Xuzi Zhou on 1/12/15.
// Copyright (c) 2015 Xuzi Zhou. All rights reserved.
//
import UIKit
class WeChatActivityGeneral: UIActivity {
var text:String!
var url:NSURL!
var image:UIImage!
var isSessionScene = true
override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
var req:SendMessageToWXReq!
if WXApi.isWXAppInstalled() && WXApi.isWXAppSupportApi() {
for item in activityItems {
if item is UIImage {
return true
}
if item is String {
return true
}
if item is NSURL {
return true
}
}
}
return false
}
override func prepareWithActivityItems(activityItems: [AnyObject]) {
for item in activityItems {
if item is UIImage {
image = item as! UIImage
}
if item is String {
text = item as! String
}
if item is NSURL {
url = item as! NSURL
}
}
}
override func performActivity() {
var req = SendMessageToWXReq()
// If you are sharing text-only messages, make req.bText=true and pick the correct WX message class
req.bText = false
req.message = WXMediaMessage()
if isSessionScene {
req.scene = WXSceneSession.value
} else {
req.scene = WXSceneTimeline.value
}
req.message.title = text
req.message.description = "https://itunes.apple.com/app/superboard/id951480740?mt=8"
// set the size of thumbnail image from original UIImage data
var width = 240.0 as CGFloat
var height = width*image.size.height/image.size.width
UIGraphicsBeginImageContext(CGSizeMake(width, height))
image.drawInRect(CGRectMake(0, 0, width, height))
req.message.setThumbImage(UIGraphicsGetImageFromCurrentImageContext())
UIGraphicsEndImageContext()
var imageObject = WXImageObject()
imageObject.imageData = UIImageJPEGRepresentation(image, 1)
req.message.mediaObject = imageObject
WXApi.sendReq(req)
self.activityDidFinish(true)
}
}
| 447c1ec70478b28da5e51250b558c150 | 30.207792 | 107 | 0.574282 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/SiteImageHelper.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import LinkPresentation
import Shared
import Storage
enum SiteImageType: Int {
case heroImage = 0, favicon
func peek() -> Self? {
return SiteImageType(rawValue: rawValue + 1)
}
mutating func next() -> Self? {
return SiteImageType(rawValue: rawValue + 1)
}
}
protocol SiteImageHelperProtocol {
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider,
completion: @escaping (UIImage?) -> Void)
}
extension SiteImageHelperProtocol {
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider = LPMetadataProvider(),
completion: @escaping (UIImage?) -> Void) {
self.fetchImageFor(site: site,
imageType: imageType,
shouldFallback: shouldFallback,
metadataProvider: metadataProvider,
completion: completion)
}
}
/// A helper that'll fetch an image, and fallback to other image options if specified.
class SiteImageHelper: SiteImageHelperProtocol {
private static let cache = NSCache<NSString, UIImage>()
private let throttler = Throttler(seconds: 0.5, on: DispatchQueue.main)
private let faviconFetcher: Favicons
convenience init(profile: Profile) {
self.init(faviconFetcher: profile.favicons)
}
init(faviconFetcher: Favicons) {
self.faviconFetcher = faviconFetcher
}
/// Given a `Site`, this will fetch the type of image you're looking for while allowing you to fallback to the next `SiteImageType`.
/// - Parameters:
/// - site: The site to fetch an image from.
/// - imageType: The `SiteImageType` that will work for you.
/// - shouldFallback: Allow a fallback image to be given in the case where the `SiteImageType` you specify is not available.
/// - metadataProvider: Metadata provider for hero image type. Default is normally used, replaced in case of tests
/// - completion: Work to be done after fetching an image, ideally done on the main thread.
/// - Returns: A UIImage.
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider = LPMetadataProvider(),
completion: @escaping (UIImage?) -> Void) {
var didCompleteFetch = false
var imageType = imageType
switch imageType {
case .heroImage:
fetchHeroImage(for: site, metadataProvider: metadataProvider) { image, result in
guard let heroImage = image else { return }
didCompleteFetch = result ?? false
DispatchQueue.main.async {
completion(heroImage)
return
}
}
case .favicon:
fetchFavicon(for: site) { image, result in
guard let favicon = image else { return }
didCompleteFetch = result ?? false
DispatchQueue.main.async {
completion(favicon)
return
}
}
}
throttler.throttle { [weak self] in
if !didCompleteFetch && imageType.peek() != nil,
let updatedImageType = imageType.next(), shouldFallback {
self?.fetchImageFor(site: site,
imageType: updatedImageType,
shouldFallback: shouldFallback,
completion: completion)
} else { return }
}
}
static func clearCacheData() {
SiteImageHelper.cache.removeAllObjects()
}
// MARK: - Private
private func fetchHeroImage(for site: Site, metadataProvider: LPMetadataProvider, completion: @escaping (UIImage?, Bool?) -> Void) {
let heroImageCacheKey = NSString(string: "\(site.url)\(SiteImageType.heroImage.rawValue)")
// Fetch from cache, if not then fetch with LPMetadataProvider
if let cachedImage = SiteImageHelper.cache.object(forKey: heroImageCacheKey) {
completion(cachedImage, true)
} else {
guard let url = URL(string: site.url) else {
completion(nil, false)
return
}
fetchFromMetaDataProvider(heroImageCacheKey: heroImageCacheKey,
url: url,
metadataProvider: metadataProvider,
completion: completion)
}
}
private func fetchFromMetaDataProvider(heroImageCacheKey: NSString,
url: URL,
metadataProvider: LPMetadataProvider,
completion: @escaping (UIImage?, Bool?) -> Void) {
// LPMetadataProvider must be interacted with on the main thread or it can crash
// The closure will return on a non-main thread
ensureMainThread {
metadataProvider.startFetchingMetadata(for: url) { metadata, error in
guard let metadata = metadata,
let imageProvider = metadata.imageProvider,
error == nil
else {
completion(nil, false)
return
}
imageProvider.loadObject(ofClass: UIImage.self) { image, error in
guard error == nil, let image = image as? UIImage else {
completion(nil, false)
return
}
SiteImageHelper.cache.setObject(image, forKey: heroImageCacheKey)
completion(image, true)
}
}
}
}
private func fetchFavicon(for site: Site, completion: @escaping (UIImage?, Bool?) -> Void) {
let faviconCacheKey = NSString(string: "\(site.url)\(SiteImageType.favicon.rawValue)")
// Fetch from cache, if not then fetch from profile
if let cachedImage = SiteImageHelper.cache.object(forKey: faviconCacheKey) {
completion(cachedImage, true)
} else {
faviconFetcher.getFaviconImage(forSite: site).uponQueue(.main, block: { result in
guard let image = result.successValue else { return }
SiteImageHelper.cache.setObject(image, forKey: faviconCacheKey)
completion(image, true)
})
}
}
}
| 678fd9e699422a53e900486aa304f2b3 | 39.268571 | 136 | 0.563076 | false | false | false | false |
kwonye/class-directory | refs/heads/master | Class Directory/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Class Directory
//
// Created by Will Kwon on 5/7/17.
// Copyright © 2017 William Kwon. 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.
let preferencesFile = Bundle.main.url(forResource: "Preferences", withExtension: "plist")!
let defaultPreferences = NSDictionary.init(contentsOf: preferencesFile)
UserDefaults.standard.register(defaults: defaultPreferences as! [String : Any])
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: "Class_Directory")
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)")
}
}
}
}
| 4d8fa8fa6ba08e32b8f315d938b76d4d | 48.867347 | 285 | 0.686515 | false | false | false | false |
lanserxt/teamwork-ios-sdk | refs/heads/master | TeamWorkClient/TeamWorkClient/MultipleResponseContainer.swift | mit | 1 | //
// MultipleResponseContainer.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 01.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
public class MultipleResponseContainer<T: Model>{
//MARK:- Variables
public var status : TWApiStatusCode?
public var rootObjects: [T]? {
return self.object as! [T]?
}
private var object : [Model]?
private var rootObjectName : String
//MARK:- Init
required public init?(rootObjectName: String, dictionary: NSDictionary) {
self.rootObjectName = rootObjectName
status = dictionary[TWApiClientConstants.kStatus] as? String == TWApiStatusCode.OK.rawValue ? .OK : .Undefined
if (dictionary[self.rootObjectName] != nil){
object = T.modelsFromDictionaryArray(array: (dictionary: dictionary[self.rootObjectName] as! NSArray))
}
}
//MARK:- Methods
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.status, forKey: TWApiClientConstants.kStatus)
var objectArr = [T]()
for item:Model in self.object! {
objectArr.append(item.dictionaryRepresentation() as! T)
}
dictionary.setValue(objectArr, forKey: self.rootObjectName)
return dictionary
}
}
| 84952d9893e343fbef05a7bd5e38a4e5 | 28.520833 | 118 | 0.64573 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/arguments.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -module-name Swift -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
struct Int {}
struct Float {}
struct UnicodeScalar {}
enum Never {}
// Minimal implementation to support varargs.
struct Array<T> { }
func _allocateUninitializedArray<T>(_: Builtin.Word)
-> (Array<T>, Builtin.RawPointer) {
Builtin.int_trap()
}
func _deallocateUninitializedArray<T>(_: Array<T>) {}
var i:Int, f:Float, c:UnicodeScalar
func arg_tuple(x: Int, y: Float) {}
// CHECK-LABEL: sil hidden @_T0s9arg_tupleySi1x_Sf1ytF
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float):
arg_tuple(x: i, y: f)
func arg_deep_tuples(x: Int, y: (Float, UnicodeScalar)) {}
// CHECK-LABEL: sil hidden @_T0s15arg_deep_tuplesySi1x_Sf_Sct1ytF
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y_0:%[0-9]+]] : @trivial $Float, [[Y_1:%[0-9]+]] : @trivial $UnicodeScalar):
arg_deep_tuples(x:i, y:(f, c))
var unnamed_subtuple = (f, c)
arg_deep_tuples(x:i, y: unnamed_subtuple)
// rdar://problem/12985801 -- tuple conversion confuses named fields
// of a subtuple with those of outer tuple
var named_subtuple = (x:f, y:c)
arg_deep_tuples(x:i, y: named_subtuple)
func arg_deep_tuples_2(x: Int, _: (y: Float, z: UnicodeScalar)) {}
// CHECK-LABEL: sil hidden @_T0s17arg_deep_tuples_2ySi1x_Sf1y_Sc1zttF
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float, [[Z:%[0-9]+]] : @trivial $UnicodeScalar):
arg_deep_tuples_2(x: i, (f, c))
arg_deep_tuples_2(x: i, unnamed_subtuple)
// FIXME rdar://problem/12985103 -- tuples don't convert recursively, so
// #var x = (1, (2.0, '3')); arg_deep_tuples_2(x)# doesn't type check
//arg_deep_tuples_2(deep_named_tuple)
func arg_default_tuple(x x: Int = i, y: Float = f) {}
// CHECK-LABEL: sil hidden @_T0s17arg_default_tupleySi1x_Sf1ytF
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float):
arg_default_tuple()
arg_default_tuple(x:i)
arg_default_tuple(y:f)
arg_default_tuple(x:i, y:f)
func variadic_arg_1(_ x: Int...) {}
// CHECK-LABEL: sil hidden @_T0s14variadic_arg_1{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Array<Int>):
variadic_arg_1()
variadic_arg_1(i)
variadic_arg_1(i, i, i)
func variadic_arg_2(_ x: Int, _ y: Float...) {}
// CHECK-LABEL: sil hidden @_T0s14variadic_arg_2{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Array<Float>):
variadic_arg_2(i)
variadic_arg_2(i, f)
variadic_arg_2(i, f, f, f)
func variadic_arg_3(_ y: Float..., x: Int) {}
// CHECK-LABEL: sil hidden @_T0s14variadic_arg_3{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[Y:%[0-9]+]] : @trivial $Array<Float>, [[X:%[0-9]+]] : @trivial $Int):
variadic_arg_3(x: i)
variadic_arg_3(f, x: i)
variadic_arg_3(f, f, f, x: i)
protocol Runcible {}
extension Int : Runcible {}
func variadic_address_only_arg(_ x: Runcible...) {}
variadic_address_only_arg(i)
| 580fa61f7df4401de89d48bdbf25f976 | 30.868132 | 123 | 0.633793 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | SampleApps/CCGSampleApp/CCGSampleApp/ViewControllers/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// CCGSampleApp
//
// Created by Artur Jankowski on 10/03/2022.
// Copyright © 2022 Box. All rights reserved.
//
import BoxSDK
import UIKit
class ViewController: UITableViewController {
private var sdk: BoxSDK!
private var client: BoxClient!
private var folderItems: [FolderItem] = []
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd,yyyy at HH:mm a"
return formatter
}()
private lazy var errorView: BasicErrorView = {
let errorView = BasicErrorView()
errorView.translatesAutoresizingMaskIntoConstraints = false
return errorView
}()
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
setUpBoxSDK()
setUpUI()
}
// MARK: - Actions
@objc private func loginButtonPressed() {
authorizeWithCCGClient()
removeErrorView()
}
@objc private func loadItemsButtonPressed() {
getSinglePageOfFolderItems()
removeErrorView()
}
// MARK: - Set up
private func setUpBoxSDK() {
sdk = BoxSDK(
clientId: Constants.clientId,
clientSecret: Constants.clientSecret
)
}
private func setUpUI() {
title = "Box SDK - CCG Sample App"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginButtonPressed))
tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
override func numberOfSections(in _: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return folderItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath)
let item = folderItems[indexPath.row]
if case let .file(file) = item {
cell.textLabel?.text = file.name
cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: file.modifiedAt ?? Date()))
cell.accessoryType = .none
var icon: String
switch file.extension {
case "boxnote":
icon = "boxnote"
case "jpg",
"jpeg",
"png",
"tiff",
"tif",
"gif",
"bmp",
"BMPf",
"ico",
"cur",
"xbm":
icon = "image"
case "pdf":
icon = "pdf"
case "docx":
icon = "word"
case "pptx":
icon = "powerpoint"
case "xlsx":
icon = "excel"
case "zip":
icon = "zip"
default:
icon = "generic"
}
cell.imageView?.image = UIImage(named: icon)
}
else if case let .folder(folder) = item {
cell.textLabel?.text = folder.name
cell.detailTextLabel?.text = ""
cell.accessoryType = .disclosureIndicator
cell.imageView?.image = UIImage(named: "folder")
}
return cell
}
}
// MARK: - CCG Helpers
private extension ViewController {
func authorizeWithCCGClient() {
// Section 1 - CCG connection for account service
#error("To obtain account service CCG connection please provide enterpriseId in Constants.swift file.")
sdk.getCCGClientForAccountService(enterpriseId: Constants.enterpriseId, tokenStore: KeychainTokenStore()) { [weak self] result in
self?.ccgAuthorizeHandler(result: result)
}
// Section 2 - CCG connection for user account
#error("To obtain user account CCG connection please provide userId in Constants.swift file, comment out section 1 above and uncomment section 2.")
// sdk.getCCGClientForUser(userId: Constants.userId, tokenStore: KeychainTokenStore()) { [weak self] result in
// self?.ccgAuthorizeHandler(result: result)
// }
}
func ccgAuthorizeHandler(result: Result<BoxClient, BoxSDKError>) {
switch result {
case let .success(client):
self.client = client
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load items", style: .plain, target: self, action: #selector(self.loadItemsButtonPressed))
case let .failure(error):
print("error in getCCGClient: \(error)")
self.addErrorView(with: error)
}
}
}
// MARK: - Loading items
extension ViewController {
func getSinglePageOfFolderItems() {
let iterator = client.folders.listItems(
folderId: BoxSDK.Constants.rootFolder,
usemarker: true,
fields: ["modified_at", "name", "extension"]
)
iterator.next { [weak self] result in
guard let self = self else { return }
switch result {
case let .success(page):
self.folderItems = []
for (i, item) in page.entries.enumerated() {
print ("Item #\(String(format: "%03d", i + 1)) | \(item.debugDescription))")
DispatchQueue.main.async {
self.folderItems.append(item)
self.tableView.reloadData()
self.navigationItem.rightBarButtonItem?.title = "Refresh"
}
}
case let .failure(error):
self.addErrorView(with: error)
}
}
}
}
// MARK: - UI Errors
private extension ViewController {
func addErrorView(with error: Error) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.view.addSubview(self.errorView)
let safeAreaLayoutGuide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
self.errorView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
self.errorView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
self.errorView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
self.errorView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
self.errorView.displayError(error)
}
}
func removeErrorView() {
if !view.subviews.contains(errorView) {
return
}
DispatchQueue.main.async {
self.errorView.removeFromSuperview()
}
}
}
| 958d3470ce8793d998405a517c9b9f43 | 30.889401 | 166 | 0.575867 | false | false | false | false |
kristoferdoman/Stormy | refs/heads/master | Stormy/Forecast.swift | mit | 2 | //
// Forecast.swift
// Stormy
//
// Created by Kristofer Doman on 2015-07-03.
// Copyright (c) 2015 Kristofer Doman. All rights reserved.
//
import Foundation
struct Forecast {
var currentWeather: CurrentWeather?
var weekly: [DailyWeather] = []
init(weatherDictionary: [String: AnyObject]?) {
if let currentWeatherDictionary = weatherDictionary?["currently"] as? [String: AnyObject] {
currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
}
if let weeklyWeatherArray = weatherDictionary?["daily"]?["data"] as? [[String: AnyObject]] {
for dailyWeather in weeklyWeatherArray {
let daily = DailyWeather(dailyWeatherDictionary: dailyWeather)
weekly.append(daily)
}
}
}
} | 108e3d5f3b4f116dfee19b7a04e3ef37 | 29.62963 | 100 | 0.639225 | false | false | false | false |
BGDigital/mcwa | refs/heads/master | mcwa/mcwa/rankinglistController.swift | mit | 1 | //
// rankinglistController.swift
// mcwa
//
// Created by XingfuQiu on 15/10/10.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class rankinglistController: UITableViewController {
let cellIdentifier = "rankinglistCell"
var isFirstLoad = true
var manager = AFHTTPRequestOperationManager()
var page: PageInfo!
var json: JSON! {
didSet {
if "ok" == self.json["state"].stringValue {
page = PageInfo(j: self.json["dataObject", "list", "pageBean"])
if let d = self.json["dataObject", "list", "data"].array {
if page.currentPage == 1 {
// println("刷新数据")
self.datasource = d
} else {
// println("加载更多")
self.datasource = self.datasource + d
}
}
//个人信息
self.user = self.json["dataObject", "user"]
}
}
}
var user: JSON?
var datasource: Array<JSON>! = Array() {
didSet {
if self.datasource.count < page.allCount {
self.tableView.footer.hidden = self.datasource.count < page.pageSize
print("没有达到最大值 \(self.tableView.footer.hidden)")
} else {
print("最大值了,noMoreData")
self.tableView.footer.endRefreshingWithNoMoreData()
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "排行榜"
self.view.layer.contents = UIImage(named: "other_bg")!.CGImage
self.tableView.header = MJRefreshNormalHeader(refreshingBlock: {self.loadNewData()})
self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: {self.loadMoreData()})
// 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()
loadNewData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadNewData() {
//开始刷新
//http://221.237.152.39:8081/interface.do?act=rankList&userId=1&page=1
self.pleaseWait()
let dict = ["act":"rankList", "userId": appUserIdSave, "page": 1]
manager.GET(URL_MC,
parameters: dict,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
//println(responseObject)
self.isFirstLoad = false
self.json = JSON(responseObject)
self.tableView.header.endRefreshing()
// self.hud?.hide(true)
self.clearAllNotice()
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.tableView.header.endRefreshing()
// self.hud?.hide(true)
self.clearAllNotice()
MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error)
})
}
func loadMoreData() {
// println("开始加载\(self.page.currentPage+1)页")
let dict = ["act":"rankList", "userId": appUserIdSave, "page": page.currentPage+1]
//println("加载:\(self.liveType),\(self.liveOrder)======")
//开始刷新
manager.GET(URL_MC,
parameters: dict,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
//println(responseObject)
self.json = JSON(responseObject)
self.tableView.footer.endRefreshing()
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.tableView.footer.endRefreshing()
MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error)
})
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if (!self.datasource.isEmpty) {
self.tableView.backgroundView = nil
return self.datasource.count
} else {
MCUtils.showEmptyView(self.tableView, aImg: UIImage(named: "empty_data")!, aText: "什么也没有,下拉刷新试试?")
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! rankinglistCell
// Configure the cell
let j = self.datasource[indexPath.row] as JSON
cell.update(j)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if appUserLogined {
return 56
} else {
return 0
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// var transform: CATransform3D
// transform = CATransform3DMakeRotation(CGFloat((90.0*M_PI) / 180), 0.0, 0.7, 0.4)
// transform.m34 = 1.0 / -600
//
// cell.layer.shadowColor = UIColor.blackColor().CGColor
// cell.layer.shadowOffset = CGSizeMake(10, 10)
// cell.alpha = 0
// cell.layer.transform = transform
// cell.layer.anchorPoint = CGPointMake(0, 0.5)
//
// UIView.beginAnimations("transform", context: nil)
// UIView.setAnimationDuration(0.5)
// cell.layer.transform = CATransform3DIdentity
// cell.alpha = 1
// cell.layer.shadowOffset = CGSizeMake(0, 0)
// cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height)
// UIView.commitAnimations()
//拉伸效果
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1, 1, 1)})
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (self.user == nil)
{
return nil
} else {
if appUserLogined {
let headView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 56))
headView.backgroundColor = UIColor(hexString: "#2C1B49")
//我的排名前面那个No.
let lb_no = UILabel(frame: CGRectMake(14, 8, 30, 17))
lb_no.textAlignment = .Center
lb_no.font = UIFont(name: lb_no.font.fontName, size: 13)
lb_no.textColor = UIColor.whiteColor()
lb_no.text = "No."
headView.addSubview(lb_no)
//我的排名
let lb_rankNo = UILabel(frame: CGRectMake(12, 25, 33, 24))
lb_rankNo.textAlignment = .Center
lb_rankNo.font = UIFont(name: lb_rankNo.font.fontName, size: 20)
lb_rankNo.textColor = UIColor.whiteColor()
lb_rankNo.text = self.user!["scoreRank"].stringValue
headView.addSubview(lb_rankNo)
//添加用户头像
let img_Avatar = UIImageView(frame: CGRectMake(56, 8, 40, 40))
let avater_Url = self.user!["headImg"].stringValue
print(avater_Url)
img_Avatar.yy_imageURL = NSURL(string: avater_Url)
// img_Avatar.yy_setImageWithURL(NSURL(string: avater_Url))
img_Avatar.layer.masksToBounds = true
img_Avatar.layer.cornerRadius = 20
headView.addSubview(img_Avatar)
//添加用户名称
let lb_userName = UILabel(frame: CGRectMake(104, 18, 186, 21))
lb_userName.textColor = UIColor.whiteColor()
lb_userName.text = "自己"//self.user!["nickName"].stringValue
headView.addSubview(lb_userName)
//添加用户分数
let lb_userSource = UILabel(frame: CGRectMake(tableView.bounds.size.width - 74, 18, 71, 21))
lb_userSource.textColor = UIColor.whiteColor()
lb_userSource.textAlignment = .Center
lb_userSource.text = self.user!["allScore"].stringValue+" 分"
headView.addSubview(lb_userSource)
return headView
} else {
return nil
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Delete the row from the data source
self.datasource.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func viewWillAppear(animated: Bool) {
MobClick.beginLogPageView("rankinglistController")
}
override func viewWillDisappear(animated: Bool) {
MobClick.endLogPageView("rankinglistController")
}
}
| 85a15ed35f44bc5182c30b35337ca42b | 39.086331 | 157 | 0.584261 | false | false | false | false |
bastienFalcou/FindMyContacts | refs/heads/master | ContactSyncing/Controllers/ContactsTableViewController.swift | mit | 1 | //
// ViewController.swift
// FindMyContacts
//
// Created by Bastien Falcou on 1/6/17.
// Copyright © 2017 Bastien Falcou. All rights reserved.
//
import UIKit
import ReactiveSwift
import DataSource
final class ContactsTableViewController: UITableViewController {
fileprivate let viewModel = ContactsTableViewModel()
fileprivate let tableDataSource = TableViewDataSource()
fileprivate let disposable = CompositeDisposable()
var syncedPhoneContacts: MutableProperty<Set<PhoneContact>> {
return self.viewModel.syncedPhoneContacts
}
var isSyncing: MutableProperty<Bool> {
return self.viewModel.isSyncing
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableDataSource.reuseIdentifierForItem = { _ in
return ContactTableViewCellModel.reuseIdentifier
}
self.tableView.dataSource = self.tableDataSource
self.tableView.delegate = self
self.tableDataSource.tableView = self.tableView
self.tableDataSource.dataSource.innerDataSource <~ self.viewModel.dataSource
self.reactive.isRefreshing <~ self.viewModel.isSyncing.skipRepeats()
self.refreshControl?.addTarget(self, action: #selector(handleRefresh(refreshControl:)), for: .valueChanged)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(notification:)), name: .UIApplicationWillEnterForeground, object: nil)
self.disposable += ContactFetcher.shared.isContactsPermissionGranted
.producer
.skipRepeats()
.startWithValues { [weak self] isPermissionGranted in
if isPermissionGranted {
self?.syncContactsProgrammatically()
}
}
}
deinit {
self.disposable.dispose()
}
func syncContactsProgrammatically() {
self.viewModel.syncContacts()
self.forceDisplayRefreshControl()
}
func removeAllContacts() {
self.viewModel.removeAllContacts()
}
@objc fileprivate func handleRefresh(refreshControl: UIRefreshControl) {
self.viewModel.syncContacts()
}
@objc fileprivate func applicationWillEnterForeground(notification: Foundation.Notification) {
if ContactFetcher.shared.isContactsPermissionGranted.value {
self.syncContactsProgrammatically()
}
}
}
extension ContactsTableViewController {
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let firstViewModel = self.tableDataSource.dataSource.item(at: IndexPath(row: 0, section: section)) as! ContactTableViewCellModel
let headerView = ContactTableHeaderView()
let text = firstViewModel.contact.hasBeenSeen ? firstViewModel.contact.dateAdded.readable : "new"
headerView.titleLabel?.text = text.uppercased()
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 28.0
}
}
| d2e1edebf85708f815aed16815c4b0e4 | 30.261364 | 168 | 0.785896 | false | false | false | false |
lerocha/ios-bootcamp-Flicks | refs/heads/master | Flicks/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// Flicks
//
// Created by Rocha, Luis on 4/1/17.
// Copyright © 2017 Luis Rocha. 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.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! FlicksViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing")
let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! FlicksViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = tabBarController
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:.
}
}
| 1ea8b1226692f8ca7c393366558879fb | 51.102941 | 285 | 0.751341 | false | false | false | false |
lee0741/Glider | refs/heads/master | Glider/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainController()
UINavigationBar.appearance().barTintColor = .mainColor
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
UITabBar.appearance().tintColor = .mainColor
let categoryItem = UIApplicationShortcutItem(type: "org.yancen.Glider.category", localizedTitle: "Categories", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "ic_option"), userInfo: nil)
let searchItem = UIApplicationShortcutItem(type: "org.yancen.Glider.search", localizedTitle: "Search", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .search), userInfo: nil)
UIApplication.shared.shortcutItems = [categoryItem, searchItem]
if let item = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
switch item.type {
case "org.yancen.Glider.category":
launchListController()
case "org.yancen.Glider.search":
launchSearchController()
default:
break
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
func applicationWillEnterForeground(_ application: UIApplication) {}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {}
// MARK: - Spotlight Search
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
(window?.rootViewController as! MainController).selectedIndex = 0
let viewController = (window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0] as! HomeController
viewController.restoreUserActivityState(userActivity)
return true
}
// MARK: - URL Scheme
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard let query = url.host else { return true }
let commentController = CommentController()
commentController.itemId = Int(query)
(window?.rootViewController as! MainController).selectedIndex = 0
(window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0].navigationController?.pushViewController(commentController, animated: true)
return true
}
// MARK: - 3D Touch
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
switch shortcutItem.type {
case "org.yancen.Glider.category":
launchListController()
case "org.yancen.Glider.search":
launchSearchController()
default:
return
}
}
func launchListController() {
(window?.rootViewController as! MainController).selectedIndex = 1
}
func launchSearchController() {
(window?.rootViewController as! MainController).selectedIndex = 2
}
}
| 9538829c4d986cae9f34bb3cc8e2a5c7 | 38.777778 | 222 | 0.678517 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Issues/Managing/IssueManagingModel.swift | mit | 1 | //
// IssueManagingModel.swift
// Freetime
//
// Created by Ryan Nystrom on 12/2/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueManagingModel: ListDiffable {
let objectId: String
let pullRequest: Bool
init(objectId: String, pullRequest: Bool) {
self.objectId = objectId
self.pullRequest = pullRequest
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
// should only ever be one
return "managing_model" as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? IssueManagingModel else { return false }
return pullRequest == object.pullRequest
&& objectId == object.objectId
}
}
| 7b6768d9eed60613a75c2e4225ae64e6 | 23.055556 | 78 | 0.660508 | false | false | false | false |
nerdycat/Cupcake | refs/heads/master | Cupcake/Color.swift | mit | 1 | //
// Color.swift
// Cupcake
//
// Created by nerdycat on 2017/3/17.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
/**
* Create UIColor Object.
* Color argument can be:
1) UIColor object
2) UIImage object, return a pattern image color
3) "red", "green", "blue", "clear", etc. (any system color)
5) "random": randomColor
6) "255,0,0": RGB color
7) "#FF0000" or "0xF00": Hex color
* All the string representation can have an optional alpha value.
* Usages:
Color([UIColor redColor])
Color("red")
Color("red,0.1") //with alpha
Color("255,0,0)
Color("255,0,0,1") //with alpha
Color("#FF0000")
Color("#F00,0.1") //with alpha
Color("random,0.5")
Color(Img("image")) //using image
...
*/
public func Color(_ any: Any?) -> UIColor? {
if any == nil {
return nil
}
if let color = any as? UIColor {
return color;
}
if let image = any as? UIImage {
return UIColor(patternImage: image)
}
guard any is String else {
return nil
}
var alpha: CGFloat = 1
var components = (any as! String).components(separatedBy: ",")
if components.count == 2 || components.count == 4 {
alpha = min(CGFloat(Float(components.last!) ?? 1), 1)
components.removeLast()
}
var r: Int?, g: Int? , b: Int?
if components.count == 1 {
let string = components.first!
let sel = NSSelectorFromString(string + "Color")
//system color
if let color = UIColor.cpk_safePerform(selector: sel) as? UIColor {
return (alpha == 1 ? color : color.withAlphaComponent(alpha))
}
if string == "random" {
// generate cryptographically secure random bytes
// avoid warnings reported by security scans like Veracode
// https://developer.apple.com/documentation/security/1399291-secrandomcopybytes
var bytes = [UInt8](repeating: 0, count: 3)
let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
if status == errSecSuccess {
r = Int(bytes[0])
g = Int(bytes[1])
b = Int(bytes[2])
} else {
r = 0
g = 0
b = 0
}
} else if string.hasPrefix("#") {
if string.cpk_length() == 4 {
r = Int(string.subAt(1), radix:16)! * 17
g = Int(string.subAt(2), radix:16)! * 17
b = Int(string.subAt(3), radix:16)! * 17
} else if string.cpk_length() == 7 {
r = Int(string.subAt(1...2), radix:16)
g = Int(string.subAt(3...4), radix:16)
b = Int(string.subAt(5...6), radix:16)
}
}
} else if components.count == 3 {
r = Int(components[0])
g = Int(components[1])
b = Int(components[2])
}
if r != nil && g != nil && b != nil {
return UIColor(red: CGFloat(r!) / 255.0,
green: CGFloat(g!) / 255.0,
blue: CGFloat(b!) / 255.0,
alpha: alpha)
}
return nil
}
| 4c7c36d20c7f37d2e2189b4dc143f115 | 27.529915 | 92 | 0.501198 | false | false | false | false |
CoderLiLe/Swift | refs/heads/master | 字典/main.swift | mit | 1 | //
// main.swift
// 字典
//
// Created by LiLe on 15/2/28.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
字典定义: 键值对
OC:
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"lnj" forKey:@"name"];
NSLog(@"%@", dict);
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"name", @"lnj", @"age", @30, nil];
NSLog(@"%@", dict);
NSDictionary *dict = @{@"name":@"lnj", @"age":@30};
NSLog(@"%@", dict);
*/
// key一定要是可以hash的(String, Int, Float, Double, Bool), value没有要求
var dict = ["name":"lnj", "age":30]
print(dict)
var dict1:Dictionary = ["name":"lnj", "age":30]
print(dict1)
var dict2:Dictionary<String,Any> = ["name":"lnj", "age":30]
print(dict2)
var dict3:[String:Any] = ["name":"lnj", "age":30]
print(dict3)
var dict4:[String:Any] = Dictionary(dictionaryLiteral: ("name", "lnj"), ("age", 30))
print(dict4)
//不可变数组:
var dict5 = [:]
//可变数组:
let dict6 = [:]
/*
字典操作
OC:
1.获取
NSDictionary *dict = @{@"name":@"lnj", @"age":@30};
NSLog(@"%@", dict[@"name"]);
2.修改
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name", @"lnj", @"age", @30, nil];
dict[@"name"] = @"iversion";
NSLog(@"%@", dict[@"name"]);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name", @"lnj", @"age", @30, nil];
[dict setObject:@"iversion" forKey:@"name"];
NSLog(@"%@", dict[@"name"]);
*/
//1.获取
var dict7 = ["name":"lnj", "age":30]
print(dict7["name"]!)
//2.修改
var dict8 = ["name":"lnj", "age":30]
dict8["name"] = "iverson"
print(dict8["name"]!)
var dict9 = ["name":"lnj", "age":30]
dict9.updateValue("iverson", forKey: "name")
print(dict9["name"]!)
// 3.更新
// updateValue返回一个可选类型, 如果字典中不存在需要更新的key, 那么返回nil, 如果存在返回原始值
var dict10 = ["name":"lnj", "age":30]
if let orignal = dict10.updateValue("iverson", forKey: "name")
{
print(dict10["name"]!)
print(orignal)
}
// updateValue返回一个可选类型, 如果字典中不存在需要更新的key, 那么返回nil并且会将新的键值对添加到字典中
var dict11 = ["name":"lnj", "age":30]
if let orignal = dict11.updateValue("iverson", forKey: "abc")
{
print(dict11["abc"]!)
print(orignal)
}
print(dict11)
/*
4.添加
OC:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name", @"lnj", @"age", @30, nil];
dict[@"height"] = @175;
NSLog(@"%@", dict);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"name", @"lnj", @"age", @30, nil];
[dict setObject:@175 forKey:@"height"];
NSLog(@"%@", dict);
*/
var dict12 = ["name":"lnj", "age":30]
dict12["height"] = 175;
print(dict12)
/*
5.删除
OC:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @30, @"age", nil];
[dict removeObjectForKey:@"name"];
NSLog(@"%@", dict);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @30, @"age", nil];
[dict removeAllObjects];
NSLog(@"%@", dict);
*/
var dict13 = ["name":"lnj", "age":30]
dict13.removeValueForKey("name")
print(dict13)
// removeValueForKey返回一个可选类型, 如果字典中不存在需要删除的key, 那么返回nil并且不会执行任何操作, 如果存在则删除key对应的值, 并且返回被删除的值
var dict14 = ["name":"lnj", "age":30]
if let orignal = dict14.removeValueForKey("names")
{
print(dict14)
print(orignal)
}
print(dict14)
var dict15 = ["name":"lnj", "age":30]
dict15.removeAll(keepCapacity: true)
/*
遍历字典
OC:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @30, @"age", nil];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key = %@ value = %@", key, obj);
}];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @30, @"age", nil];
NSArray *keys = [dict allKeys];
for (NSString *key in keys) {
NSLog(@"%@", key);
}
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @30, @"age", nil];
NSArray *values = [dict allValues];
for (NSString *value in values) {
NSLog(@"%@", value);
}
*/
var dict16 = ["name":"lnj", "age":30]
for (key , value) in dict16
{
print("key = \(key) value = \(value)")
}
var dict17 = ["name":"lnj", "age":30]
for key in dict17.keys
{
print("key = \(key)")
}
var dict18 = ["name":"lnj", "age":30]
for value in dict18.values
{
print("value = \(value)")
}
| 5d7f748f0d66645db9400f13ac89f966 | 23.275862 | 113 | 0.652225 | false | false | false | false |
admkopec/BetaOS | refs/heads/x86_64 | Kernel/Kernel/System.swift | apache-2.0 | 1 | //
// System.swift
// Kernel
//
// Created by Adam Kopeć on 11/13/17.
// Copyright © 2017-2018 Adam Kopeć. All rights reserved.
//
import Loggable
final class System: Loggable {
static let sharedInstance = System()
let Name: String = "System"
let modulesController = ModulesController()
fileprivate(set) var interruptManager: InterruptManager!
fileprivate(set) var Timer: PIT8254?
fileprivate(set) var DeviceVendor = "Generic"
fileprivate(set) var DeviceName = "Generic Device"
fileprivate(set) var DeviceID = "Generic1,1"
fileprivate(set) var SerialNumber = "000000000000"
internal var Video: VideoModule = VESA()
internal var Drives = [PartitionTable]()
internal var ACPI: ACPI? {
return modulesController.modules.filter { $0 is ACPI }.first as? ACPI
}
internal var SMBIOS: SMBIOS? {
return modulesController.modules.filter { $0 is SMBIOS }.first as? SMBIOS
}
func initialize() {
modulesController.initialize()
interruptManager = InterruptManager(acpiTables: ACPI)
DeviceVendor = SMBIOS?.SystemVendor ?? DeviceVendor
DeviceName = SMBIOS?.ProductDisplayName ?? DeviceName
DeviceID = SMBIOS?.ProductName ?? DeviceID
SerialNumber = SMBIOS?.ProductSerial ?? SerialNumber
interruptManager.enableIRQs()
Timer = PIT8254()
if DeviceID == "VMware7,1" {
modulesController.modules.append(VMwareTools())
}
modulesController.companionController = PCIModulesController()
}
internal func shutdown() {
modulesController.stop()
shutdown_system()
}
}
public func NullHandler(irq: Int) {
}
| 785def9e99fc057df364781d238b0594 | 29.859649 | 81 | 0.646958 | false | false | false | false |
TransitionKit/Union | refs/heads/master | Union/Navigator.swift | mit | 1 | //
// Navigator.swift
// Union
//
// Created by Hirohisa Kawasaki on 10/7/15.
// Copyright © 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public class Navigator: NSObject {
let before = AnimationManager()
let present = AnimationManager()
var duration: NSTimeInterval {
return before.duration + present.duration
}
func animate(transitionContext: UIViewControllerContextTransitioning) {
setup(transitionContext)
start(transitionContext)
}
public class func animate() -> UIViewControllerAnimatedTransitioning {
return Navigator()
}
}
extension Navigator: UIViewControllerAnimatedTransitioning {
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
animate(transitionContext)
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
}
extension Navigator {
func setup(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
if let fromViewController = fromViewController, let toViewController = toViewController {
_setup(fromViewController: fromViewController, toViewController: toViewController)
}
}
func start(transitionContext: UIViewControllerContextTransitioning) {
before.completion = { [unowned self] in
self.startTransition(transitionContext)
}
before.start()
}
func startTransition(transitionContext: UIViewControllerContextTransitioning) {
if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey), let toView = transitionContext.viewForKey(UITransitionContextToViewKey) {
toView.frame = fromView.frame
transitionContext.containerView()?.insertSubview(toView, aboveSubview: fromView)
}
present.completion = {
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
fromView?.removeFromSuperview()
transitionContext.completeTransition(true)
}
present.start()
}
private func _setup(fromViewController fromViewController: UIViewController, toViewController: UIViewController) {
if let delegate = fromViewController as? Delegate {
before.animations = delegate.animationsBeforeTransition(from: fromViewController, to: toViewController)
}
// present
let fromAnimations: [Animation] = (fromViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
let toAnimations: [Animation] = (toViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
present.animations = fromAnimations + toAnimations
}
} | 90464c9777051b0af22eb239374d0b20 | 34.287356 | 161 | 0.72825 | false | false | false | false |
idomizrachi/Regen | refs/heads/master | regen/main.swift | mit | 1 | //
// main.swift
// Regen
//
// Created by Ido Mizrachi on 7/7/16.
//
import Foundation
let operationTimer = OperationTimer()
operationTimer.start()
let arguments = Array(CommandLine.arguments.dropFirst())
let argumentsParser = ArgumentsParser(arguments: arguments)
switch argumentsParser.operationType {
case .version:
Version.display()
case .usage:
Usage.display()
case .localization(let parameters):
let operation = Localization.Operation(parameters: parameters)
operation.run()
print("Finished in: \(String(format: "%.5f", operationTimer.end())) seconds.")
case .images(let parameters):
let operation = Images.Operation(parameters: parameters)
operation.run()
print("Finished in: \(String(format: "%.5f", operationTimer.end())) seconds.")
}
| 98e1c95bf1926f2f7ffa7c0ce1a71f44 | 23.65625 | 82 | 0.716096 | false | false | false | false |
SwiftGen/SwiftGenKit | refs/heads/master | Tests/SwiftGenKitTests/ColorsJSONFileTests.swift | mit | 1 | //
// SwiftGenKit
// Copyright (c) 2017 Olivier Halligon
// MIT Licence
//
import XCTest
import PathKit
@testable import SwiftGenKit
class ColorsJSONFileTests: XCTestCase {
func testFileWithDefaults() throws {
let parser = ColorsParser()
parser.palettes = [try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "colors.json", sub: .colors))]
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "defaults.plist", sub: .colors)
}
func testFileWithBadSyntax() {
do {
_ = try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "bad-syntax.json", sub: .colors))
XCTFail("Code did parse file successfully while it was expected to fail for bad syntax")
} catch ColorsParserError.invalidFile {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
func testFileWithBadValue() {
do {
_ = try ColorsJSONFileParser().parseFile(at: Fixtures.path(for: "bad-value.json", sub: .colors))
XCTFail("Code did parse file successfully while it was expected to fail for bad value")
} catch ColorsParserError.invalidHexColor(path: _, string: "this isn't a color", key: "ArticleTitle"?) {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
}
| b845cde2cd6e3ad80b6880a85b3beecd | 33.780488 | 113 | 0.692146 | false | true | false | false |
BennyKJohnson/OpenCloudKit | refs/heads/master | Sources/CKContainer.swift | mit | 1 | //
// CKContainer.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 6/07/2016.
//
//
import Foundation
public class CKContainer {
let convenienceOperationQueue = OperationQueue()
public let containerIdentifier: String
public init(containerIdentifier: String) {
self.containerIdentifier = containerIdentifier
}
public class func `default`() -> CKContainer {
// Get Default Container
return CKContainer(containerIdentifier: CloudKit.shared.containers.first!.containerIdentifier)
}
public lazy var publicCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .public)
}()
public lazy var privateCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .private)
}()
public lazy var sharedCloudDatabase: CKDatabase = {
return CKDatabase(container: self, scope: .shared)
}()
var isRegisteredForNotifications: Bool {
return false
}
func registerForNotifications() {}
func accountStatus(completionHandler: @escaping (CKAccountStatus, Error?) -> Void) {
guard let _ = CloudKit.shared.defaultAccount.iCloudAuthToken else {
completionHandler(.noAccount, nil)
return
}
// Verify the account is valid
completionHandler(.available, nil)
}
func schedule(convenienceOperation: CKOperation) {
convenienceOperation.queuePriority = .veryHigh
convenienceOperation.qualityOfService = .utility
add(convenienceOperation)
}
public func add(_ operation: CKOperation) {
if !(operation is CKDatabaseOperation) {
operation.container = self
convenienceOperationQueue.addOperation(operation)
} else {
fatalError("CKDatabaseOperations must be submitted to a CKDatabase")
}
}
}
| e2c1fb01e08897a2e7c5f50d0b6c5510 | 25.890411 | 102 | 0.643403 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/expr/closure/basic.swift | apache-2.0 | 9 | // RUN: %target-parse-verify-swift
func takeIntToInt(f: (Int) -> Int) { }
func takeIntIntToInt(f: (Int, Int) -> Int) { }
// Simple closures
func simple() {
takeIntToInt({(x: Int) -> Int in
return x + 1
})
takeIntIntToInt({(x: Int, y: Int) -> Int in
return x + y
})
}
// Closures with variadic argument lists
func variadic() {
var f = {(start: Int, rest: Int...) -> Int in
var result = start
for x in rest {
result += x
}
return result
}
f(1)
f(1, 2)
f(1, 3)
let D = { (Ss ...) in 1 } // expected-error{{'...' cannot be applied to a subpattern which is not explicitly typed}}, expected-error{{unable to infer closure return type in current context}}
}
// Closures with attributes in the parameter list.
func attrs() {
_ = {(inout z: Int) -> Int in z }
}
// Closures with argument and parameter names.
func argAndParamNames() -> Int {
let f1: (x: Int, y: Int) -> Int = { (a x, b y) in x + y }
f1(x: 1, y: 2)
return f1(x: 1, y: 2)
}
| 6288c4bf347434ffcac3948e67a6b8cc | 22.666667 | 192 | 0.589537 | false | false | false | false |
dche/FlatCG | refs/heads/master | Sources/Pose.swift | mit | 1 | //
// FlatCG - Pose.swift
//
// Copyright (c) 2016 The FlatCG authors.
// Licensed under MIT License.
import simd
import GLMath
/// Types that describe poses of solid bodies in Euclidean space.
///
/// This type just records the amount of rotation from initial pose to the
/// final pose. How the rotation is performed is determined by the concrete
/// `RotationType`.
public protocol Pose: Equatable, CustomDebugStringConvertible {
associatedtype PointType: Point
associatedtype RotationType: Rotation
/// Position.
var position: PointType { get set }
/// Amount of rotation from initial pose.
var rotation: RotationType { get set }
typealias DirectionType = Normal<PointType>
static var initialDirection: DirectionType { get }
static var initialRightDirection: DirectionType { get }
/// Forward direction.
var direction: DirectionType { get set }
/// Right direction.
var rightDirection: DirectionType { get set }
//
// var objectToWorldTransform: Transform<PointType> { get }
/// Sets the forward direction to the vector from `position` to `at`.
mutating func look(at: PointType)
}
extension Pose {
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.position == rhs.position && lhs.rotation == rhs.rotation
}
public var debugDescription: String {
return "Pose(position: \(self.position), rotation: \(self.rotation))"
}
}
extension Pose {
/// Changes `self`'s `position` to `point`.
mutating public func move(to point: PointType) {
self.position = point
}
/// Moves `self` from current position with `vector`'s direciton and
/// length.
mutating public func move(_ vector: PointType.VectorType) {
self.move(to: self.position + vector)
}
}
extension Pose where PointType.VectorType: FloatVector2 {
/// Moves `self` along the `X` axis.
mutating public func move(x: PointType.VectorType.Component) {
self.move(PointType.VectorType(x, PointType.VectorType.Component.zero))
}
/// Moves `self` along the `Y` axis.
mutating public func move(y: PointType.VectorType.Component) {
self.move(PointType.VectorType(PointType.VectorType.Component.zero, y))
}
}
extension Pose where PointType.VectorType: FloatVector3 {
/// Moves `self` along the `X` axis.
mutating public func move(x: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(x, zero, zero))
}
/// Moves `self` along the `Y` axis.
mutating public func move(y: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(zero, y, zero))
}
/// Moves `self` along the `Z` axis.
mutating public func move(z: PointType.VectorType.Component) {
let zero = PointType.VectorType.Component.zero
self.move(PointType.VectorType(zero, zero, z))
}
}
extension Pose {
/// Changes `self`'s `rotation` to a new value given by `rotation`.
mutating public func rotate(to rotation: RotationType) {
self.rotation = rotation
}
/// Adds `amount` of rotation to `self`.
mutating public func rotate(_ amount: RotationType) {
self.rotate(to: self.rotation.compose(amount))
}
}
extension Pose where RotationType == Quaternion {
mutating public func pitch(_ radian: Float) {
self.rotate(Quaternion.pitch(radian))
}
mutating public func yaw(_ radian: Float) {
self.rotate(Quaternion.yaw(radian))
}
mutating public func roll(_ radian: Float) {
self.rotate(Quaternion.roll(radian))
}
}
extension Pose where PointType == RotationType.PointType {
mutating public func move(forward distance: DirectionType.Component) {
move(direction.vector * distance)
}
mutating public func move(backward distance: DirectionType.Component) {
move(forward: -distance)
}
mutating public func move(right distance: DirectionType.Component) {
move(rightDirection.vector * distance)
}
mutating public func move(left distance: DirectionType.Component) {
move(right: -distance)
}
}
///
public protocol HasPose: Pose {
associatedtype PoseType: Pose
var pose: PoseType { get set }
}
extension HasPose where PointType == PoseType.PointType {
public var position: PointType {
get { return pose.position }
set { pose.position = newValue }
}
public mutating func look(at point: PointType) {
pose.look(at: point)
}
}
extension HasPose where PointType == PoseType.PointType, RotationType == PoseType.RotationType {
public var rotation: RotationType {
get { return pose.rotation }
set { pose.rotation = newValue }
}
public var direction: DirectionType {
get {
return pose.direction
}
set {
pose.direction = newValue
}
}
public var rightDirection: DirectionType {
get {
return pose.rightDirection
}
set {
pose.rightDirection = newValue
}
}
public static var initialDirection: DirectionType {
return PoseType.initialDirection
}
public static var initialRightDirection: DirectionType {
return PoseType.initialRightDirection
}
}
/// Pose in 2D Euclidean space.
public struct Pose2D: Pose {
public typealias PointType = Point2D
public typealias RotationType = Rotation2D
public var position: Point2D
public var rotation: Rotation2D
public var direction: Normal2D {
get {
return Normal(vector: rotation.apply(Pose2D.initialDirection.vector))
}
set {
let v = newValue.vector
let theta = atan2(v.y, v.x) + .tau - .half_pi
self.rotation = Rotation2D(angle: theta)
}
}
public var rightDirection: Normal2D {
get {
return Normal<Point2D>(vector: rotation.apply(Pose2D.initialRightDirection.vector))
}
set {
let v = newValue.vector
let theta = atan2(v.y, v.x) + .tau
self.rotation = Rotation2D(angle: theta)
}
}
public mutating func look(at point: Point2D) {
self.direction = Normal(vector: point - self.position)
}
public static let initialDirection = Normal<Point2D>(vec2(0, 1))
public static let initialRightDirection = Normal<Point2D>(vec2(1, 0))
public init () {
self.position = Point2D.origin
self.rotation = Rotation2D.identity
}
}
/// Pose in 3D Euclidean space.
public struct Pose3D: Pose {
public typealias PointType = Point3D
public typealias RotationType = Quaternion
public var position: Point3D
public var rotation: Quaternion
mutating public func move(upward distance: Float) {
move(upDirection.vector * distance)
}
mutating public func move(downward distance: Float) {
move(upward: -distance)
}
public var direction: Normal3D {
get {
return Normal(vector: rotation.apply(Pose3D.initialDirection.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.direction, to: newValue))
}
}
public var rightDirection: Normal3D {
get {
return Normal(vector: rotation.apply(Pose3D.initialRightDirection.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.rightDirection, to: newValue))
}
}
public var upDirection: Normal3D {
get {
return Normal(vector: cross(rightDirection.vector, direction.vector))
}
set {
self.rotate(Quaternion(fromDirection: self.upDirection, to: newValue))
}
}
public mutating func look(at point: Point3D) {
self.direction = Normal(vector: point - self.position)
}
public static let initialDirection = Normal<Point3D>(vec3(0, 0, -1))
public static let initialRightDirection = Normal<Point3D>(vec3(1, 0, 0))
public init () {
self.position = Point3D.origin
self.rotation = Quaternion.identity
}
}
extension HasPose where PoseType == Pose3D, PointType == Point3D, RotationType == Quaternion {
public var upDirection: DirectionType {
get {
return pose.upDirection
}
set {
pose.upDirection = newValue
}
}
}
| 807f088d5806559d953055fb0660efc5 | 25.57764 | 96 | 0.643608 | false | false | false | false |
livingincode/ios-exercises | refs/heads/master | SwiftExercises.playground/section-1.swift | mit | 1 | import UIKit
/*
Strings
*/
func favoriteCheeseStringWithCheese(cheese: String) -> String {
return "My favorite cheese is " + cheese
}
let fullSentence = favoriteCheeseStringWithCheese("cheddar")
// Make fullSentence say "My favorite cheese is cheddar."
/*
Arrays & Dictionaries
*/
// Add 5 to this array
//let numberDictionary = [1 : "one", 2 : "two", 3 : "three", 4 : "four"]
// Add 5 : "five" to this dictionary
var numberArray = [1, 2, 3, 4]
numberArray.append(5)
var numberDictionary = [1 : "one", 2: "two", 3 : "three", 4 : "four"]
numberDictionary [5] = "five"
/*
Loops
*/
// Use a closed range loop to print 1 - 10, inclusively
// WORK HERE
for number in 1...10 {
println(number)
}
// Use a half-closed range loop to print 1 - 10, inclusively
// WORK HERE
for number in 1..<10 {
println(number)
}
let worf = [
"name": "Worf",
"rank": "lieutenant",
"information": "son of Mogh, slayer of Gowron",
"favorite drink": "prune juice",
"quote" : "Today is a good day to die."]
let picard = [
"name": "Jean-Luc Picard",
"rank": "captain",
"information": "Captain of the USS Enterprise",
"favorite drink": "tea, Earl Grey, hot"]
let characters = [worf, picard]
func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> {
// return an array of favorite drinks, like ["prune juice", "tea, Earl Grey, hot"]
return ["prune juice", "tea, Earl grey, hot"]
}
let favoriteDrinks = favoriteDrinksArrayForCharacters(characters)
favoriteDrinks
/*
Functions
*/
// Make a function that inputs an array of strings and outputs the strings separated by a semicolon
let strings = ["milk", "eggs", "bread", "challah"]
// WORK HERE - make your function and pass `strings` in
func output(stringArray:[String]) -> String{
let string = ";".join(stringArray)
return string
}
output(strings)
let expectedOutput = "milk;eggs;bread;challah"
/*
Closures
*/
let cerealArray = ["Golden Grahams", "Cheerios", "Trix", "Cap'n Crunch OOPS! All Berries", "Cookie Crisp"]
// Use a closure to sort this array alphabetically
// WORK HERE
sorted(cerealArray, {
return $0 < $1
})
| c1bf332fc349b3931d3deb6c325e6d79 | 16.666667 | 106 | 0.654088 | false | false | false | false |
RedRoma/Lexis | refs/heads/develop | Code/Lexis/Cells/ImageCell.swift | apache-2.0 | 1 | //
// ImageCell.swift
// Lexis
//
// Created by Wellington Moreno on 9/25/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import UIKit
class ImageCell: UITableViewCell
{
@IBOutlet weak var cardView: LexisView!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var cardLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var cardTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var photoHeightConstraint: NSLayoutConstraint!
private var pressGesture: UILongPressGestureRecognizer! = nil
private var onLongPress: ((ImageCell) -> Void)?
func setupLongPressGesture(callback: @escaping (ImageCell) -> Void)
{
removeLongPressGesture()
self.onLongPress = callback
self.pressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.onLongPressGesture(gesture:)))
self.addGestureRecognizer(pressGesture)
}
@objc
private func removeLongPressGesture()
{
if let existingGesture = pressGesture
{
self.removeGestureRecognizer(existingGesture)
}
onLongPress = nil
}
@objc
private func onLongPressGesture(gesture: UIGestureRecognizer)
{
onLongPress?(self)
}
}
| 67ca2bed991a6cedaf52a1633b775ace | 25.632653 | 124 | 0.689655 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Rules/Style/IdentifierNameRule.swift | mit | 1 | import Foundation
import SourceKittenFramework
struct IdentifierNameRule: ASTRule, ConfigurationProviderRule {
var configuration = NameConfiguration(minLengthWarning: 3,
minLengthError: 2,
maxLengthWarning: 40,
maxLengthError: 60,
excluded: ["id"])
init() {}
static let description = RuleDescription(
identifier: "identifier_name",
name: "Identifier Name",
description: "Identifier names should only contain alphanumeric characters and " +
"start with a lowercase character or should only contain capital letters. " +
"In an exception to the above, variable names may start with a capital letter " +
"when they are declared static and immutable. Variable names should not be too " +
"long or too short.",
kind: .style,
nonTriggeringExamples: IdentifierNameRuleExamples.nonTriggeringExamples,
triggeringExamples: IdentifierNameRuleExamples.triggeringExamples,
deprecatedAliases: ["variable_name"]
)
func validate(
file: SwiftLintFile,
kind: SwiftDeclarationKind,
dictionary: SourceKittenDictionary
) -> [StyleViolation] {
guard !dictionary.enclosedSwiftAttributes.contains(.override) else {
return []
}
return validateName(dictionary: dictionary, kind: kind).map { name, offset in
guard !configuration.excluded.contains(name), let firstCharacter = name.first else {
return []
}
let isFunction = SwiftDeclarationKind.functionKinds.contains(kind)
let description = Self.description
let type = self.type(for: kind)
if !isFunction {
let allowedSymbols = configuration.allowedSymbols.union(.alphanumerics)
if !allowedSymbols.isSuperset(of: CharacterSet(charactersIn: name)) {
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: "\(type) name should only contain alphanumeric " +
"characters: '\(name)'")
]
}
if let severity = severity(forLength: name.count) {
let reason = "\(type) name should be between " +
"\(configuration.minLengthThreshold) and " +
"\(configuration.maxLengthThreshold) characters long: '\(name)'"
return [
StyleViolation(ruleDescription: Self.description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
}
let firstCharacterIsAllowed = configuration.allowedSymbols
.isSuperset(of: CharacterSet(charactersIn: String(firstCharacter)))
guard !firstCharacterIsAllowed else {
return []
}
let requiresCaseCheck = configuration.validatesStartWithLowercase
if requiresCaseCheck &&
kind != .varStatic && name.isViolatingCase && !name.isOperator {
let reason = "\(type) name should start with a lowercase character: '\(name)'"
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
return []
} ?? []
}
private func validateName(
dictionary: SourceKittenDictionary,
kind: SwiftDeclarationKind
) -> (name: String, offset: ByteCount)? {
guard
var name = dictionary.name,
let offset = dictionary.offset,
kinds.contains(kind),
!name.hasPrefix("$")
else { return nil }
if
kind == .enumelement,
let parenIndex = name.firstIndex(of: "("),
parenIndex > name.startIndex
{
let index = name.index(before: parenIndex)
name = String(name[...index])
}
return (name.nameStrippingLeadingUnderscoreIfPrivate(dictionary), offset)
}
private let kinds: Set<SwiftDeclarationKind> = {
return SwiftDeclarationKind.variableKinds
.union(SwiftDeclarationKind.functionKinds)
.union([.enumelement])
}()
private func type(for kind: SwiftDeclarationKind) -> String {
if SwiftDeclarationKind.functionKinds.contains(kind) {
return "Function"
} else if kind == .enumelement {
return "Enum element"
} else {
return "Variable"
}
}
}
private extension String {
var isViolatingCase: Bool {
let firstCharacter = String(self[startIndex])
guard firstCharacter.isUppercase() else {
return false
}
guard count > 1 else {
return true
}
let secondCharacter = String(self[index(after: startIndex)])
return secondCharacter.isLowercase()
}
var isOperator: Bool {
let operators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", ".", "%", "<", ">", "&"]
return operators.contains(where: hasPrefix)
}
}
| a856a5e836733fcc4bd2b90abecc855a | 38.283784 | 99 | 0.535432 | false | true | false | false |
maletzt/Alien-Adventure | refs/heads/master | Alien Adventure/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - SettingsViewController: UIViewController
class SettingsViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var levelSegmentedControl: UISegmentedControl!
@IBOutlet weak var startGameButton: UIButton!
@IBOutlet weak var showBadgesLabel: UILabel!
@IBOutlet weak var showBadgesSwitch: UISwitch!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let attributesDictionary: [String:AnyObject] = [
NSFontAttributeName: UIFont(name: Settings.Common.Font, size: 18)!
]
titleLabel.font = UIFont(name: Settings.Common.Font, size: 32)
showBadgesLabel.font = UIFont(name: Settings.Common.Font, size: 20)
showBadgesSwitch.onTintColor = UIColor.magentaColor()
levelSegmentedControl.setTitleTextAttributes(attributesDictionary, forState: .Normal)
Settings.Common.Level = levelSegmentedControl.selectedSegmentIndex
startGameButton.titleLabel?.font = UIFont(name: Settings.Common.Font, size: 20)
addTargets()
}
// MARK: Add Targets
func addTargets() {
startGameButton.addTarget(self, action: #selector(SettingsViewController.startGame), forControlEvents: .TouchUpInside)
showBadgesSwitch.addTarget(self, action: #selector(SettingsViewController.showBadges(_:)), forControlEvents: .ValueChanged)
levelSegmentedControl.addTarget(self, action: #selector(SettingsViewController.switchLevel(_:)), forControlEvents: .ValueChanged)
}
// MARK: Implementing Actions
func switchLevel(segmentControl: UISegmentedControl) {
Settings.Common.Level = segmentControl.selectedSegmentIndex
}
func showBadges(switchControl: UISwitch) {
if switchControl.on == true {
Settings.Common.ShowBadges = switchControl.on
}
}
func startGame() {
let alienAdventureViewController = self.storyboard!.instantiateViewControllerWithIdentifier("AlienAdventureViewController") as! AlienAdventureViewController
self.presentViewController(alienAdventureViewController, animated: true, completion: nil)
}
} | b8f96f55aef192ed1cf6e69c4f921dcd | 34.385714 | 164 | 0.690226 | false | false | false | false |
Bartlebys/Bartleby | refs/heads/master | BartlebysUI/BartlebysUI/DropView.swift | apache-2.0 | 1 | //
// DropView.swift
// BartlebysUI
//
// Created by Benoit Pereira da silva on 02/11/2016.
//
import Foundation
import AppKit
extension Notification.Name {
public struct DropView {
/// Posted on dropped url if there not dropDelegate set
/// The urls are passed in userInfos["urls"]
public static let droppedUrls = Notification.Name(rawValue: "org.bartlebys.notification.DropView.droppedUrls")
}
}
// The delegate that handles the droppedURLs
public protocol DropDelegate {
/// Passes the validated URLs
///
/// - Parameter urls: the URLs
func droppedURLs(urls:[URL],dropZoneIdentifier:String)
}
// An View with Delegated Drop support
// You should setup dropDelegate,supportedUTTypes, and optionaly dropZoneIdentifier/Users/bpds/Desktop/Un gros insecte.mov
open class DropView:NSView{
// MARK: Properties
@IBInspectable
open var backgroundColor: NSColor? {
didSet {
self.needsDisplay = true
}
}
@IBInspectable
open var highLightOnRollOver: Bool = true
// MARK: Drawings
open override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard let color = self.backgroundColor else {return}
color.setFill()
__NSRectFill(self.bounds)
}
// You can specify a zone identifier
public var dropZoneIdentifier:String=""
// Should return for example: [kUTTypeMovie as String,kUTTypeVideo as String]
public var supportedUTTypes:[String]?
//If set to true the paths that are not matching the supportedUTTypes are excluded
//else in case of unsupported UTTypes all the drop is cancelled
public var filterIrreleventUTTypes:Bool=true
// You setup the drop Delegate that will handle the URLs
public var dropDelegate:DropDelegate?
// Temp alpha storage
private var _alphas=[Int:CGFloat]()
// Active zone
private var _active:Bool=false{
didSet {
if self.highLightOnRollOver{
//needsDisplay = true
if _active==true{
self.subviews.forEach({ (view) in
self._alphas[view.hashValue]=view.alphaValue
view.alphaValue=0.30
})
}else{
self.subviews.forEach({ (view) in
view.alphaValue = self._alphas[view.hashValue] ?? 1.0
})
self._alphas.removeAll()
}
}
}
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.registerForDraggedTypes([NSPasteboard.PasteboardType("NSFilenamesPboardType"), NSPasteboard.PasteboardType("NSFontPboardType")])
}
internal var _fileTypeAreOk = false
internal var _droppedFilesPaths: [String]?{
didSet{
if let paths=_droppedFilesPaths{
var urls=[URL]()
for path in paths{
let url=URL(fileURLWithPath: path)
urls.append(url)
}
if let delegate=self.dropDelegate{
delegate.droppedURLs(urls: urls,dropZoneIdentifier:dropZoneIdentifier)
}else{
let notification = Notification(name: Notification.Name.DropView.droppedUrls, object: self.window, userInfo: ["urls":urls,"identifier":dropZoneIdentifier])
NotificationCenter.default.post(notification)
}
}
}
}
override open func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if self._checkValidity(drag: sender) {
self._fileTypeAreOk = true
self._active = true
return .copy
} else {
self._fileTypeAreOk = false
self._active = false
return []
}
}
override open func draggingExited(_ sender: NSDraggingInfo?) {
self._active = false
}
override open func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
if self._fileTypeAreOk {
return .copy
} else {
return []
}
}
override open func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let paths = sender.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]{
if self.filterIrreleventUTTypes==false{
self._droppedFilesPaths = paths
}else{
// Filter the irrelevent paths
var validPaths=[String]()
for path in paths{
let url=URL(fileURLWithPath: path)
if self._isSupported(url){
validPaths.append(path)
}
}
self._droppedFilesPaths = validPaths
}
self._active = false
return true
}
return false
}
private func _checkValidity(drag: NSDraggingInfo) -> Bool {
if let paths = drag.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]{
var isValid = (self.filterIrreleventUTTypes==true) ? false : true
for path in paths{
let url=URL(fileURLWithPath: path)
if self.filterIrreleventUTTypes{
// Inclusive logic if there at least one valid element when consider the drop valid
isValid = isValid || self._isSupported(url)
}else{
// Exclusive logic
isValid = isValid && self._isSupported(url)
}
}
return isValid
}
return false
}
private func _isSupported(_ url:URL)->Bool{
if let supportedUTTypes=self.supportedUTTypes{
let pathExtension:CFString = url.pathExtension as CFString
let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil);
if let fileUTI = unmanagedFileUTI?.takeRetainedValue(){
for t in supportedUTTypes{
let cft:CFString = t as CFString
if UTTypeConformsTo(fileUTI,cft){
return true
}
}
}
}
return false
}
}
| cb73627d9f74fa8003e1edaa007048d9 | 30.451456 | 175 | 0.578639 | false | false | false | false |
bromas/StrategicControllers | refs/heads/master | StrategySample/MovableStrategy.swift | mit | 1 | //
// RedStrategy.swift
// StrategyPattern
//
// Created by Brian Thomas on 10/22/14.
// Copyright (c) 2014 Brian Thomas. All rights reserved.
//
import Foundation
import StrategicControllers
import UIKit
typealias MovableStrategy = movableStrategy<Int>
class movableStrategy<T> : ControllerStrategy<ColorViewController> {
var view : UIView = UIView()
var leftConstraint : NSLayoutConstraint?
var topConstraint : NSLayoutConstraint?
let startingColor : UIColor
init(color: UIColor) {
startingColor = color
super.init()
}
override func viewDidLoad() {
addViewAboveColorView()
view.backgroundColor = startingColor
controller.actionOnButtonTap = { [unowned self] in
let newCoords = randomCoords()
let animation = self.viewFrameAnimationPosition(newCoords)
self.view.layer.removeAllAnimations()
self.view.layer.addAnimation(animation, forKey: "newCoords")
}
}
func addViewAboveColorView () {
let container = controller.colorView
if let found = container {
view.setTranslatesAutoresizingMaskIntoConstraints(false)
controller.view.addSubview(view)
let constraint1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[view(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[view]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint3 = NSLayoutConstraint.constraintsWithVisualFormat("H:[view(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
let constraint4 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\((controller.view.frame.size.width - 60) / 2)-[view]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["view": view]).first! as! NSLayoutConstraint
controller.view.addConstraint(constraint1)
controller.view.addConstraint(constraint2)
controller.view.addConstraint(constraint3)
controller.view.addConstraint(constraint4)
leftConstraint = constraint4
topConstraint = constraint2
}
}
func viewFrameAnimationPosition(newPosition: CGPoint) -> CABasicAnimation {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "position")
let newCoords = randomCoords()
let oldValue = (view.layer.presentationLayer() as! CALayer).position
animation.fromValue = NSValue(CGPoint: oldValue)
animation.duration = 0.6
animation.toValue = NSValue(CGPoint: newCoords)
CATransaction.setCompletionBlock { () -> Void in
}
CATransaction.commit()
leftConstraint?.constant = newCoords.x - 30
topConstraint?.constant = newCoords.y - 30
return animation
}
}
| 6ad8a831e98c956b0ba5b7456480fb3f | 38.054795 | 233 | 0.728516 | false | false | false | false |
hq7781/MoneyBook | refs/heads/master | Mah Income/Pods/ChartsRealm/ChartsRealm/Classes/Data/RealmLineRadarDataSet.swift | mit | 2 | //
// RealmLineRadarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import Realm.Dynamic
open class RealmLineRadarDataSet: RealmLineScatterCandleRadarDataSet, ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
fileprivate var _fillColor = NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
/// The color that is used for filling the line surface area.
open var fillColor: NSUIColor
{
get { return _fillColor }
set
{
_fillColor = newValue
fill = nil
}
}
/// The object that is used for filling the area below the line.
/// **default**: nil
open var fill: Fill?
/// The alpha value that is used for filling the line surface,
/// **default**: 0.33
open var fillAlpha = CGFloat(0.33)
fileprivate var _lineWidth = CGFloat(1.0)
/// line width of the chart (min = 0.2, max = 10)
///
/// **default**: 1
open var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if newValue < 0.2
{
_lineWidth = 0.2
}
else if newValue > 10.0
{
_lineWidth = 10.0
}
else
{
_lineWidth = newValue
}
}
}
open var drawFilledEnabled = false
open var isDrawFilledEnabled: Bool
{
return drawFilledEnabled
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmLineRadarDataSet
copy.fillColor = fillColor
copy._lineWidth = _lineWidth
copy.drawFilledEnabled = drawFilledEnabled
return copy
}
}
| ef73eec3a17cee6f12633bc249ab2351 | 22.967391 | 111 | 0.565079 | false | false | false | false |
DaRkD0G/EasyHelper | refs/heads/master | EasyHelper/NSDateExtensions.swift | mit | 1 | //
// NSDateExtensions.swift
// EasyHelper
//
// Created by DaRk-_-D0G on 26/09/2015.
// Copyright © 2015 DaRk-_-D0G. All rights reserved.
//
import Foundation
/*
* Date Extension
* Inspirate by : https://github.com/malcommac/SwiftDate
*
* - Convert Numbers
* - Radians Degrees
*/
/// ############################################################ ///
/// Operations with NSDate WITH DATES (==,!=,<,>,<=,>= ///
/// ############################################################ ///
//MARK: OPERATIONS WITH DATES (==,!=,<,>,<=,>=)
extension NSDate : Comparable {}
/**
NSDate == NSDate
- returns: Bool
*/
public func == (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedSame)
}
/**
NSDate != NSDate
- returns: Bool
*/
public func != (left: NSDate, right: NSDate) -> Bool {
return !(left == right)
}
/**
NSDate < NSDate
- returns: Bool
*/
public func < (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedAscending)
}
/**
NSDate > NSDate
- returns: Bool
*/
public func > (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedDescending)
}
/**
NSDate <= NSDate
- returns: Bool
*/
public func <= (left: NSDate, right: NSDate) -> Bool {
return !(left > right)
}
/**
NSDate >=
- returns: Bool
*/
public func >= (left: NSDate, right: NSDate) -> Bool {
return !(left < right)
}
/// ############################################################ ///
/// Arithmetic operations with NSDate ///
/// ############################################################ ///
//MARK: ARITHMETIC OPERATIONS WITH DATES (-,-=,+,+=)
/**
NSDate - 1.day
- returns: NSDate
*/
public func - (left : NSDate, right: NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(-right)
}
/**
NSDate -= 1.month
*/
public func -= (inout left: NSDate, right: NSTimeInterval) {
left = left.dateByAddingTimeInterval(-right)
}
/**
NSDate + 1.year
- returns: NSDate
*/
public func + (left: NSDate, right: NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(right)
}
/**
NSDate += 1.month
*/
public func += (inout left: NSDate, right: NSTimeInterval) {
left = left.dateByAddingTimeInterval(right)
}
/// ############################################################ ///
/// Get days functions ///
/// ############################################################ ///
// MARK: - Get days functions
public extension NSDate {
/// Get the day component of the date
var day: Int {
get {
return components.day
}
}
/// Get the month component of the date
var month : Int {
get {
return components.month
}
}
/// Get the year component of the date
public var year : Int {
get {
return components.year
}
}
/// Get the hour component of the date
var hour: Int {
get {
return components.hour
}
}
/// Get the minute component of the date
var minute: Int {
get {
return components.minute
}
}
/// Get the second component of the date
var second: Int {
get {
return components.second
}
}
/// Get the era component of the date
var era: Int {
get {
return components.era
}
}
/// Get the week of the month component of the date
var weekOfMonth: Int {
get {
return components.weekOfMonth
}
}
/// Get the week of the month component of the date
var weekOfYear: Int {
get {
return components.weekOfYear
}
}
/// Get the weekday component of the date
var weekday: Int {
get {
return components.weekday
}
}
/// Get the weekday ordinal component of the date
var weekdayOrdinal: Int {
get {
return components.weekdayOrdinal
}
}
}
/// ############################################################ ///
/// To ( Converted ) ///
/// ############################################################ ///
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
func toString (format: String) -> String {
let formatter = NSDateFormatter ()
formatter.locale = NSLocale(localeIdentifier: "tr")
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
func toTimeStamp() -> String {
let timeInterval = self.timeIntervalSince1970
let result = String(format: "/Date(%.0f000)/", arguments:[timeInterval])
return result
}
}
/// ############################################################ ///
/// Create days functions ///
/// ############################################################ ///
// MARK: - Create days functions
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
/**
Create a new NSDate instance based on refDate (if nil uses current date) and set components
:param: refDate reference date instance (nil to use NSDate())
:param: year year component (nil to leave it untouched)
:param: month month component (nil to leave it untouched)
:param: day day component (nil to leave it untouched)
:param: tz time zone component (it's the abbreviation of NSTimeZone, like 'UTC' or 'GMT+2', nil to use current time zone)
:returns: a new NSDate with components changed according to passed params
*/
public class func date(refDate refDate: NSDate? = nil, year: Int? = nil, month: Int? = nil, day:Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> NSDate {
let referenceDate = refDate ?? NSDate()
return referenceDate.set(year, month: month, day: day, hour: hour, minute: minute, second: second, tz: tz)
}
/* --------------------------------------------------------------------------- */
/* Create day by Today, Yesteday, Tomorrow */
/* --------------------------------------------------------------------------- */
/**
Return a new NSDate instance with the current date and time set to 00:00:00
:param: tz optional timezone abbreviation
:returns: a new NSDate instance of the today's date
*/
public class func today() -> NSDate {
let nowDate = NSDate()
return NSDate.date(refDate: nowDate, year: nowDate.year, month: nowDate.month, day: nowDate.day)
}
/**
Return a new NSDate istance with the current date minus one day
:param: tz optional timezone abbreviation
:returns: a new NSDate instance which represent yesterday's date
*/
public class func yesterday() -> NSDate {
return today()-1.day
}
/**
Return a new NSDate istance with the current date plus one day
:param: tz optional timezone abbreviation
:returns: a new NSDate instance which represent tomorrow's date
*/
public class func tomorrow() -> NSDate {
return today()+1.day
}
}
/// ############################################################ ///
/// Is ( Tested ) ///
/// ############################################################ ///
// MARK: - Is ( Tested )
public extension NSDate {
/// Return true if the date is the weekend
public var isWeekend:Bool {
let range = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.Weekday)
return (self.weekday == range.location || self.weekday == range.length)
}
/// Return true if current date's day is not a weekend day
public var isWeekday:Bool {
return !self.isWeekend
}
}
/// ############################################################ ///
/// Private ///
/// ############################################################ ///
// MARK: - Get days functions
public extension NSDate {
/* --------------------------------------------------------------------------- */
/* Create Day */
/* --------------------------------------------------------------------------- */
/**
Individual set single component of the current date instance
:param: year a non-nil value to change the year component of the instance
:param: month a non-nil value to change the month component of the instance
:param: day a non-nil value to change the day component of the instance
:param: hour a non-nil value to change the hour component of the instance
:param: minute a non-nil value to change the minute component of the instance
:param: second a non-nil value to change the second component of the instance
:param: tz a non-nil value (timezone abbreviation string as for NSTimeZone) to change the timezone component of the instance
:returns: a new NSDate instance with changed values
*/
private func set(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, tz: String? = nil) -> NSDate! {
let components = self.components
components.year = year ?? self.year
components.month = month ?? self.month
components.day = day ?? self.day
components.hour = hour ?? self.hour
components.minute = minute ?? self.minute
components.second = second ?? self.second
components.timeZone = (tz != nil ? NSTimeZone(abbreviation: tz!) : NSTimeZone.defaultTimeZone())
return NSCalendar.currentCalendar().dateFromComponents(components)
}
/* --------------------------------------------------------------------------- */
/* Components */
/* --------------------------------------------------------------------------- */
/// Specify calendrical units such as day and month
private class var componentFlags:NSCalendarUnit {
return [NSCalendarUnit.Year ,
NSCalendarUnit.Month ,
NSCalendarUnit.Day,
NSCalendarUnit.WeekOfYear,
NSCalendarUnit.Hour ,
NSCalendarUnit.Minute ,
NSCalendarUnit.Second ,
NSCalendarUnit.Weekday ,
NSCalendarUnit.WeekdayOrdinal,
NSCalendarUnit.WeekOfYear]
}
/// Return the NSDateComponents which represent current date
private var components: NSDateComponents {
return NSCalendar.currentCalendar().components(NSDate.componentFlags, fromDate: self)
}
}
| 38d820e5a24b534d4f62f307bdfa5cf6 | 32.323529 | 203 | 0.493116 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS | refs/heads/develop | NoticiasLeganes/Chat/ViewControllers/AliasVC.swift | mit | 1 | //
// AliasVC.swift
// NoticiasLeganes
//
// Created by Alvaro Informática on 16/1/18.
// Copyright © 2018 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
import Material
import Firebase
class AliasVC: InputDataViewController {
@IBOutlet weak var aliasView: UIView!
private var aliasField: ErrorTextField!
var viewModel: ChatVM!
override func viewDidLoad() {
super.viewDidLoad()
prepareAliasField()
Analytics.watchAliasChat()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func initChatTap(_ sender: Any) {
guard let textAlias = aliasField.text else {
return
}
if textAlias == "" || textAlias.count < 5 {
aliasField.isErrorRevealed = true
return
}
Auth.auth().signInAnonymously(completion: { (user, error) in
if let _error = error {
print(_error.localizedDescription)
return
}
UserDF.alias = textAlias
self.viewModel.alias = textAlias
self.viewModel.uid = Auth.auth().currentUser?.uid
self.navigationController?.popViewController(animated: true)
})
}
}
extension AliasVC {
private func prepareAliasField() {
aliasField = prepareErrorTextField(placeholder: "Alias", error: "Debe tener al menos 5 caracteres", centerInLayout: aliasView)
}
}
| 54c0efef5e77aa0fbd87cc5b5c3739d5 | 25.603448 | 134 | 0.624109 | false | false | false | false |
kevinsumios/KSiShuHui | refs/heads/master | Project/Model/Subscription+extension.swift | mit | 1 | //
// Subscription+extension.swift
// KSiShuHui
//
// Created by Kevin Sum on 30/7/2017.
// Copyright © 2017 Kevin iShuHui. All rights reserved.
//
import Foundation
import MagicalRecord
import SwiftyJSON
extension Subscription {
class func subscribe(bookId: Int16, YesOrNo: Bool) {
MagicalRecord.save(blockAndWait: { (localContext) in
var entity = Subscription.mr_findFirst(byAttribute: "bookId", withValue: bookId, in: localContext)
if entity == nil, YesOrNo {
entity = Subscription.mr_createEntity(in: localContext)
entity?.bookId = bookId
} else if entity != nil, !YesOrNo {
entity?.mr_deleteEntity(in: localContext)
}
})
}
class func isSubscribe(bookId: Int16?) -> Bool {
if Subscription.mr_findFirst(byAttribute: "bookId", withValue: bookId ?? -1) == nil {
return false
} else {
return true
}
}
}
| d453478563757781db43f8742e168f31 | 27.571429 | 110 | 0.595 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live | refs/heads/master | AppExtensionBirdWatcher/BirdWatcher/ViewController.swift | mit | 1 | //😘 it is 8/24/17
import UIKit
import BirdKit
import MobileCoreServices
class ViewController: UIViewController {
@IBOutlet weak var birdNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
BirdCallGenerator.makeBirdCall()
}
@IBAction func handleShareActionTapped(_ sender: Any) {
let activityViewController = UIActivityViewController(activityItems: [birdNameLabel.text!], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
activityViewController.completionWithItemsHandler = {
(activityType, completed, returnedItems, error) in
guard
let returnedItems = returnedItems,
returnedItems.count > 0,
let textItem = returnedItems.first as? NSExtensionItem,
let textItemProvider = textItem.attachments?.first as? NSItemProvider,
textItemProvider.hasItemConformingToTypeIdentifier(kUTTypeText as String)
else { return }
textItemProvider.loadItem(forTypeIdentifier: kUTTypeText as String, options: nil, completionHandler: { (string, error) in
guard
error == nil,
let newText = string as? String else { return }
DispatchQueue.main.async {
self.birdNameLabel.text = newText
}
})
}
}
}
| a46a50c1d3d1d395cdb172bca60efaec | 32.688889 | 133 | 0.605541 | false | false | false | false |
lincolnge/sparsec | refs/heads/master | sparsec/sparsec/atom.swift | mit | 1 | //
// atom.swift
// sparsec
//
// Created by Mars Liu on 15/3/10.
// Copyright (c) 2015年 Dwarf Artisan. All rights reserved.
//
import Foundation
func one<T:Equatable, S:CollectionType where S.Generator.Element==T>(one: T)->Parsec<T, S>.Parser{
var pred = equals(one)
return {(state: BasicState<S>)->(T?, ParsecStatus) in
var re = state.next(pred)
switch re {
case .Success:
return (one, ParsecStatus.Success)
case .Failed:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) missmatch."))
case .Eof:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) Eof."))
}
}
}
func subject<T:Equatable, S:CollectionType where S.Generator.Element==T >
(one: T, curry:(T)->(T)->Bool)->Parsec<T, S>.Parser {
var pred:(T)->Bool = curry(one)
return {(state: BasicState<S>)->(T?, ParsecStatus) in
var re = state.next(pred)
switch re {
case .Success:
return (one, ParsecStatus.Success)
case .Failed:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) missmatch."))
case .Eof:
return (nil, ParsecStatus.Failed("Except \(one) but \(state[state.pos]) Eof."))
}
}
}
func eof<S:CollectionType>(state: BasicState<S>)->(S.Generator.Element?, ParsecStatus){
var item = state.next()
if item == nil {
return (nil, ParsecStatus.Success)
} else {
return (item, ParsecStatus.Failed("Except Eof but \(item) at \(state.pos)"))
}
}
func pack<T, S:CollectionType>(value:T?)->Parsec<T, S>.Parser {
return {(state:BasicState)->(T?, ParsecStatus) in
return (value, ParsecStatus.Success)
}
}
func fail<S:CollectionType>(message:String)->Parsec<S.Generator.Element, S>.Parser {
return {(state:BasicState)->(S.Generator.Element?, ParsecStatus) in
return (nil, ParsecStatus.Failed(message))
}
}
| 3fdb2ffe1e71fa84282494aaba5dc1e6 | 29.661538 | 98 | 0.605118 | false | false | false | false |
openhab/openhab.ios | refs/heads/sse-monitor-and-tracker-changes | openHAB/RollershutterUITableViewCell.swift | epl-1.0 | 1 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import DynamicButton
import OpenHABCore
import os.log
import UIKit
class RollershutterUITableViewCell: GenericUITableViewCell {
private let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
@IBOutlet private var downButton: DynamicButton!
@IBOutlet private var stopButton: DynamicButton!
@IBOutlet private var upButton: DynamicButton!
@IBOutlet private var customDetailText: UILabel!
required init?(coder: NSCoder) {
os_log("RollershutterUITableViewCell initWithCoder", log: .viewCycle, type: .info)
super.init(coder: coder)
initialize()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
os_log("RollershutterUITableViewCell initWithStyle", log: .viewCycle, type: .info)
super.init(style: style, reuseIdentifier: reuseIdentifier)
initialize()
}
override func initialize() {
selectionStyle = .none
separatorInset = .zero
}
override func displayWidget() {
customTextLabel?.text = widget.labelText
customDetailText?.text = widget.labelValue ?? ""
upButton?.setStyle(.caretUp, animated: true)
stopButton?.setStyle(.stop, animated: true)
downButton?.setStyle(.caretDown, animated: true)
upButton?.addTarget(self, action: .upButtonPressed, for: .touchUpInside)
stopButton?.addTarget(self, action: .stopButtonPressed, for: .touchUpInside)
downButton?.addTarget(self, action: .downButtonPressed, for: .touchUpInside)
downButton?.highlightStokeColor = .ohHightlightStrokeColor
upButton?.highlightStokeColor = .ohHightlightStrokeColor
stopButton?.highlightStokeColor = .ohHightlightStrokeColor
}
@objc
func upButtonPressed() {
os_log("up button pressed", log: .viewCycle, type: .info)
widget.sendCommand("UP")
feedbackGenerator.impactOccurred()
}
@objc
func stopButtonPressed() {
os_log("stop button pressed", log: .viewCycle, type: .info)
widget.sendCommand("STOP")
feedbackGenerator.impactOccurred()
}
@objc
func downButtonPressed() {
os_log("down button pressed", log: .viewCycle, type: .info)
widget.sendCommand("DOWN")
feedbackGenerator.impactOccurred()
}
}
// inspired by: Selectors in swift: A better approach using extensions
// https://medium.com/@abhimuralidharan/selectors-in-swift-a-better-approach-using-extensions-aa6b0416e850
private extension Selector {
static let upButtonPressed = #selector(RollershutterUITableViewCell.upButtonPressed)
static let stopButtonPressed = #selector(RollershutterUITableViewCell.stopButtonPressed)
static let downButtonPressed = #selector(RollershutterUITableViewCell.downButtonPressed)
}
| 885539b9ffce94b77ea16391f5df7ebc | 36.761905 | 106 | 0.715637 | false | false | false | false |
GraphQLSwift/GraphQL | refs/heads/main | Tests/GraphQLTests/StarWarsTests/StarWarsValidationTests.swift | mit | 1 | @testable import GraphQL
import XCTest
/**
* Helper function to test a query and the expected response.
*/
func validationErrors(query: String) throws -> [GraphQLError] {
let source = Source(body: query, name: "StarWars.graphql")
let ast = try parse(source: source)
return validate(schema: starWarsSchema, ast: ast)
}
class StarWarsValidationTests: XCTestCase {
func testNestedQueryWithFragment() throws {
let query = "query NestedQueryWithFragment {" +
" hero {" +
" ...NameAndAppearances" +
" friends {" +
" ...NameAndAppearances" +
" friends {" +
" ...NameAndAppearances" +
" }" +
" }" +
" }" +
"}" +
"fragment NameAndAppearances on Character {" +
" name" +
" appearsIn" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
func testHeroSpaceshipQuery() throws {
let query = "query HeroSpaceshipQuery {" +
" hero {" +
" favoriteSpaceship" +
" }" +
"}" +
"fragment NameAndAppearances on Character {" +
" name" +
" appearsIn" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testHeroNoFieldsQuery() throws {
let query = "query HeroNoFieldsQuery {" +
" hero" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testHeroFieldsOnScalarQuery() throws {
let query = "query HeroFieldsOnScalarQuery {" +
" hero {" +
" name {" +
" firstCharacterOfName" +
" }" +
" }" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testDroidFieldOnCharacter() throws {
let query = "query DroidFieldOnCharacter {" +
" hero {" +
" name" +
" primaryFunction" +
" }" +
"}"
XCTAssertFalse(try validationErrors(query: query).isEmpty)
}
func testDroidFieldInFragment() throws {
let query = "query DroidFieldInFragment {" +
" hero {" +
" name" +
" ...DroidFields" +
" }" +
"}" +
"fragment DroidFields on Droid {" +
" primaryFunction" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
func testDroidFieldInInlineFragment() throws {
let query = "query DroidFieldInInlineFragment {" +
" hero {" +
" name" +
" ... on Droid {" +
" primaryFunction" +
" }" +
" }" +
"}"
XCTAssert(try validationErrors(query: query).isEmpty)
}
}
| 6bfc6a518ff002aae07423de104042be | 28.447619 | 66 | 0.464101 | false | true | false | false |
shaps80/SwiftLayout | refs/heads/master | Pod/Classes/SingleView+Size.swift | mit | 1 | //
// SingleView+Size.swift
// SwiftLayout
//
// Created by Shaps Mohsenin on 21/06/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
extension View {
/**
Sizes this view
- parameter axis: The axis to size
- parameter relation: The relation for this sizing, equal, greaterThanOrEqual, lessThanOrEqual
- parameter size: The size to set
- returns: The constraint that was added
*/
@discardableResult public func size(axis: Axis, relation: LayoutRelation, size: CGFloat, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> NSLayoutConstraint {
var constraint = Constraint(view: self)
constraint.firstAttribute = sizeAttribute(for: axis)
constraint.secondAttribute = sizeAttribute(for: axis)
constraint.relation = relation
constraint.constant = size
constraint.priority = priority
let layout = constraint.constraint()
layout.isActive = true
return layout
}
/**
Sizes this view's axis relative to another view axis. Note: The axis for each view doesn't have to be the same
- parameter axis: The axis to size
- parameter otherAxis: The other axis to use for sizing
- parameter view: The second view to reference
- parameter ratio: The ratio to apply to this sizing. (e.g. 0.5 would size this view by 50% of the second view's edge)
- returns: The constraint that was added
*/
@discardableResult public func size(axis: Axis, to otherAxis: Axis, of view: View, ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> NSLayoutConstraint {
var constraint = Constraint(view: self)
constraint.secondView = view
constraint.firstAttribute = sizeAttribute(for: axis)
constraint.secondAttribute = sizeAttribute(for: otherAxis)
constraint.multiplier = ratio
constraint.priority = priority
let layout = constraint.constraint()
layout.isActive = true
return layout
}
/**
Sizes the view to the specified width and height
- parameter width: The width
- parameter height: The height
- returns: The constraint that was added
*/
@discardableResult public func size(width: CGFloat, height: CGFloat, relation: LayoutRelation = .equal, priority: LayoutPriority = LayoutPriorityDefaultHigh) -> [NSLayoutConstraint] {
let horizontal = size(axis: .horizontal, relation: relation, size: width, priority: priority)
let vertical = size(axis: .vertical, relation: relation, size: height, priority: priority)
return [horizontal, vertical]
}
}
| daef1fa451ec411c088ddece11530170 | 34.175676 | 185 | 0.706108 | false | false | false | false |
Chriskuei/Bon-for-Mac | refs/heads/master | Bon/BonViewController.swift | mit | 1 | //
// BonViewController.swift
// Bon
//
// Created by Chris on 16/5/14.
// Copyright © 2016年 Chris. All rights reserved.
//
import Cocoa
class BonViewController: NSViewController {
@IBOutlet weak var infoTableView: NSTableView!
@IBOutlet weak var usernameTextField: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField!
@IBOutlet weak var bonLoginView: BonLoginView!
@IBOutlet weak var settingsButton: BonButton!
var username: String = ""{
didSet {
usernameTextField.stringValue = username
BonUserDefaults.username = username
}
}
var password: String = ""{
didSet {
passwordTextField.stringValue = password
BonUserDefaults.password = password
}
}
var seconds: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.bonHighlight().cgColor
username = BonUserDefaults.username
password = BonUserDefaults.password
NotificationCenter.default.addObserver(self, selector: #selector(getOnlineInfo), name: Notification.Name(rawValue: BonConfig.BonNotification.GetOnlineInfo), object: nil)
getOnlineInfo()
}
@IBAction func onLoginButton(_ sender: AnyObject) {
bonLoginView.show(.loading)
login()
}
@IBAction func onLogoutButton(_ sender: AnyObject) {
bonLoginView.show(.loading)
forceLogout()
}
@IBAction func switchToPasswordTextField(_ sender: AnyObject) {
usernameTextField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
}
@IBAction func enterKeyPressed(_ sender: AnyObject) {
onLoginButton(sender)
}
@IBAction func onSettingsButton(_ sender: BonButton) {
SettingsMenuAction.makeSettingsMenu(sender)
}
func showLoginView() {
bonLoginView.isHidden = false
}
func hideLoginView() {
bonLoginView.isHidden = true
}
// MARK: - Network operation
func login() {
username = usernameTextField.stringValue
password = passwordTextField.stringValue
let parameters = [
"action": "login",
"username": username,
"password": password,
"ac_id": "1",
"user_ip": "",
"nas_ip": "",
"user_mac": "",
"save_me": "1",
"ajax": "1"
]
BonNetwork.post(parameters, success: { (value) in
print(value)
if value.contains("login_ok,") {
delay(1) {
self.getOnlineInfo()
}
delay(1) {
self.bonLoginView.show(.loginSuccess)
}
} else if value.contains("You are already online.") || value.contains("IP has been online, please logout.") {
delay(1) {
self.getOnlineInfo()
}
delay(1) {
self.bonLoginView.show(.loginSuccess)
}
} else if value.contains("Password is error.") {
delay(1) {
self.bonLoginView.show(.passwordError)
}
} else if value.contains("User not found.") {
delay(1) {
self.bonLoginView.show(.usernameError)
}
} else if value.contains("Arrearage users.") { // E2616: Arrearage users.(已欠费)
delay(1) {
self.bonLoginView.show(.inArrearsError)
}
}
else {
delay(1) {
self.bonLoginView.show(.error)
}
}
}) { (error) in
self.bonLoginView.show(.timeout)
}
}
// MARK : - logout
func logout() {
let parameters = [
"action": "auto_logout"
]
BonNetwork.post(parameters) { (value) in
self.bonLoginView.isHidden = false
}
}
// TODO : - forcelogout
//Parse response
func forceLogout() {
username = usernameTextField.stringValue
password = passwordTextField.stringValue
BonNetwork.updateLoginState()
switch loginState {
case .offline:
delay(1) {
self.bonLoginView.showLoginState(.offline)
}
case .online:
let parameters = [
"action": "logout",
"username": username,
"password": password,
"ajax": "1"
]
BonNetwork.post(parameters) { (value) in
print(value)
delay(1) {
self.bonLoginView.show(.logoutSuccess)
}
}
}
}
// MARK : - get online info
@objc func getOnlineInfo() {
let parameters = [
"action": "get_online_info"
]
BonNetwork.post(parameters, success: { (value) in
NSLog(value)
if(value == "not_online") {
loginState = .offline
self.showLoginView()
} else {
self.hideLoginView()
loginState = .online
print(value)
let info = value.components(separatedBy: ",")
self.seconds = Int(info[1])!
self.itemsInfo = BonFormat.formatOnlineInfo(info)
self.updateItems()
}
}) { (error) in
loginState = .offline
self.showLoginView()
}
}
var items = [BonItem]()
var itemsInfo = [String]()
let itemsName = ["username", "used Data", "used Time", "balance", "daily Available Data"]
func updateItems() {
self.items = []
for index in 0...4 {
let item = BonItem(name: itemsName[index], info: itemsInfo[index])
items.append(item)
}
infoTableView.reloadData()
}
}
// MARK: - Table view
extension BonViewController: NSTableViewDataSource {
func numberOfRows(in aTableView: NSTableView) -> Int {
return items.count
}
@objc(tableView:viewForTableColumn:row:) func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
return BonCell.view(tableView, owner: self, subject: items[row])
}
}
extension BonViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return true
}
}
| 251bd9c9cb6d16b4a7066afe9d7851f7 | 26 | 177 | 0.508405 | false | false | false | false |
germc/IBM-Ready-App-for-Retail | refs/heads/master | iOS/ReadyAppRetail/ReadyAppRetail/Utilities/UserAuthHelper.swift | epl-1.0 | 2 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
class UserAuthHelper: NSObject {
static var hasKeychainItems : Bool = true
/**
This method checks to see if a user is logged in by calling the isLoggedIn method. If a user is logged in it returns true. If a user isn't logged in, it presents the loginViewController and returns false.
:param: fromViewController the view controller that will present the loginViewController if a user isn't logged in
:returns: bool true - user is logged in, false - user isn't logged in
*/
class func checkIfLoggedIn(fromViewController:UIViewController) -> Bool {
if(isLoggedIn() == true){
return true
}
presentLoginViewController(fromViewController)
return false
}
/**
This method checks to see if a user is logged in by checking NSUserDefaults to see if there is a string for key "userID". If there is a value for this key, it checks to see if the value is greated than 0. If it isn't greater than 0 then it returns false, else true. If there is no string for Key "userID" then it returns false.
:returns: bool true - user is logged in, false - user isn't logged in
*/
class func isLoggedIn() -> Bool {
if let name = NSUserDefaults.standardUserDefaults().stringForKey("userID")
{
if(count(name) > 0){
return true
}
else{
return false
}
}
else
{
return false
}
}
/**
This method saves the userID parameter to NSUserDefaults for the key "userID"
:param: userID the userID to be saved to NSUSerDefaults for key "userID"
*/
class func saveUser(userID : String){
NSUserDefaults.standardUserDefaults().setObject(userID, forKey: "userID")
NSUserDefaults.standardUserDefaults().synchronize()
}
/**
This method sets the value for key "userID" to "" in NSUserDefaults
*/
class func clearUser(){
NSUserDefaults.standardUserDefaults().setObject("", forKey: "userID")
NSUserDefaults.standardUserDefaults().synchronize()
}
/**
This method checks to see if a user has downloaded the defaultLists yet.
:returns: bool true - user has downloaded default lists, false - user hasn't downloaded default lists
*/
class func hasDownloadedDefaultLists() -> Bool{
if let hasDownloadedDefaultLists = NSUserDefaults.standardUserDefaults().stringForKey("hasDownloadedDefaultLists")
{
if(hasDownloadedDefaultLists == "true"){
return true
}
else{
return false
}
}
else
{
return false
}
}
/**
This method sets the key hasDownloadedDefaultLists to true in NSUserDefaults
*/
class func setUserHasDownloadedDefaultLists(){
NSUserDefaults.standardUserDefaults().setObject("true", forKey: "hasDownloadedDefaultLists")
NSUserDefaults.standardUserDefaults().synchronize()
}
/**
This method is called by the checkIfLogged method. It is called when the user isn't logged in and the loginViewController should be presented.
:param: fromViewController the view controller that will be presenting the loginViewController.
*/
private class func presentLoginViewController(fromViewController:UIViewController) {
var vc = fromViewController.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
vc.presentingVC = fromViewController
fromViewController.presentViewController(vc, animated: true, completion: nil)
}
}
| 7b8fe54aa15aee70d7a50a3333ae28a2 | 32.603448 | 331 | 0.647255 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/Interpreter/SDK/autolinking.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: echo "int global() { return 42; }" | %clang -dynamiclib -o %t/libLinkMe.dylib -x c -
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name LinkMe -module-link-name LinkMe %S/../../Inputs/empty.swift
// RUN: %target-jit-run -DIMPORT %s -I %t -L %t 2>&1
// RUN: %target-jit-run -lLinkMe %s -L %t 2>&1
// RUN: not %target-jit-run -lLinkMe %s 2>&1
// RUN: %target-jit-run -lLinkMe -DUSE_DIRECTLY %s -L %t 2>&1
// RUN: not %target-jit-run -DUSE_DIRECTLY -lLinkMe %s 2>&1
// REQUIRES: executable_test
// This is specifically testing autolinking for immediate mode. Please do not
// change it to use %target-build/%target-run
// REQUIRES: swift_interpreter
// REQUIRES: OS=macosx
import Darwin
#if IMPORT
import LinkMe
#endif
#if USE_DIRECTLY
@_silgen_name("global")
func global() -> Int32
if global() != 42 {
exit(EXIT_FAILURE)
}
#else
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
if dlsym(RTLD_DEFAULT, "global") == nil {
print(String(cString: dlerror()))
exit(EXIT_FAILURE)
}
#endif
| 3f06aa4ca3ed3875b09e4bc613de64e9 | 24.547619 | 136 | 0.674744 | false | false | false | false |
rymcol/Linux-Server-Side-Swift-Benchmarking | refs/heads/master | KituraJSON/Sources/main.swift | apache-2.0 | 1 | import Kitura
import SwiftyJSON
#if os(Linux)
import SwiftGlibc
public func arc4random_uniform(_ max: UInt32) -> Int32 {
return (SwiftGlibc.rand() % Int32(max-1)) + 1
}
#endif
// All Web apps need a router to define routes
let router = Router()
router.get("/json") { _, response, next in
response.headers["Content-Type"] = "application/json; charset=utf-8"
let json = JSON(JSONCreator().generateJSON())
try response.send(json: json).end()
}
router.get(middleware: StaticFileServer(path: "./public"))
// Handles any errors that get set
router.error { request, response, next in
response.headers["Content-Type"] = "text/plain; charset=utf-8"
let errorDescription: String
if let error = response.error {
errorDescription = "\(error)"
} else {
errorDescription = "Unknown error"
}
try response.send("Caught the error: \(errorDescription)").end()
}
// A custom Not found handler
router.all { request, response, next in
if response.statusCode == .unknown {
// Remove this wrapping if statement, if you want to handle requests to / as well
if request.originalURL != "/" && request.originalURL != "" {
try response.status(.notFound).send("404! - This page does not exits!").end()
}
}
next()
}
// Add HTTP Server to listen on port 8090
Kitura.addHTTPServer(onPort: 8090, with: router)
// start the framework - the servers added until now will start listening
Kitura.run()
| 0c5f754a020b1ea0d630aead6d29a349 | 29.1 | 89 | 0.658472 | false | false | false | false |
sebmartin/Pipeline | refs/heads/master | Pipeline/Source/ViewModel/ViewProperty.swift | mit | 1 | //
// FormElement.swift
// Pipeline
//
// Created by Seb Martin on 2016-03-29.
// Copyright © 2016 Seb Martin. All rights reserved.
//
public struct ViewProperty<ValueType: Equatable, ViewType:UIControl> where ViewType:PipeableViewType {
public var valuePipe: Observable<ValueType>
public var viewPipe: ViewPipe<ViewType>
public var isValidPipe: Observable<Bool>
public init <
ValuePipeType: PipeType,
ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: ViewPipeType, validator: Validator<ValueType>? = nil)
where
ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType,
ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
valuePipe = Observable(value)
viewPipe = ViewPipe(view)
isValidPipe = Observable(true)
let validator = validator ?? Validator<ValueType> { (value) in return true }
viewPipe |- viewOut |- validator |~ {
$0 |- self.valuePipe |- valueOut |- AnyPipe(self.viewPipe, weak: true)
$0.isValid |- self.isValidPipe
}
}
public var value: ValueType {
get {
return valuePipe.value
}
set(value) {
valuePipe.value = value
}
}
public var view: ViewType {
return viewPipe.view
}
// MARK: - Convenience initializers
// MARK: View and Value Pipe/Lambda permutations
public init <ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: ViewPipeType, validator: Validator<ValueType>? = nil) where ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
let valuePipe = Pipe(valueOut)
self.init(value: value, view: view, valueOut: valuePipe, viewOut: viewOut, validator: validator)
}
public init <ValuePipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: Validator<ValueType>? = nil) where ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType
{
let viewPipe = Pipe(viewOut)
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewPipe, validator: validator)
}
public init (value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: Validator<ValueType>? = nil)
{
let valuePipe = Pipe(valueOut)
let viewPipe = Pipe(viewOut)
self.init(value: value, view: view, valueOut: valuePipe, viewOut: viewPipe, validator: validator)
}
// MARK: Validator as a lambda
public init <
ValuePipeType: PipeType,
ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: ViewPipeType, validator: @escaping (ValueType)->Bool)
where
ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType,
ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init <ViewPipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: ViewPipeType, validator: @escaping (ValueType)->Bool) where ViewPipeType.PipeInput == ViewType.ViewValueType, ViewPipeType.PipeOutput == ValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init <ValuePipeType: PipeType>
(value: ValueType, view: ViewType, valueOut: ValuePipeType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: @escaping (ValueType)->Bool) where ValuePipeType.PipeInput == ValueType, ValuePipeType.PipeOutput == ViewType.ViewValueType
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
public init (value: ValueType, view: ViewType, valueOut: @escaping (ValueType)->ViewType.ViewValueType, viewOut: @escaping (ViewType.ViewValueType)->(ValueType), validator: @escaping (ValueType)->Bool)
{
self.init(value: value, view: view, valueOut: valueOut, viewOut: viewOut, validator: Validator(validate: validator))
}
}
extension ViewProperty where ValueType == ViewType.ViewValueType {
public init(value: ValueType, view: ViewType, validator: Validator<ValueType>? = nil) {
self.init(value: value, view: view, valueOut: { return $0 }, viewOut: { return $0 }, validator: validator)
}
public init(value: ValueType, view: ViewType, validator: @escaping (ValueType)->Bool) {
self.init(value: value, view: view, valueOut: { return $0 }, viewOut: { return $0 }, validator: Validator(validate: validator))
}
}
| 0945094831d5cfddcfde958ad598e71c | 42.901786 | 254 | 0.726866 | false | false | false | false |
EMart86/WhitelabelApp | refs/heads/master | Whitelabel/Application/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// Whitelabel
//
// Created by Martin Eberl on 27.02.17.
// Copyright © 2017 Martin Eberl. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.viewModel = MasterViewModel(timeStore: Dependencies.shared.timeStore)
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.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
/*if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}*/
return true
}
}
| 4379504c8e1d2f2625012963cb8eafaf | 55.515152 | 285 | 0.763539 | false | false | false | false |
tomdiggle/HexClockScreenSaver | refs/heads/master | Hex Clock/HexClock.swift | mit | 1 | //
// HexClock.swift
// Hex Clock
//
// Created by Tom Diggle on 27/08/2015.
// Copyright © 2015 Tom Diggle. All rights reserved.
//
import Cocoa
class HexClock {
let calendar: NSCalendar
init() {
self.calendar = NSCalendar.currentCalendar()
}
func stringOfCurrentTime() -> String {
let time = self.getCurrentTime()
let hour = time.hour <= 9 ? "0\(time.hour)" : "\(time.hour)"
let minute = time.minute <= 9 ? "0\(time.minute)" : "\(time.minute)"
let second = time.second <= 9 ? "0\(time.second)" : "\(time.second)"
return "\(hour)\(minute)\(second)"
}
func colorFromCurrentTime() -> NSColor {
let time = self.getCurrentTime()
return NSColor(red: time.hour, green: time.minute, blue: time.second)
}
private func getCurrentTime() -> (hour: Int, minute: Int, second: Int) {
var (hour, minute, second, nanosecond) = (0, 0, 0, 0)
let date = NSDate()
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: &nanosecond, fromDate: date)
return (hour, minute, second)
}
}
| c09b19a691f6dc4395156298012956e4 | 27.390244 | 106 | 0.573024 | false | false | false | false |
inamiy/DebugLog | refs/heads/swift/2.0 | DebugLog.all.swift | mit | 1 |
//
// DDFileReader+DebugLog.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/26.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
extension DDFileReader
{
func readLogLine(index: Int) -> NSString!
{
var line: NSString!
self.resetOffset()
var lineNum = 0
self.enumerateLinesUsingBlock { (currentLine, stop) in
lineNum += 1
if lineNum == index {
line = currentLine
stop = true
}
}
let logFuncString = "LOG_OBJECT\\(.*?\\)" as NSString
var range = line.rangeOfString(logFuncString as String, options: .RegularExpressionSearch)
range.location += logFuncString.length-6
range.length -= logFuncString.length-5
line = line.substringWithRange(range).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return line
}
}
//
// DebugLog+ClassParsing.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/26.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
// Swift and Objective-C Class Parsing by @jpsim
// https://gist.github.com/jpsim/1b86d116808cb4e9bc30
extension DebugLog
{
enum ClassType {
case Swift, ObjectiveC
func toString() -> String {
switch self {
case .Swift:
return "Swift"
case .ObjectiveC:
return "Objective-C"
}
}
}
struct ParsedClass {
let type: ClassType
let name: String
let mangledName: String?
let moduleName: String?
}
static func _substr(str: String, range: Range<Int>) -> String {
let startIndex = str.startIndex.advancedBy(range.startIndex)
let endIndex = startIndex.advancedBy(range.endIndex)
return str[startIndex..<endIndex]
}
static func parseClass(aClass: AnyClass) -> ParsedClass {
// Swift mangling details found here: http://www.eswick.com/2014/06/inside-swift
let originalName = NSStringFromClass(aClass)
if !originalName.hasPrefix("_T") {
// Not a Swift symbol
return ParsedClass(type: ClassType.ObjectiveC,
name: originalName,
mangledName: nil,
moduleName: nil)
}
let originalNameLength = originalName.utf16.count
var cursor = 4
var substring = _substr(originalName, range: cursor ..< originalNameLength-cursor)
// Module
let moduleLength = (substring as NSString).integerValue
let moduleLengthLength = "\(moduleLength)".utf16.count
let moduleName = _substr(substring, range: moduleLengthLength ..< moduleLength)
// Update cursor and substring
cursor += moduleLengthLength + moduleName.utf16.count
substring = _substr(originalName, range: cursor ..< originalNameLength-cursor)
// Class name
let classLength = (substring as NSString).integerValue
let classLengthLength = "\(classLength)".utf16.count
let className = _substr(substring, range: classLengthLength ..< classLength)
return ParsedClass(type: ClassType.Swift,
name: className,
mangledName: originalName,
moduleName: moduleName)
}
}
//
// DebugLog+Printable.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
import CoreGraphics
import QuartzCore
//
// TODO:
// Some C-structs (e.g. CGAffineTransform, CATransform3D) + Printable don't work well in Xcode6-beta2
//
extension CGAffineTransform : CustomStringConvertible, CustomDebugStringConvertible
{
public var description: String
{
// return NSStringFromCGAffineTransform(self) // comment-out: requires UIKit
return "[\(a), \(b);\n \(c), \(d);\n \(tx), \(ty)]"
}
public var debugDescription: String
{
return self.description
}
}
extension CATransform3D : CustomStringConvertible, CustomDebugStringConvertible
{
public var description: String
{
return "[\(m11) \(m12) \(m13) \(m14);\n \(m21) \(m22) \(m23) \(m24);\n \(m31) \(m32) \(m33) \(m34);\n \(m41) \(m42) \(m43) \(m44)]"
}
public var debugDescription: String
{
return self.description
}
}
//
// DebugLog.swift
// DebugLog
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Inami Yasuhiro. All rights reserved.
//
import Foundation
public struct DebugLog
{
private static let _lock = NSObject()
private static let _dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
private static func _currentDateString() -> String
{
return self._dateFormatter.stringFromDate(NSDate())
}
public static var printHandler: (Any!, String, String, Int) -> Void = { body, filename, functionName, line in
let dateString = DebugLog._currentDateString()
if body == nil {
print("\(dateString) [\(filename).\(functionName):\(line)]") // print functionName
return
}
if let body = body as? String {
if body.characters.count == 0 {
print("") // print break
return
}
}
print("\(dateString) [\(filename):\(line)] \(body)")
}
public static func print(body: Any! = nil, var filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
objc_sync_enter(_lock)
filename = ((filename as NSString).lastPathComponent as NSString).stringByDeletingPathExtension
self.printHandler(body, filename, functionName, line)
objc_sync_exit(_lock)
#endif
}
}
/// LOG() = prints __FUNCTION__
public func LOG(filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
DebugLog.print(nil, filename: filename, functionName: functionName, line: line)
#endif
}
/// LOG(...) = println
public func LOG(body: Any, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
DebugLog.print(body, filename: filename, functionName: functionName, line: line)
#endif
}
/// LOG_OBJECT(myObject) = println("myObject = ...")
public func LOG_OBJECT(body: Any, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
if let reader = DDFileReader(filePath: filename) {
let logBody = "\(reader.readLogLine(line)) = \(body)"
LOG(logBody, filename: filename, functionName: functionName, line: line)
} else {
LOG(body, filename: filename, functionName: functionName, line: line)
}
#endif
}
public func LOG_OBJECT(body: AnyClass, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__)
{
#if DEBUG
_ = DDFileReader(filePath: filename)
let classInfo: DebugLog.ParsedClass = DebugLog.parseClass(body)
let classString = classInfo.moduleName != nil ? "\(classInfo.moduleName!).\(classInfo.name)" : "\(classInfo.name)"
LOG_OBJECT(classString, filename: filename, functionName: functionName, line: line)
// comment-out: requires method name demangling
// LOG_OBJECT("\(class_getName(body))", filename: filename, functionName: functionName, line: line)
#endif
}
//
// DDFileReader.swift
// DDFileReader
//
// Created by Yasuhiro Inami on 2014/06/22.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
//
// Swift port of DDFileReader by Dave DeLong
//
// objective c - How to read data from NSFileHandle line by line? - Stack Overflow
// http://stackoverflow.com/a/3711079/666371
//
public class DDFileReader
{
public var lineDelimiter = "\n"
public var chunkSize = 128
public let filePath: NSString
private let _fileHandle: NSFileHandle!
private let _totalFileLength: CUnsignedLongLong
private var _currentOffset: CUnsignedLongLong = 0
public init?(filePath: NSString)
{
self.filePath = filePath
if let fileHandle = NSFileHandle(forReadingAtPath: filePath as String) {
self._fileHandle = fileHandle
self._totalFileLength = self._fileHandle.seekToEndOfFile()
}
else {
self._fileHandle = nil
self._totalFileLength = 0
return nil
}
}
deinit
{
if let _fileHandle = self._fileHandle {
_fileHandle.closeFile()
}
}
public func readLine() -> NSString?
{
if self._currentOffset >= self._totalFileLength {
return nil
}
self._fileHandle.seekToFileOffset(self._currentOffset)
let newLineData = self.lineDelimiter.dataUsingEncoding(NSUTF8StringEncoding)
let currentData = NSMutableData()
var shouldReadMore = true
autoreleasepool {
while shouldReadMore {
if self._currentOffset >= self._totalFileLength {
break
}
var chunk = self._fileHandle.readDataOfLength(self.chunkSize)
let newLineRange = chunk.rangeOfData(newLineData!)
if newLineRange.location != NSNotFound {
chunk = chunk.subdataWithRange(NSMakeRange(0, newLineRange.location+newLineData!.length))
shouldReadMore = false
}
currentData.appendData(chunk)
self._currentOffset += CUnsignedLongLong(chunk.length)
}
}
let line = NSString(data: currentData, encoding:NSUTF8StringEncoding)
return line
}
public func readTrimmedLine() -> NSString?
{
let characterSet = NSCharacterSet(charactersInString: self.lineDelimiter)
return self.readLine()?.stringByTrimmingCharactersInSet(characterSet)
}
public func enumerateLinesUsingBlock(closure: (line: NSString, stop: inout Bool) -> Void)
{
var line: NSString? = nil
var stop = false
while stop == false {
line = self.readLine()
if line == nil { break }
closure(line: line!, stop: &stop)
}
}
public func resetOffset()
{
self._currentOffset = 0
}
}
extension NSData
{
private func rangeOfData(dataToFind: NSData) -> NSRange
{
var searchIndex = 0
var foundRange = NSRange(location: NSNotFound, length: dataToFind.length)
for index in 0...length-1 {
let bytes_ = UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(self.bytes), count: self.length)
let searchBytes_ = UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(dataToFind.bytes), count: self.length)
if bytes_[index] == searchBytes_[searchIndex] {
if foundRange.location == NSNotFound {
foundRange.location = index
}
searchIndex += 1
if searchIndex >= dataToFind.length {
return foundRange
}
}
else {
searchIndex = 0
foundRange.location = NSNotFound
}
}
return foundRange
}
}
| 31aab466a1a369e725fb7a0257eff1ad | 27.60095 | 139 | 0.591147 | false | false | false | false |
aestesis/Aether | refs/heads/master | Project/sources/Services/Spotify.swift | apache-2.0 | 1 | //
// Spotify.swift
// Alib
//
// Created by renan jegouzo on 18/03/2017.
// Copyright © 2017 aestesis. All rights reserved.
//
import Foundation
public class Spotify {
static let apiSearch="https://api.spotify.com/v1/search?q=$artist&type=artist"
public static func searchArtist(name:String,fn:@escaping ((Any?)->())) {
let url = apiSearch.replacingOccurrences(of:"$artist",with:name.addingPercentEncoding(withAllowedCharacters:.alphanumerics)!)
Web.getJSON(url, { r in
if let json = r as? JSON {
fn(json)
} else if let err = r as? Alib.Error {
fn(Error(err))
}
})
}
}
| 0d0cc39f24599b790a27a8edf0474ca7 | 28.565217 | 133 | 0.601471 | false | false | false | false |
uphold/uphold-sdk-ios | refs/heads/master | Source/Model/Reserve.swift | mit | 1 | import Foundation
import PromiseKit
import SwiftClient
/// Reserve model.
open class Reserve: BaseModel {
/**
Gets the ledger.
- returns: A paginator with the array of deposits.
*/
open func getLedger() -> Paginator<Deposit> {
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: Paginator<Deposit>.DEFAULT_START, end: Paginator<Deposit>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Deposit> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Deposit>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Deposit]> in
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: range))
let promise: Promise<[Deposit]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
/**
Gets the reserve summary of all the obligations and assets within it.
- returns: A promise with the reserve summary of all the obligations and assets within it.
*/
open func getStatistics() -> Promise<[ReserveStatistics]> {
let request = self.adapter.buildRequest(request: ReserveService.getStatistics())
return self.adapter.buildResponse(request: request)
}
/**
Gets the information of any transaction.
- parameter transactionId: The id of the transaction.
- returns: A promise with the transaction.
*/
open func getTransactionById(transactionId: String) -> Promise<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactionById(transactionId: transactionId))
return self.adapter.buildResponse(request: request)
}
/**
Gets information of all the transactions from the beginning of time.
- returns: A paginator with the array of transactions.
*/
open func getTransactions() -> Paginator<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: Paginator<Transaction>.DEFAULT_START, end: Paginator<Transaction>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Transaction> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Transaction>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Transaction]> in
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: range))
let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
}
| 44cc7cc693fa6eec3b8dade6b20b5b6d | 43.819672 | 220 | 0.600768 | false | false | false | false |
jay18001/brickkit-ios | refs/heads/master | Source/Models/BrickSectionDataSource.swift | apache-2.0 | 1 | //
// BrickSectionDataSource.swift
// BrickKit
//
// Created by Ruben Cagnie on 9/29/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import Foundation
// MARK: - Convenience methods for a BrickSection
extension BrickSection {
/// Number Of Sections
func numberOfSections(in collection: CollectionInfo) -> Int {
_ = invalidateIfNeeded(in: collection)
return sectionCount
}
func numberOfBricks(in collection: CollectionInfo) -> Int {
return bricks.reduce(0) { $0.0 + $0.1.count(for: collection) }
}
fileprivate func brickSection(for section: Int, in collection: CollectionInfo) -> BrickSection? {
if let indexPath = sectionIndexPaths[collection]?[section] {
return brick(at: indexPath, in: collection) as? BrickSection
}
return nil
}
/// Return number of items that are in a given section
///
/// - parameter section: Section
///
/// - returns: The number of items in the given section
func numberOfItems(in section: Int, in collection: CollectionInfo) -> Int {
_ = invalidateIfNeeded(in: collection)
guard section > 0 else {
return 1
}
guard let brickSection = brickSection(for: section, in: collection) else {
return 0
}
return brickSection.numberOfBricks(in: collection)
}
internal func brickAndIndex(at indexPath: IndexPath, in collection: CollectionInfo) -> (Brick, Int)? {
_ = invalidateIfNeeded(in: collection)
if indexPath.section == 0 {
return (self, 0)
}
guard let section = brickSection(for: indexPath.section, in: collection) else {
return nil
}
var index = 0
for brick in section.bricks {
if indexPath.item < index + brick.count(for: collection) {
return (brick, indexPath.item - index)
}
index += brick.count(for: collection)
}
return nil
}
func brick(at indexPath: IndexPath, in collection: CollectionInfo) -> Brick? {
return brickAndIndex(at: indexPath, in: collection)?.0
}
func index(at indexPath: IndexPath, in collection: CollectionInfo) -> Int? {
return brickAndIndex(at: indexPath, in: collection)?.1
}
func indexPathFor(_ section: Int, in collection: CollectionInfo) -> IndexPath? {
return sectionIndexPaths[collection]?[section]
}
/// Get the indexPaths for a brick with a certain identifier
///
/// - parameter identifier: Identifier
/// - parameter index: Index
///
/// - returns: an array of identifiers
func indexPathsForBricksWithIdentifier(_ identifier: String, index: Int? = nil, in collection: CollectionInfo) -> [IndexPath] {
var indexPaths: [IndexPath] = []
for section in 0..<numberOfSections(in: collection) {
for item in 0..<numberOfItems(in: section, in: collection) {
let indexPath = IndexPath(item: item, section: section)
let foundBrickWithIndex = brickAndIndex(at: indexPath, in: collection)! //We can safely unwrap, because this indexPath must exist
if foundBrickWithIndex.0.identifier == identifier {
if let index = index , foundBrickWithIndex.1 != index {
continue
}
indexPaths.append(indexPath)
}
}
}
return indexPaths
}
/// Gets the section index of a given indexPath
///
/// - parameter indexPath: IndexPath
///
/// - returns: Optional index
func sectionIndexForSectionAtIndexPath(_ indexPath: IndexPath, in collection: CollectionInfo) -> Int? {
let sectionIndexPaths = invalidateIfNeeded(in: collection)
guard let section = sectionIndexPaths.allKeysForValue(indexPath).first else {
return nil
}
return section
}
/// A Dictionary with the item-count of each section
internal func currentSectionCounts(in collection: CollectionInfo) -> [Int: Int] {
var sectionCounts: [Int: Int] = [:]
for section in 0..<numberOfSections(in: collection) {
sectionCounts[section] = numberOfItems(in: section, in: collection)
}
return sectionCounts
}
}
| 60dffc6540f084ca7832dcdd1880f1b1 | 31.014599 | 145 | 0.613771 | false | false | false | false |
NinjaIshere/GKGraphKit | refs/heads/master | GKGraphKit/GKAction.swift | agpl-3.0 | 1 | /**
* Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program located at the root of the software package
* in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
*
* GKAction
*
* Represents Action Nodes, which are repetitive relationships between Entity Nodes.
*/
import Foundation
@objc(GKAction)
public class GKAction: GKNode {
/**
* init
* Initializes GKAction with a given type.
* @param type: String
*/
override public init(type: String) {
super.init(type: type)
}
/**
* subjects
* Retrieves an Array of GKEntity Objects.
* @return Array<GKEntity>
*/
public var subjects: Array<GKEntity> {
get {
var nodes: Array<GKEntity> = Array<GKEntity>()
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
for item: AnyObject in node.subjectSet {
nodes.append(GKEntity(entity: item as GKManagedEntity))
}
}
return nodes
}
set(value) {
assert(false, "[GraphKit Error: Subjects may not be set.]")
}
}
/**
* objects
* Retrieves an Array of GKEntity Objects.
* @return Array<GKEntity>
*/
public var objects: Array<GKEntity> {
get {
var nodes: Array<GKEntity> = Array<GKEntity>()
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
for item: AnyObject in node.objectSet {
nodes.append(GKEntity(entity: item as GKManagedEntity))
}
}
return nodes
}
set(value) {
assert(false, "[GraphKit Error: Objects may not be set.]")
}
}
/**
* addSubject
* Adds a GKEntity Model Object to the Subject Set.
* @param entity: GKEntity!
* @return Bool of the result, true if added, false otherwise.
*/
public func addSubject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.addSubject(entity.node as GKManagedEntity);
}
return result
}
/**
* removeSubject
* Removes a GKEntity Model Object from the Subject Set.
* @param entity: GKEntity!
* @return Bool of the result, true if removed, false otherwise.
*/
public func removeSubject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.removeSubject(entity.node as GKManagedEntity);
}
return result
}
/**
* addObject
* Adds a GKEntity Object to the Object Set.
* @param entity: GKEntity!
* @return Bool of the result, true if added, false otherwise.
*/
public func addObject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.addObject(entity.node as GKManagedEntity);
}
return result
}
/**
* removeObject
* Removes a GKEntity Model Object from the Object Set.
* @param entity: GKEntity!
* @return Bool of the result, true if removed, false otherwise.
*/
public func removeObject(entity: GKEntity!) -> Bool {
var result: Bool = false
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
result = node.removeObject(entity.node as GKManagedEntity);
}
return result
}
/**
* delete
* Marks the Model Object to be deleted from the Graph.
*/
public func delete() {
graph.managedObjectContext.performBlockAndWait {
var node: GKManagedAction = self.node as GKManagedAction
node.delete()
}
}
/**
* init
* Initializes GKAction with a given GKManagedAction.
* @param action: GKManagedAction!
*/
internal init(action: GKManagedAction!) {
super.init(node: action)
}
/**
* createImplementorWithType
* Initializes GKManagedAction with a given type.
* @param type: String
* @return GKManagedAction
*/
override internal func createImplementorWithType(type: String) -> GKManagedNode {
return GKManagedAction(type: type);
}
}
| f3a1d36b5ce95028ea938c328366673c | 31.10119 | 89 | 0.622103 | 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.