repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
llxyls/DYTV | DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift | 1 | 1223 | //
// BaseViewController.swift
// DYTV
//
// Created by liuqi on 16/11/24.
// Copyright © 2016年 liuqi. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var contentView : UIView?
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!]
imageView.animationDuration = 1.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
contentView?.isHidden = true
// 动画
view.addSubview(animImageView)
animImageView.startAnimating()
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
func loadDataFinished(){
animImageView.stopAnimating()
animImageView.isHidden = true
contentView?.isHidden = false;
}
}
| mit | 302864bd5540257d96858506cf3fefac | 25.434783 | 104 | 0.633224 | 4.676923 | false | false | false | false |
LongPF/FaceTube | FaceTube/Shelf/FTTabbarContrller.swift | 1 | 3670 | //
// FTTabbarContrller.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/3/1.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
import AMScrollingNavbar
class FTTabbarContrller: UITabBarController {
//MARK: ************************ life cycle ************************
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.addChildViewControllers()
}
//MARK: ************************ interface methods ***************
open func showTabBar(show: Bool , aniamtie: Bool){
if show {
if aniamtie{
UIView.transition(with: tabBar, duration: 0.3, options: .curveLinear, animations: {
self.tabBar.layer.transform = CATransform3DMakeTranslation(0, 0, 0)
}, completion: nil)
}else{
self.tabBar.layer.transform = CATransform3DMakeTranslation(0, 0, 0)
}
}else{
tabBar.layer.removeAllAnimations()
if aniamtie{
UIView.transition(with: tabBar, duration: 0.3, options: .curveLinear, animations: {
self.tabBar.layer.transform = CATransform3DMakeTranslation(0, 60, 0)
}, completion: nil)
}else{
self.tabBar.layer.transform = CATransform3DMakeTranslation(0, 60, 0)
}
}
}
//MARK:private methods
fileprivate func addChildViewControllers(){
//home
let homeViewController = FTHomeViewController()
homeViewController.view.backgroundColor = UIColor.backgroundColor()
let homeTabBarItem: UITabBarItem = UITabBarItem.init(title: nil, image: UIImage.init(named: "ft_tabbar_live"), selectedImage: UIImage.init(named: "ft_tabbar_live_hl"))
homeTabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0)
homeViewController.tabBarItem = homeTabBarItem
let homeNav: ScrollingNavigationController = ScrollingNavigationController.init(rootViewController: homeViewController)
/*
//record
let recordViewController = FTVideoCaptureViewController()
recordViewController.view.backgroundColor = UIColor.backgroundColor()
let recordTabBarItem: UITabBarItem = UITabBarItem.init(title: nil, image: UIImage.init(named: "ft_tabbar_record"), selectedImage: UIImage.init(named: "ft_tabbar_record_hl"))
recordTabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
recordViewController.tabBarItem = recordTabBarItem
let recordNav: ScrollingNavigationController = ScrollingNavigationController.init(rootViewController: recordViewController)
*/
//capture
let captureViewController = FTCaptureViewController()
captureViewController.view.backgroundColor = UIColor.backgroundColor()
let captureTabBarItem: UITabBarItem = UITabBarItem.init(title: nil, image: UIImage.init(named: "ft_tabbar_record"), selectedImage: UIImage.init(named: "ft_tabbar_record_hl"))
captureTabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
captureViewController.tabBarItem = captureTabBarItem
let captureNav: ScrollingNavigationController = ScrollingNavigationController.init(rootViewController: captureViewController)
let controllers = NSArray.init(array:[homeNav,captureNav])
self.viewControllers = controllers as? [UIViewController]
}
}
| mit | 840ee95bf71844d8c3afddcdec9df911 | 37.946809 | 182 | 0.62879 | 5.185552 | false | false | false | false |
DanielCech/Vapor-Catalogue | Sources/App/Controllers/UserController.swift | 1 | 1337 | //
// UserController.swift
// Catalog
//
// Created by Dan on 19.01.17.
//
//
import Vapor
import HTTP
import Auth
final class UserController {
func addRoutes(drop: Droplet) {
let group = drop.grouped("user")
let albumGroup = group.grouped("albums")
albumGroup.get(handler: index)
albumGroup.post(handler: create)
// group.get(Album.self, handler: show)
// group.patch(Album.self, handler: update)
// group.delete(Album.self, handler: delete)
// group.get(Album.self, "artists", handler: artistShow)
}
func index(request: Request) throws -> ResponseRepresentable {
let userID = try User.getUserIDFromAuthorizationHeader(request: request)
let user = try User.find(userID)
return try JSON(node: user?.albums().makeNode())
}
func create(request: Request) throws -> ResponseRepresentable {
let userID = try User.getUserIDFromAuthorizationHeader(request: request)
var album = try request.album()
album.userId = Node(userID)
try album.save()
return album
}
func albumsIndex(request: Request, user: User) throws -> ResponseRepresentable {
let children = user.albums()
return try JSON(node: children.makeNode())
}
}
| mit | 3014ad191c8371dbf2302ca9d9bc1c98 | 26.854167 | 84 | 0.623785 | 4.244444 | false | false | false | false |
ragnar/VindsidenApp | VindSidenSpotlight/IndexRequestHandler.swift | 1 | 1965 | //
// IndexRequestHandler.swift
// VindSidenSpotlight
//
// Created by Ragnar Henriksen on 01.04.2016.
// Copyright © 2016 RHC. All rights reserved.
//
import CoreSpotlight
import VindsidenKit
class IndexRequestHandler: CSIndexExtensionRequestHandler {
override func searchableIndex(_ searchableIndex: CSSearchableIndex, reindexAllSearchableItemsWithAcknowledgementHandler acknowledgementHandler: @escaping () -> Void) {
let managedObjectContext = DataManager.shared.viewContext()
for station in CDStation.visibleStationsInManagedObjectContext(managedObjectContext) {
DataManager.shared.addStationToIndex(station, index: searchableIndex)
}
acknowledgementHandler()
}
override func searchableIndex(_ searchableIndex: CSSearchableIndex, reindexSearchableItemsWithIdentifiers identifiers: [String], acknowledgementHandler: @escaping () -> Void) {
let managedObjectContext = DataManager.shared.viewContext()
for identifier in identifiers {
do {
let stationIDString = (identifier as NSString).lastPathComponent
if let stationID = Int(stationIDString) {
let station = try CDStation.existingStationWithId(stationID, inManagedObjectContext: managedObjectContext)
if let hidden = station.isHidden, hidden.boolValue == false {
DataManager.shared.addStationToIndex(station, index: searchableIndex)
} else {
DataManager.shared.removeStationFromIndex(station, index: searchableIndex)
}
}
} catch {
searchableIndex.deleteSearchableItems(withIdentifiers: [identifier], completionHandler: { (error) in
DLOG("Error: \(String(describing: error))")
})
continue
}
}
acknowledgementHandler()
}
}
| bsd-2-clause | d7c6a139918866da028d5ef9051b86d8 | 36.056604 | 180 | 0.656823 | 5.709302 | false | false | false | false |
blue42u/swift-t | stc/tests/407-foreach-8.swift | 4 | 412 | import assert;
(int o) f (int i) {
o = i;
}
main {
// Iterate over fixed range using both loop vars
foreach i, j in [2:5] {
trace("loop1", i, j);
assert(i >= 2 && i <= 5, "loop1 range");
}
foreach i, j in [f(2):f(5)] {
trace("loop2", i, j);
assert(i >= 2 && i <= 5, "loop2 range");
}
foreach i, j in [1:1] {
trace("loop3", i, j);
assert(i == 1, "loop3 range");
}
}
| apache-2.0 | 8825fbcfc1572362ea9e9dee6ac6d2d0 | 17.727273 | 50 | 0.485437 | 2.607595 | false | false | false | false |
GrinnellAppDev/KDIC-Radio-iOS | KDIC/FeedViewController.swift | 1 | 2693 | import UIKit
class ScheduleViewController: UIViewController , UITableViewDataSource {
@IBOutlet weak var daySegmntCntrl: UISegmentedControl!
var dayScheduleKeysArray = [AnyObject]()
var dayScheduleValuesArray = [AnyObject]()
@IBOutlet weak var scheduleTableView: UITableView!
var kdicScrapperReqs: KDICScrapperReqs?
@IBOutlet weak var scheduleDataLoadingIndicator: UIActivityIndicatorView!
var scheduleUrlStr = "http://kdic.grinnell.edu/scheduleScript.php"
override func viewDidLoad() {
super.viewDidLoad()
self.kdicScrapperReqs = KDICScrapperReqs(urlStr: scheduleUrlStr, tableView: scheduleTableView, completionCall: loadInitialTableData)
self.kdicScrapperReqs?.get_data_from_url()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dayScheduleKeysArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ScheduleCell", forIndexPath: indexPath) as! ScheduleTableCell
let showTime = self.dayScheduleKeysArray[indexPath.row] as! String
let showName = self.dayScheduleValuesArray[indexPath.row] as! String
cell.showTime.text = showTime
cell.showName.text = showName
return cell
}
@IBAction func dayChanged(sender: AnyObject) {
switch daySegmntCntrl.selectedSegmentIndex
{
case 0:
loadTableData("Monday")
case 1:
loadTableData("Tuesday")
case 2:
loadTableData("Wednesday")
case 3:
loadTableData("Thursday")
case 4:
loadTableData("Friday")
case 5:
loadTableData("Saturday")
case 6:
loadTableData("Sunday")
default:
break;
}
}
//method called after asynch req is done
func loadInitialTableData(){
loadTableData("Monday")
}
func loadTableData(day: String){
let scheduleDictionary = self.kdicScrapperReqs!.jsonDictionary!["data"]![day]! as! NSDictionary as Dictionary
self.dayScheduleKeysArray = Array(scheduleDictionary.keys)
self.dayScheduleValuesArray = Array(scheduleDictionary.values)
scheduleDataLoadingIndicator.stopAnimating()
scheduleDataLoadingIndicator.hidden = true
self.scheduleTableView.reloadData()
}
}
| gpl-2.0 | 79add0dee60b5ae412e8c700ee0cc1cd | 30.682353 | 140 | 0.65466 | 5.14914 | false | false | false | false |
sol/aeson | tests/JSONTestSuite/parsers/test_STJSON/STJSON/main.swift | 6 | 1099 | //
// main.swift
// STJSON
//
// Created by Nicolas Seriot on 17.10.16.
// Copyright © 2016 ch.seriot. All rights reserved.
//
import Foundation
func main() {
guard ProcessInfo.processInfo.arguments.count == 2 else {
let url = URL(fileURLWithPath: ProcessInfo.processInfo.arguments[0])
let programName = url.lastPathComponent
print("Usage: ./\(programName) file.json")
exit(1)
}
let path = ProcessInfo.processInfo.arguments[1]
let url = NSURL.fileURL(withPath:path)
do {
let data = try Data(contentsOf:url)
//var p = JSONParser(data: data, maxParserDepth:10, options:[.useUnicodeReplacementCharacter])
var p = STJSONParser(data: data)
do {
let o = try p.parse()
guard o != nil else {
exit(1)
}
exit(0)
} catch let e {
print(e)
exit(1)
}
} catch let e {
print("*** CANNOT READ DATA AT \(url)")
print(e)
exit(1)
}
}
main()
| bsd-3-clause | 600920deb21f27209050408011eecb5a | 22.361702 | 102 | 0.528233 | 4.081784 | false | false | false | false |
andrebocchini/SwiftChattyOSX | SwiftChattyOSX/Threads/ThreadManager.swift | 1 | 9982 | //
// ThreadManager.swift
// SwiftChattyOSX
//
// Created by Andre Bocchini on 4/1/16.
// Copyright (c) 2016 Andre Bocchini. All rights reserved.
//
import SwiftChatty
class ThreadManager {
private var unreadThreadIds = Set<Int>()
private var readThreadIds = Set<Int>()
private var unreadPostIds = Set<Int>()
private var readPostIds = Set<Int>()
private let userDefaults = NSUserDefaults.standardUserDefaults()
private var selectedThreadId = 0
private var selectedPostId = 0
var selectedThread: Thread {
for thread in self.threads {
if thread.id == self.selectedThreadId {
return thread
}
}
return Thread()
}
var selectedPost: Post {
for post in self.selectedThread.posts {
if post.id == self.selectedPostId {
return post
}
}
return Post()
}
var firstThread: Thread {
if let thread = self.threads.first {
return thread
}
return Thread()
}
var firstPost: Post {
if let post = self.selectedThread.posts.first {
return post
}
return Post()
}
var threads = [Thread]() {
didSet {
for (index, var thread) in self.threads.enumerate() {
thread.sort(.ThreadedOldestFirst)
self.threads[index] = thread
}
cleanupUnreadAndExpiredThreads(self.threads)
cleanupUnreadAndExpiredPosts(self.threads)
markNewThreadsUnread()
markNewPostsUnread()
}
}
var pinnedThreads: [Thread] {
let pinnedThreadIds = loadPinnedThreadIdsFromUserDefaults()
var updatedPinnedThreadIds = [Int]()
var pinnedThreads = [Thread]()
for threadId in pinnedThreadIds {
for thread in self.threads {
if thread.id == threadId {
pinnedThreads.append(thread)
updatedPinnedThreadIds.append(threadId)
}
}
}
savePinnedThreadIdsToUserDefaults(updatedPinnedThreadIds)
return pinnedThreads
}
init(threads: [Thread]) {
self.threads = threads
loadReadStatusesFromUserDefaults()
}
func threadForId(id: Int) -> Thread {
for thread in self.threads {
if thread.id == id {
return thread
}
}
return Thread()
}
func selectFirstThread() {
if let firstThread = self.threads.first {
selectThread(firstThread)
}
}
func selectFirstPost() {
selectPost(self.selectedThread.rootPost())
}
func selectThread(thread: Thread) {
self.selectedThreadId = thread.id
markThreadAsRead(thread)
selectFirstPost()
}
func selectPost(post: Post) {
self.selectedThreadId = post.threadId
self.selectedPostId = post.id
markPostAsRead(post)
}
// MARK: Events
func processNewPostEvent(newPost: Post, parentAuthor: String?) {
for (index, var thread) in self.threads.enumerate() {
if thread.id == newPost.threadId {
thread.posts.append(newPost)
thread.sort(.ThreadedOldestFirst)
self.threads[index] = thread
if !isPostUnread(newPost) {
markPostUnread(newPost)
}
}
}
}
func processLolCountsUpdateEvent(updates: [LolCountUpdate]) {
for update in updates {
for (threadIndex, var thread) in self.threads.enumerate() {
for (postIndex, var post) in thread.posts.enumerate() {
if post.id == update.postId {
for (lolIndex, var lol) in post.lols.enumerate() {
if lol.tag == update.tag {
lol.count = update.count
post.lols[lolIndex] = lol
}
}
thread.posts[postIndex] = post
self.threads[threadIndex] = thread
}
}
}
}
}
func processCategoryChangeEvent(category: ModerationFlag, updatedPostId: Int) {
for (threadIndex, var thread) in self.threads.enumerate() {
for (postIndex, var post) in thread.posts.enumerate() {
if post.id == updatedPostId {
post.category = category
thread.posts[postIndex] = post
self.threads[threadIndex] = thread
}
}
}
}
// MARK: Pinned threads
private func loadPinnedThreadIdsFromUserDefaults() -> [Int] {
if let pinnedThreadIds = self.userDefaults.objectForKey(Preferences.PinnedThreads.rawValue) as? [Int] {
return pinnedThreadIds
} else {
return [Int]()
}
}
private func savePinnedThreadIdsToUserDefaults(pinnedThreadIds: [Int]) {
self.userDefaults.setObject(pinnedThreadIds, forKey: Preferences.PinnedThreads.rawValue)
}
func pinThread(thread: Thread) {
thread.pin()
}
func unpinThread(thread: Thread) {
thread.unPin()
}
// MARK: Read/Unread operations
func loadReadStatusesFromUserDefaults() {
self.readThreadIds = Set<Int>()
self.readPostIds = Set<Int>()
self.unreadThreadIds = Set<Int>()
self.unreadPostIds = Set<Int>()
if let ids = self.userDefaults.objectForKey(Preferences.ReadThreadIds.rawValue) as? [Int] {
for id in ids {
self.readThreadIds.insert(id)
}
}
if let ids = self.userDefaults.objectForKey(Preferences.UnreadThreadIds.rawValue) as? [Int] {
for id in ids {
self.unreadThreadIds.insert(id)
}
}
if let ids = self.userDefaults.objectForKey(Preferences.ReadPostIds.rawValue) as? [Int] {
for id in ids {
self.readPostIds.insert(id)
}
}
if let ids = self.userDefaults.objectForKey(Preferences.UnreadPostIds.rawValue) as? [Int] {
for id in ids {
self.unreadPostIds.insert(id)
}
}
}
func saveReadStatusesToUserDefaults() {
self.userDefaults.setObject(Array(self.readThreadIds), forKey: Preferences.ReadThreadIds.rawValue)
self.userDefaults.setObject(Array(self.unreadThreadIds), forKey: Preferences.UnreadThreadIds.rawValue)
self.userDefaults.setObject(Array(self.readPostIds), forKey: Preferences.ReadPostIds.rawValue)
self.userDefaults.setObject(Array(self.unreadPostIds), forKey: Preferences.UnreadPostIds.rawValue)
}
private func markNewThreadsUnread() {
for thread in self.threads {
if isNewThread(thread) {
markThreadUnread(thread)
}
}
}
private func markNewPostsUnread() {
for thread in self.threads {
for post in thread.posts {
if isNewPost(post) && post.parentId != 0 {
markPostUnread(post)
}
}
}
}
private func isNewThread(thread: Thread) -> Bool {
return !self.unreadThreadIds.contains(thread.id) && !self.readThreadIds.contains(thread.id)
}
func isThreadUnread(thread: Thread) -> Bool {
return self.unreadThreadIds.contains(thread.id)
}
func markThreadAsRead(thread: Thread) {
self.unreadThreadIds.remove(thread.id)
self.readThreadIds.insert(thread.id)
saveReadStatusesToUserDefaults()
}
func markThreadUnread(thread: Thread) {
self.unreadThreadIds.insert(thread.id)
self.readThreadIds.remove(thread.id)
saveReadStatusesToUserDefaults()
}
private func isNewPost(post: Post) -> Bool {
return !self.unreadPostIds.contains(post.id) && !self.readPostIds.contains(post.id)
}
func isPostUnread(post: Post) -> Bool {
return self.unreadPostIds.contains(post.id)
}
func markPostAsRead(post: Post) {
self.unreadPostIds.remove(post.id)
self.readPostIds.insert(post.id)
saveReadStatusesToUserDefaults()
}
func markPostUnread(post: Post) {
self.unreadPostIds.insert(post.id)
self.readPostIds.remove(post.id)
saveReadStatusesToUserDefaults()
}
func unreadRepliesCount(thread: Thread) -> Int {
var unreadReplies = [Post]()
for post in thread.posts {
for postId in self.unreadPostIds {
if postId == post.id {
unreadReplies.append(post)
}
}
}
return unreadReplies.count
}
private func cleanupUnreadAndExpiredThreads(newThreads: [Thread]) {
let combinedThreadIds = self.unreadThreadIds.union(self.readThreadIds)
var newThreadIds = [Int]()
for thread in newThreads {
newThreadIds.append(thread.id)
}
for threadId in combinedThreadIds {
if !newThreadIds.contains(threadId) {
self.unreadThreadIds.remove(threadId)
self.readThreadIds.remove(threadId)
}
}
}
private func cleanupUnreadAndExpiredPosts(newThreads: [Thread]) {
let combinedPostIds = self.unreadPostIds.union(self.readPostIds)
var newPostIds = [Int]()
for thread in newThreads {
for post in thread.posts {
newPostIds.append(post.id)
}
}
for postId in combinedPostIds {
if !newPostIds.contains(postId) {
self.unreadPostIds.remove(postId)
self.readPostIds.remove(postId)
}
}
}
}
| mit | 738d6386d7d3fa1a092ebab70fc8dace | 27.683908 | 111 | 0.571328 | 4.535211 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Spring Fling/FlingViewController.swift | 1 | 14135 | //
// FlingViewController.swift
// PennMobile
//
// Created by Josh Doman on 3/10/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
//
// import Foundation
// import ZoomImageView
// import SafariServices
//
// protocol FlingCellDelegate: ModularTableViewCellDelegate, URLSelectable {}
//
// final class FlingTableViewModel: ModularTableViewModel {}
//
// final class FlingViewController: GenericViewController, HairlineRemovable, IndicatorEnabled {
//
// fileprivate var performersTableView: ModularTableView!
// fileprivate var scheduleTableView: UITableView!
// fileprivate var model: FlingTableViewModel!
// fileprivate var headerToolbar: UIToolbar!
//
// // TEMP COLORS - TO be deleted in favor of General/Extensions
// fileprivate static var navigation = UIColor(r: 74, g: 144, b: 226)
// fileprivate static var baseGreen = UIColor(r: 118, g: 191, b: 150)
// fileprivate static var yellowLight = UIColor(r: 240, g: 180, b: 0)
//
// // For Map Zoom
// fileprivate var mapImageView: ZoomImageView!
//
// fileprivate var performers = [FlingPerformer]()
//
// fileprivate var checkInWebview: SFSafariViewController!
// fileprivate var checkInUrl = "https://docs.google.com/forms/d/e/1FAIpQLSexkehYfGgyAa7RagaCl8rze4KUKQSX9TbcvvA6iXp34TyHew/viewform"
//
// override func viewDidLoad() {
// super.viewDidLoad()
// self.title = "Spring Fling"
//
// setupThisNavBar()
// prepareScheduleTableView()
// preparePerformersTableView()
// prepareMapImageView()
// prepareCheckInButton()
//
// performersTableView.isHidden = false
// scheduleTableView.isHidden = true
// mapImageView.isHidden = true
//
// self.showActivity()
// self.fetchViewModel {
// // TODO: do something when fetch has completed
// self.hideActivity()
// }
//
// FirebaseAnalyticsManager.shared.trackEvent(action: "Viewed Fling", result: "Viewed Fling", content: "Fling page")
// }
//
// override func viewWillAppear(_ animated: Bool) {
// super.viewWillAppear(animated)
// if let navbar = navigationController?.navigationBar {
// removeHairline(from: navbar)
// }
// }
//
// func setupThisNavBar() {
// //removes hairline from bottom of navbar
// if let navbar = navigationController?.navigationBar {
// removeHairline(from: navbar)
// }
//
// let width = view.frame.width
//
// guard let headerFrame = navigationController?.navigationBar.frame else {
// return
// }
//
// headerToolbar = UIToolbar(frame: CGRect(x: 0, y: 64, width: width, height: headerFrame.height + headerFrame.origin.y))
// headerToolbar.backgroundColor = navigationController?.navigationBar.backgroundColor
//
// let newsSwitcher = UISegmentedControl(items: ["Performers", "Schedule", "Map"])
// newsSwitcher.center = CGPoint(x: width/2, y: 64 + headerToolbar.frame.size.height/2)
// newsSwitcher.tintColor = UIColor.navigation
// newsSwitcher.selectedSegmentIndex = 0
// newsSwitcher.isUserInteractionEnabled = true
// newsSwitcher.addTarget(self, action: #selector(switchTabMode(_:)), for: .valueChanged)
//
// view.addSubview(headerToolbar)
// view.addSubview(newsSwitcher)
// }
//
// @objc internal func switchTabMode(_ segment: UISegmentedControl) {
// performersTableView.isHidden = segment.selectedSegmentIndex == 0 ? false : true
// scheduleTableView.isHidden = segment.selectedSegmentIndex == 1 ? false : true
// mapImageView.isHidden = segment.selectedSegmentIndex == 2 ? false : true
// }
// }
//
// extension FlingViewController: UITableViewDelegate, UITableViewDataSource {
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return performers.count
// }
//
// func numberOfSections(in tableView: UITableView) -> Int {
// return 1
// }
//
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineTableViewCell",
// for: indexPath) as! TimelineTableViewCell
//
// cell.backgroundColor = .white
//
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "h:mm"
// let dateFormatterTwelveHour = DateFormatter()
// dateFormatterTwelveHour.dateFormat = "h:mm a"
//
// var (title, description) = ("", "")
// var (startTime, endTime) : (Date?, Date?)
//
// let performer = performers[indexPath.row]
// (title, description, startTime, endTime) = (performer.name,
// "\(dateFormatter.string(from: performer.startTime)) - \(dateFormatterTwelveHour.string(from: performer.endTime))",
// performer.startTime, performer.endTime)
//
//
// if (indexPath.row > 0) {
// cell.timeline.frontColor = .lightGray
// } else {
// cell.timeline.frontColor = .clear
// }
//
// if (startTime != nil && endTime != nil && startTime! < Date() && endTime! > Date()) {
// cell.timeline.backColor = FlingViewController.yellowLight
// cell.bubbleColor = FlingViewController.yellowLight
// cell.timelinePoint = TimelinePoint(color: FlingViewController.yellowLight, filled: true)
// } else {
// cell.timeline.backColor = .lightGray
// cell.bubbleColor = FlingViewController.baseGreen
// cell.timelinePoint = TimelinePoint(color: .lightGray, filled: true)
// }
//
// cell.titleLabel.text = title
// cell.descriptionLabel.text = description
// cell.descriptionLabel.font = UIFont(name: "AvenirNext-Regular", size: 16)
// cell.descriptionLabel.textColor = UIColor(r: 63, g: 63, b: 63)
//
// //cell.lineInfoLabel.text = lineInfo
// /*if indexPath.row != 5 {
// cell.bubbleColor = FlingViewController.baseGreen
// } else {
// cell.bubbleColor = FlingViewController.yellowLight
// }
// if let thumbnail = thumbnail {
// cell.thumbnailImageView.image = UIImage(named: thumbnail)
// }
// else {
// cell.thumbnailImageView.image = nil
// }
// if let illustration = illustration {
// cell.illustrationImageView.image = UIImage(named: illustration)
// }
// else {
// cell.illustrationImageView.image = nil
// }*/
//
// return cell
// }
//
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return "Saturday, April 13th"
// }
//
// func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// return 50
// }
//
// func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// if let view = view as? UITableViewHeaderFooterView {
// // Customize header view
// view.textLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 24)
// view.textLabel?.textColor = UIColor(r: 63, g: 63, b: 63)
// view.textLabel?.widthAnchor.constraint(equalToConstant: 300)
// view.contentView.backgroundColor = UIColor.clear
//
// // Add divider line to header view
// let dividerLine = UIView()
// dividerLine.backgroundColor = .lightGray
// view.addSubview(dividerLine)
// dividerLine.translatesAutoresizingMaskIntoConstraints = false
// dividerLine.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
// dividerLine.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
// dividerLine.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
// dividerLine.heightAnchor.constraint(equalToConstant: 1).isActive = true
// }
// }
//
// }
//
// MARK: - Networking
// extension FlingViewController {
// func fetchViewModel(_ completion: @escaping () -> Void) {
// FlingNetworkManager.instance.fetchModel { (model) in
// guard let model = model else { return }
// if let prevItems = self.model?.items as? [HomeFlingCellItem], let items = model.items as? [HomeFlingCellItem], prevItems.equals(items) { return }
// DispatchQueue.main.async {
// self.setPerformersTableViewModel(model)
// self.performersTableView.reloadData()
// self.setScheduleTableViewModel(model)
// self.scheduleTableView.reloadData()
// self.fetchCellSpecificData {
// // TODO: do something when done fetching cell specific data
// }
// completion()
// }
// }
// }
//
// func fetchCellSpecificData(_ completion: (() -> Void)? = nil) {
// guard let items = model.items as? [HomeCellItem] else { return }
// HomeAsynchronousAPIFetching.instance.fetchData(for: items, singleCompletion: { (item) in
// DispatchQueue.main.async {
// let row = items.firstIndex(where: { (thisItem) -> Bool in
// thisItem.equals(item: item)
// })!
// let indexPath = IndexPath(row: row, section: 0)
// self.performersTableView.reloadRows(at: [indexPath], with: .none)
// }
// }) {
// DispatchQueue.main.async {
// completion?()
// }
// }
// }
//
//
// func setPerformersTableViewModel(_ model: FlingTableViewModel) {
// self.model = model
// self.model.delegate = self
// performersTableView.model = self.model
// }
//
// func setScheduleTableViewModel(_ model: FlingTableViewModel) {
// performers = model.items.map { (item) -> FlingPerformer in
// let flingItem = item as! HomeFlingCellItem
// return flingItem.performer
// }
// performers.sort(by: { ($0.startTime < $1.startTime) })
// }
// }
//
// MARK: - ModularTableViewDelegate
// extension FlingViewController: FlingCellDelegate {
// func handleUrlPressed(urlStr: String, title: String, item: ModularTableViewItem, shouldLog: Bool) {
// checkInWebview = SFSafariViewController(url: URL(string: checkInUrl)!)
// navigationController?.present(checkInWebview, animated: true)
// FirebaseAnalyticsManager.shared.trackEvent(action: "Fling Check-In", result: "Fling Check-In", content: "Fling Check-In")
// }
// }
//
// MARK: - Check In
// extension FlingViewController {
// fileprivate func prepareCheckInButton() {
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Check-In", style: .done, target: self, action: #selector(handleCheckInButtonPressed(_:)))
// }
//
// @objc fileprivate func handleCheckInButtonPressed(_ sender: Any?) {
// checkInWebview = SFSafariViewController(url: URL(string: checkInUrl)!)
// navigationController?.present(checkInWebview, animated: true)
// }
// }
//
// MARK: - Map Image
// extension FlingViewController {
// fileprivate func prepareMapImageView() {
// mapImageView = ZoomImageView()
// mapImageView.image = UIImage(named: "Fling_Map")
//
// view.addSubview(mapImageView)
//
// mapImageView.anchorToTop(nil, left: view.leftAnchor, bottom: nil, right: view.rightAnchor)
// mapImageView.topAnchor.constraint(equalTo: headerToolbar.bottomAnchor, constant: 0).isActive = true
// mapImageView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
// }
// }
//
// MARK: - Prepare TableViews
// extension FlingViewController {
// func prepareScheduleTableView() {
// scheduleTableView = UITableView()
// scheduleTableView.backgroundColor = .uiBackground
// scheduleTableView.separatorStyle = .none
// scheduleTableView.allowsSelection = false
// scheduleTableView.showsVerticalScrollIndicator = false
//
// // Initialize TimelineTableViewCell
// let bundle = Bundle(for: TimelineTableViewCell.self)
// let nibUrl = bundle.url(forResource: "TimelineTableViewCell", withExtension: "bundle")
// let timelineTableViewCellNib = UINib(nibName: "TimelineTableViewCell", bundle: Bundle(url: nibUrl!)!)
// scheduleTableView.register(timelineTableViewCellNib, forCellReuseIdentifier: "TimelineTableViewCell")
//
// scheduleTableView.delegate = self
// scheduleTableView.dataSource = self
//
// view.addSubview(scheduleTableView)
//
// scheduleTableView.anchorToTop(nil, left: view.leftAnchor, bottom: nil, right: view.rightAnchor)
// scheduleTableView.topAnchor.constraint(equalTo: headerToolbar.bottomAnchor, constant: 0).isActive = true
// scheduleTableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
// }
//
// func preparePerformersTableView() {
// performersTableView = ModularTableView()
// performersTableView.backgroundColor = .clear
// performersTableView.separatorStyle = .none
//
// view.addSubview(performersTableView)
//
// performersTableView.anchorToTop(nil, left: view.leftAnchor, bottom: nil, right: view.rightAnchor)
// performersTableView.topAnchor.constraint(equalTo: headerToolbar.bottomAnchor, constant: 0).isActive = true
// performersTableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
//
// performersTableView.tableFooterView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 30.0))
//
// HomeItemTypes.instance.registerCells(for: performersTableView)
// }
// }
//
//
//
//
//
//
| mit | db3a9ecca07a1b7539440a606fd365d9 | 41.191045 | 172 | 0.638602 | 4.216587 | false | false | false | false |
morpheby/aTarantula | Plugins/ATARCrawlExampleWebsite/ATARCrawlExampleWebsite/crawling/crawlDrugSwitches.swift | 1 | 4795 | //
// crawlDrugSwitches.swift
// ATARCrawlExampleWebsite
//
// Created by Ilya Mikhaltsou on 9/18/17.
// Copyright © 2017 morpheby. All rights reserved.
//
import Foundation
import Kanna
import Regex
import TarantulaPluginCore
func crawlDrugSwitches(_ object: DrugSwitches, usingRepository repo: Repository, withPlugin plugin: ATARCrawlExampleWebsiteCrawlerPlugin) throws {
let objectUrl = repo.performAndWait {
object.objectUrl
}
guard !(repo.performAndWait { object.objectIsCrawled }) else {
return
}
let data = try plugin.networkManager?.stringData(url: objectUrl) ?? String(contentsOf: objectUrl)
if !checkLoggedIn(in: data) {
throw CrawlError(url: objectUrl, info: "Not logged in")
}
var relatedCrawlables: [CrawlableObject] = []
guard let html = Kanna.HTML(html: data, encoding: .utf8) else {
throw CrawlError(url: objectUrl, info: "Unable to parse HTML")
}
let switch_selector = ["switched_from_treatment", "switched_to_treatment"]
enum Selection: Int {
case from = 0
case to = 1
case error = -1
}
let selected = repo.performAndWait {
object.drug_from != nil ? Selection.from :
object.drug_to != nil ? Selection.to : Selection.error
}
guard selected != .error else {
// Discard the object — some drugs don't have one of those
repo.perform { repo.delete(object: object) }
return
}
let switched: [DrugSwitch] = {
html.xpath("//tr[@data-yah-key='\(switch_selector[selected.rawValue])']").flatMap { element in
guard let id_value_str = element.xpath("@data-yah-value").first?.text,
let id_value = Int(id_value_str) else { return nil }
let tmpArray = element.xpath("td | th")
guard tmpArray.count == 3,
let name = (tmpArray[0].xpath("text()").flatMap { x in x.text?.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { x in x.count != 0 }.first),
let countStr = tmpArray[1].text?.trimmingCharacters(in: .whitespacesAndNewlines),
let count = Int(countStr) else { return nil }
guard let assembledUrl = URL(string: "https://examplewebsite/treatments/show/\(id_value)") else { return nil }
let relatedObject: Treatment = repo.performAndWait {
let o = repo.readAllObjects(Treatment.self, withSelection: .object(url: assembledUrl)).first ??
repo.newObject(forUrl: assembledUrl, type: Treatment.self)
precondition(o.name == nil || o.name == name, "Invalid DrugSwitch parameters: Treatment names mismatch")
return o
}
relatedCrawlables.append(relatedObject)
let otherObject: DrugSwitch = repo.performAndWait {
let from: Treatment, to: Treatment
switch selected {
case .from:
from = object.drug_from!
to = relatedObject
case .to:
from = relatedObject
to = object.drug_to!
default:
fatalError("Unreachable")
}
// if let o = repo.readAllObjects(DrugSwitch.self,
// withPredicate: NSPredicate(format: "\(#keyPath(DrugSwitch.switched_from)) == %@ && \(#keyPath(DrugSwitch.switched_to)) == %@", argumentArray: [from, to])).first {
// assert(o.patients_count == Int64(count), "Invalid DrugSwitch parameters: patient_count mismatch. DS from \(from) to \(to). Original value: \(o.patients_count), New value: \(count)")
// return o
// } else {
// Apparently, those numbers are taken almost like if from the air. It is "normal"
// for one drug to list another here, and not vice versa, have different values, etc.
// So for the time being, we just make duplicates. We can decide what to do later.
let o = repo.newObject(type: DrugSwitch.self)
o.patients_count = Int64(count)
o.switched_from = from
o.switched_to = to
return o
// }
}
return otherObject
}
}() .flatMap { x in x }
// Store object
repo.perform {
object.originalHtml = data
object.drug_switch = Set(switched) as NSSet
object.objectIsCrawled = true
if needsToBeSelected(object: object, filterMethod: plugin.filterMethod) {
object.select(newObjects: relatedCrawlables)
} else {
object.unselect(newObjects: relatedCrawlables)
}
}
}
| gpl-3.0 | 9842bc03051f296186ad6bff20b31222 | 37.95935 | 211 | 0.584098 | 4.233216 | false | false | false | false |
jpaffrath/mpd-ios | mpd-ios/ViewControllerSongs.swift | 1 | 4352 | //
// ViewControllerSongs.swift
// mpd-ios
//
// Created by Julius Paffrath on 21.12.16.
// Copyright © 2016 Julius Paffrath. All rights reserved.
//
import UIKit
import Toast_Swift
class ViewControllerSongs: UITableViewController {
private let TAG_LABEL_SONGNAME: Int = 100
private let TAG_LABEL_SONGNR: Int = 101
private let TAG_LABEL_SONGTIME: Int = 102
private let COLOR_BLUE = UIColor.init(colorLiteralRed: Float(55.0/255), green: Float(111.0/255), blue: Float(165.0/255), alpha: 1)
private let TOAST_DURATION = 1.0
private var songs: [MPDSong] = []
var artist: String = ""
var album: String = ""
// MARK: Init
override func viewDidLoad() {
self.refreshControl = UIRefreshControl.init()
self.refreshControl?.backgroundColor = self.COLOR_BLUE
self.refreshControl?.tintColor = UIColor.white
self.refreshControl?.addTarget(self, action: #selector(ViewControllerSongs.reloadSongs), for: UIControlEvents.valueChanged)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .organize, target: self, action: #selector(ViewControllerSongs.addAllSongs))
}
override func viewWillAppear(_ animated: Bool) {
self.title = self.album
self.reloadSongs()
}
// MARK: Private Methods
func reloadSongs() {
MPD.sharedInstance.getSongs(forAlbum: self.album, byArtist: self.artist, handler: { (songs: [MPDSong]) in
self.songs = songs
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
})
}
func addAllSongs() {
MPD.sharedInstance.loadAlbum(name: self.album, fromArtist: self.artist) {
self.tableView.makeToast("Added \(self.album) to current playlist", duration: self.TOAST_DURATION, position: .center)
}
}
// MARK: TableView Delegates
override func numberOfSections(in tableView: UITableView) -> Int {
if self.songs.count > 0 {
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
self.tableView.backgroundView = nil
return 1
}
else {
let size = self.view.bounds.size
let labelMsg = UILabel.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height)))
labelMsg.text = "No songs available! Pull to refresh"
labelMsg.textColor = self.COLOR_BLUE
labelMsg.numberOfLines = 0
labelMsg.textAlignment = NSTextAlignment.center
labelMsg.font = UIFont.init(name: "Avenir", size: 20)
labelMsg.sizeToFit()
self.tableView.backgroundView = labelMsg
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
}
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.songs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let song = self.songs[indexPath.row]
let labelSongname: UILabel = cell.viewWithTag(self.TAG_LABEL_SONGNAME) as! UILabel
labelSongname.text = song.title
let labelSongnr: UILabel = cell.viewWithTag(self.TAG_LABEL_SONGNR) as! UILabel
labelSongnr.text = "\(song.track)."
let labelSongtime: UILabel = cell.viewWithTag(self.TAG_LABEL_SONGTIME) as! UILabel
labelSongtime.text = song.getSecondsString()
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let song = self.songs[indexPath.row]
MPD.sharedInstance.loadSong(title: song.title, fromAlbum: song.album, byArtist: song.artist) {
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.makeToast("Added \(song.title) to current playlist", duration: self.TOAST_DURATION, position: .center)
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
}
| gpl-3.0 | 1eb2c2c9395ce9ec5bc2f33a37356786 | 36.508621 | 162 | 0.650655 | 4.494835 | false | false | false | false |
silence0201/Swift-Study | SwiftLearn/MySwift07_function.playground/Contents.swift | 1 | 10325 | //: Playground - noun: a place where people can play
import UIKit
/*** Swift 函数 **/
func sayHello(name:String?) -> String{
return "Hello " + (name ?? "Guest")
}
sayHello(name: "kangqiao")
sayHello(name: nil)
func printHello1(){ //函数没有参数, 没有返回值
print("Hello1")
}
printHello1()
func printHello2() -> (){ //显示指定没有返回值 ()
print("hello2")
}
printHello2()
func printHello3() -> Void{
print("hello3")
}
printHello3()
var arr = [1, 2, 3]
arr.append(4)
arr.contains(1)
arr.index(of: 3) //swift3
arr.remove(at: 2) //swfit3
arr
var str : NSString = "1234"
//str.stringByTrimmingCharactersInSet(Set<Character>(["1","4"]))
func findMaxAndMin(numbers:[Int]) -> (max:Int, min:Int)? { //给元组命名分量的名字.
// if numbers.isEmpty{
// return nil
// }
guard numbers.count > 0 else{
return nil
}
var minValue = numbers[0]
var maxValue = numbers[0]
for number in numbers{
minValue = minValue < number ? minValue : number
maxValue = maxValue > number ? maxValue : number
}
return (max: maxValue, min:minValue)
}
var scores : [Int]? = [202, 123, 2345, 232, 89, 5555] //若从网络返回时, scores可能是nil.
scores = scores ?? [] //当使用可选型时, 进行解包.若为nil时, 默认指定为[]空数组.
if let result = findMaxAndMin(numbers: scores!){ //上一行已经进行解包,设置初值空数组, 所以这里用!号强制解包使用.
print("The max score is \(result.max)")
print("The min score is \(result.min)")
}
func sayHelloTo(name: String, greeting:String) -> String{
return "\(greeting), \(name)"
}
//*** swift2函数调用时, 第一个参数可以不用写参数名, 第二个参数开始必须写参数名 *** //swift2
//sayHelloTo("Playground", greeting: "hello") //swift2 error
//*** swift3函数调用时, 参数<必须>写参数名 *** //swift3
sayHelloTo(name: "Playground", greeting: "hello")
var str1 = "hello, palyground"
//str1.replaceRange(str1.startIndex..<str1.startIndex.advancedBy(5), with: "Hi") //swfit2
//str1.replaceSubrange(bounds: str1.startIndex..<str1.index(str1.startIndex, offsetBy: 5) , with: "Hi"); //swift3
//str1.stringByReplacingOccurrencesOfString("Hi", withString: "Morning") //swift2
str1.replacingOccurrences(of: "Hi", with: "Morning") //swift3
//*** swift3 函数参数全名, 外部参数名与内部参数名, 同时保证函数体内与调用者的语义明确
//swift3第一个参数同其他的参数一样, 遵循外部参数名和内部参数名, 不写外部参数名, 调用时, 就用内部参数, 写了外部参数名, 调用时, 就必须用
//定义时, 指定参数的默认值, 则调用时, 可不给赋值.
//swift3 在调用时所有参数必须按顺序调用.
//建议将有默认值的参数放在函数参数列表的后面.
func sayHelloTo2(to name: String, greeting:String = "Hello"
, punctuation:String = "!") -> String{
return "\(greeting), \(name) \(punctuation)"
}
//函数定义时, 若指定了外部参数名, 则调用时, 必须使用外部参数名
sayHelloTo2(to: "Playground", greeting: "hello")
//error: argument 'to' must precede argument 'withGreetingWord'
sayHelloTo2(to: "Playground", greeting: "hello", punctuation: "Hi") //swift3中参数必须按顺序调用
sayHelloTo2(to: "kangqiao") //必须指定外部参数名"to"
func mutipleOf(num1: Int, and num2: Int) -> Int{
return num1 * num2
}
//*** swift函数调用时, 第一个参数可以不用写外部参数名, 第二个参数开始必须写参数名 ***
mutipleOf(num1: 4, and: 2)
//使用下划线忽略参数的外部名
func mutiply(num1: Int, _ num2: Int) -> Int{
return num1 * num2
}
mutiply(num1: 4, 3)
func sayHelloTo3(name: String = "playground", withGreetingWord greeting:String = "Hello"
, punctuation:String = "!") -> String{
return "\(greeting), \(name) \(punctuation)"
}
sayHelloTo3() //无参数调用
sayHelloTo3(name: "kang", withGreetingWord: "Hi", punctuation: "...") //swift3参数必须按顺序调用
sayHelloTo3(name: "Kang") //只指定第一个参数.
print("Hello", 1, 2, 3, 4, "hi", separator:", ", terminator:"++")
print("")
//变长参数类型的函数
func mean(numbers: Double ...) -> Double{
var sum: Double = 0
//将变长参数当做一个数组看待
for number in numbers{
sum += number
}
return sum/Double(numbers.count)
}
mean(numbers: 2)
mean(numbers: 2, 3)
mean(numbers: 2, 5, 6, 77, 99, 90)
//变长参数的应用.
func sayHelloTo4( names:String ... , withGreetingWord greeting:String, punctuation:String){
for name in names{
print("\(greeting), \(name) \(punctuation)")
}
}
sayHelloTo4(names: "A", "B", "C", withGreetingWord: "Hi", punctuation: "!!!")
//函数的参数定义时默认是let修饰为常量, 不能在函数体中改变它. 若想改变它, 则显示用var修饰. //swift2
func toBinary( num: Int) -> String{ //swift3 中参数不能用var修饰了, 若要在内部使用它, 在函数开头声明为var, 若要影响它, 则用inout
var num = num
var res = ""
repeat{
res = String(num % 2) + res
num /= 2
}while num != 0
return res
}
toBinary(num: 12)
var p = 100
toBinary(num: p) //1100100
p //100 x并没有因为调用toBinary函数而被改变.
//交换参数的值, 但是这样并不会真正的交换函数调用外的变量的值.
func swapTwoInts( a: Int, _ b: Int){
var a = a
var b = b
let t: Int = a
a = b
b = t
}
var x: Int = 1
var y: Int = 2
swapTwoInts(a: x, y)
print(x)
print(y)
//函数的引用传递 inout
func swapTwoInts2( a: inout Int, _ b: inout Int){ //swift3中 inout作为类型修饰, 放在:冒号后面.
// let t: Int = a
// a = b
// b = t
(a,b)=(b,a) //利用元组进行数据的交换.
}
swapTwoInts2(a: &x, &y) //使用x和y的引用传递.
print("swapTwoInts2 after x" , x)
print("swapTwoInts2 after y", y)
//Swift中的参数默认是传值, 若要改变参数在函数体外的实际值, 必须使用inout.
func initArray(arr: inout [Int], by value: Int){
for i in 0..<arr.count{
arr[i] = value
}
}
var arr2 = [1, 2, 3, 4]
initArray(arr: &arr2, by: 0)
arr2
/*** 函数型变量 **/
func add( a: Int, _ b: Int) -> Int{
return a + b
}
let anotherAdd = add //函数型变量, 将函数传递给变量anotherAdd变量.
anotherAdd(3, 4)
let anotherAdd2: (Int, Int)->Int = add //声明函数型变量的类型, 其由(参数元组) -> 返回值 组成.
anotherAdd2(3, 4)
func sayHelloTo5(name:String){ //没有返回值的函数.
print("hello, \(name)")
}
let anotherSayHelloTo5: (String)->Void = sayHelloTo5
anotherSayHelloTo5("kang qiao") //"hello, kang qiao"
func sayHello6(){ //空的参数和空的返回值 的 类型函数.
print("hello")
}
/*** swift3 中规定函数的类型 参数列表必须用括号 **/
let anotherSayHello61 = sayHello6
let anotherSayHello62: ()->() = sayHello6
let anotherSayHello63: (Void)->() = sayHello6
let anotherSayHello64: (Void)->Void = sayHello6
let anotherSayHello65: (Void)->Void = sayHello6
/*** 对数组进行排序 **/
var arr3:[Int] = []
for _ in 0..<100{
arr3.append(Int(arc4random()) % 1000)
}
arr3
arr3.sort() //排序函数.
arr3
//从大到小的排序比较器.
func biggerNumberFirst(a: Int, _ b:Int) -> Bool{
return a > b
}
arr3.sorted(by: biggerNumberFirst) //swfit3
//按字典序排序.
func cmpByNumberString(a:Int, _ b:Int) -> Bool{
return String(a) < String(b)
}
arr3.sorted(by: cmpByNumberString)
//按靠近500的距离排序.
func near500(a:Int, _ b: Int)->Bool{
return abs(a - 500) < abs(b-500)
}
arr3.sorted(by: near500)
/***
* 函数式编程初步 -- 高阶函数
**/
//对每一个分数开平方再乘以10
func changeScores1( scores:inout [Int] ) {
for (index , score) in scores.enumerated(){
scores[index] = Int(sqrt(Double(score)) * 10)
}
}
//对每一个分数 150分按百分制计录.
func changeScores2( scores:inout [Int]){
for (index, score) in scores.enumerated(){
scores[index] = Int(Double(score) / 150.0 * 100.0)
}
}
var scores1 = [36, 61, 78, 89, 99]
changeScores1(scores: &scores1)
var scores2 = [88, 101, 124, 137, 150]
changeScores2(scores: &scores2)
//高阶函数式编程 ***
func changeScoresss( scores:inout [Int], by changeScore: (Int)->Int){
for (index, score) in scores.enumerated(){
scores[index] = changeScore(score)
}
}
func changeScore111(score:Int)->Int{
return Int(sqrt(Double(score))*10)
}
func changeScore222(score:Int)->Int{
return Int(Double(score)/150.0*100.0)
}
var scores111 = [36, 61, 78, 89, 99]
changeScoresss(scores: &scores111, by:changeScore111)
var scores222 = [88, 101, 124, 137, 150]
changeScoresss(scores: &scores222, by:changeScore222)
// Map 操作
var scores333 = [36, 61, 78, 89, 99]
scores333.map(changeScore111)
func isPassOrFail(score:Int)->String{
return score < 60 ? "Fail" : "Pass"
}
scores333.map(isPassOrFail)
scores333
// filter 操作
func fail(score:Int)->Bool{ //过滤不及格的分数.
return score < 60
}
scores333.filter(fail)
// reduce 操作
func addd(num1:Int, _ num2: Int) -> Int{
return num1 + num2
}
//第一个参数: 初值 , 第二个参数接合: 函数式参数.
scores333.reduce(0, addd)
scores333.reduce(0, +)
//将数组中的数据 以字符串的形式 接合在一起.
func concatenate( str: String, num: Int) -> String{
return str + String(num) + " "
}
scores333.reduce("", concatenate)
/*** 返回函数类型 和函数嵌套 **/
func tier1MailFeeByWeight(weight:Int)->Int{ //1块钱
return 1 * weight
}
func tier2MailFeeByWeight(weight:Int)->Int{ //3块钱
return 3 * weight
}
func feeByunitPrice(price:Int, weight:Int) -> Int{
//函数的嵌套. 作用是仅将chooseMailFeeCalculationByWeight暴露给函数feeByunitPrice使用.
func chooseMailFeeCalculationByWeight(weight:Int) -> (Int)->Int{
//如果weight 小于 10 使用 起价1函数, 否则起价2函数.
return weight <= 10 ? tier1MailFeeByWeight : tier2MailFeeByWeight
}
let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight: weight) //根据重量摆选择起价函数.
return mailFeeByWeight(weight) + price * weight //计算总价.
}
| mit | 4298240915fd188158e1396995d912a1 | 24.214706 | 113 | 0.658929 | 2.759253 | false | false | false | false |
Mazy-ma/MiaoShow | MiaoShow/MiaoShow/Classes/Live/ViewController/FilterImageViewController.swift | 1 | 2196 | //
// FilterImageViewController.swift
// MiaoShow
//
// Created by Mazy on 2017/4/23.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
import GPUImage
class FilterImageViewController: UIViewController {
var closeAction: (()->())?
// 创建视频源
// SessionPreset:屏幕分辨率,AVCaptureSessionPresetHigh会自适应高分辨率
// cameraPosition:摄像头方向
let videoCamera = GPUImageVideoCamera(sessionPreset: AVCaptureSessionPresetHigh, cameraPosition: AVCaptureDevicePosition.front)
// 创建最终预览View
let captureVideoPreview = GPUImageView(frame: UIScreen.main.bounds)
// 磨皮滤镜(美颜)
let bilateralFilter = GPUImageBilateralFilter()
// 美白滤镜
let brightnessFilter = GPUImageBrightnessFilter()
override func viewDidLoad() {
super.viewDidLoad()
// 设置为竖屏
videoCamera?.outputImageOrientation = .portrait
// 添加预览图层到最一个
view.insertSubview(captureVideoPreview, at: 0)
let groupFilter = GPUImageFilterGroup()
// 将磨皮和美白滤镜加入到滤镜组
groupFilter.addTarget(bilateralFilter)
groupFilter.addTarget(brightnessFilter)
// 设置滤镜组链
bilateralFilter.addTarget(brightnessFilter)
// 设置起始的滤镜
groupFilter.initialFilters = [bilateralFilter]
// 设置最后一个滤镜
groupFilter.terminalFilter = brightnessFilter
videoCamera?.addTarget(groupFilter)
groupFilter.addTarget(captureVideoPreview)
videoCamera?.startCapture()
}
/// 重写touchBegin 阻止响应链
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
@IBAction func closeCapture(_ sender: UIButton) {
videoCamera?.stopCapture()
captureVideoPreview.removeFromSuperview()
dismiss(animated: true) {
self.closeAction!()
}
}
/// 切换摄像头
@IBAction func switctAction(_ sender: UIButton) {
videoCamera?.rotateCamera()
}
}
| apache-2.0 | 79000c9850e142c48a6dc1a71765d328 | 26.625 | 131 | 0.648567 | 4.647196 | false | false | false | false |
kmikiy/SpotMenu | SpotMenu/AppDelegate/AppDelegate.swift | 1 | 13337 | //
// AppDelegate.swift
// SpotMenu
//
// Created by Miklós Kristyán on 02/09/16.
// Copyright © 2016 KM. All rights reserved.
//
import AppKit.NSAppearance
import Carbon.HIToolbox
import Cocoa
import MusicPlayer
import Sparkle
import Fabric
import Crashlytics
@NSApplicationMain
final class AppDelegate: NSObject, NSApplicationDelegate {
private enum Constants {
static let statusItemIconLength: CGFloat = 30
static let statusItemLength: CGFloat = 250
}
// MARK: - Properties
private var hudController: HudWindowController?
private var preferencesController: NSWindowController?
private var hiddenController: NSWindowController?
// private let popoverDelegate = PopOverDelegate()
private var eventMonitor: EventMonitor?
private let issuesURL = URL(string: "https://github.com/kmikiy/SpotMenu/issues")
private let kmikiyURL = URL(string: "https://github.com/kmikiy")
private let menu = StatusMenu().menu
private let spotMenuIcon = NSImage(named: NSImage.Name(rawValue: "StatusBarButtonImage"))
private let spotMenuIconItunes = NSImage(named: NSImage.Name(rawValue: "StatusBarButtonImageItunes"))
private var lastStatusTitle: String = ""
private var removeHudTimer: Timer?
private var musicPlayerManager: MusicPlayerManager!
private lazy var statusItem: NSStatusItem = {
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.length = Constants.statusItemIconLength
return statusItem
}()
private lazy var contentView: NSView? = {
let view = (statusItem.value(forKey: "window") as? NSWindow)?.contentView
return view
}()
private lazy var scrollingStatusItemView: ScrollingStatusItemView = {
let view = ScrollingStatusItemView()
view.translatesAutoresizingMaskIntoConstraints = false
view.icon = chooseIcon(musicPlayerName: MusicPlayerName(rawValue: UserPreferences.lastMusicPlayer)!)
view.lengthHandler = handleLength
return view
}()
private lazy var handleLength: StatusItemLengthUpdate = { length in
if length < Constants.statusItemLength {
self.statusItem.length = length
} else {
self.statusItem.length = Constants.statusItemLength
}
}
// MARK: - AppDelegate methods
func applicationDidFinishLaunching(_: Notification) {
Fabric.with([Crashlytics.self])
UserPreferences.initializeUserPreferences()
musicPlayerManager = MusicPlayerManager()
musicPlayerManager.add(musicPlayer: .spotify)
musicPlayerManager.add(musicPlayer: .iTunes)
musicPlayerManager.delegate = self
let lastMusicPlayerName = MusicPlayerName(rawValue: UserPreferences.lastMusicPlayer)!
let lastMusicPlayer = musicPlayerManager.existMusicPlayer(with: lastMusicPlayerName)
musicPlayerManager.currentPlayer = lastMusicPlayer
let popoverVC = PopOverViewController(nibName: NSNib.Name(rawValue: "PopOver"), bundle: nil)
popoverVC.setUpMusicPlayerManager()
hiddenController = (NSStoryboard(name: NSStoryboard.Name(rawValue: "Hidden"), bundle: nil).instantiateInitialController() as! NSWindowController)
hiddenController?.contentViewController = popoverVC
hiddenController?.window?.isOpaque = false
hiddenController?.window?.backgroundColor = .clear
hiddenController?.window?.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.floatingWindow)))
//hiddenController?.window?.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.maximumWindow)))
//hiddenController?.window?.ignoresMouseEvents = true
loadSubviews()
updateTitle()
eventMonitor = EventMonitor(mask: [NSEvent.EventTypeMask.leftMouseDown, NSEvent.EventTypeMask.rightMouseDown]) { [unowned self] event in
self.closePopover(event)
}
if UserPreferences.keyboardShortcutEnabled {
registerHotkey()
}
}
func applicationWillTerminate(_: Notification) {
// Insert code here to tear down your application
eventMonitor?.stop()
}
// MARK: - Public methods
func registerHotkey() {
guard let hotkeyCenter = DDHotKeyCenter.shared() else { return }
let modifiers: UInt = NSEvent.ModifierFlags.control.rawValue | NSEvent.ModifierFlags.shift.rawValue
// Register system-wide summon hotkey
hotkeyCenter.registerHotKey(withKeyCode: UInt16(kVK_ANSI_M),
modifierFlags: modifiers,
target: self,
action: #selector(AppDelegate.hotkeyAction),
object: nil)
hotkeyCenter.registerHotKey(withKeyCode: UInt16(kVK_LeftArrow),
modifierFlags: modifiers,
target: self,
action: #selector(AppDelegate.hotkeyActionLeft),
object: nil)
hotkeyCenter.registerHotKey(withKeyCode: UInt16(kVK_RightArrow),
modifierFlags: modifiers,
target: self,
action: #selector(AppDelegate.hotkeyActionRight),
object: nil)
hotkeyCenter.registerHotKey(withKeyCode: UInt16(kVK_Space),
modifierFlags: modifiers,
target: self,
action: #selector(AppDelegate.hotkeyActionSpace),
object: nil)
}
func unregisterHotKey() {
guard let hotkeyCenter = DDHotKeyCenter.shared() else { return }
hotkeyCenter.unregisterAllHotKeys()
}
@objc func hotkeyActionSpace() {
if (musicPlayerManager.currentPlayer?.playbackState == .paused){
musicPlayerManager.currentPlayer?.play()
} else {
musicPlayerManager.currentPlayer?.stop()
}
}
@objc func hotkeyActionRight() {
musicPlayerManager.currentPlayer?.playNext()
}
@objc func hotkeyActionLeft() {
musicPlayerManager.currentPlayer?.playPrevious()
}
@objc func hotkeyAction() {
let sb = NSStoryboard(name: NSStoryboard.Name(rawValue: "Hud"), bundle: nil)
hudController = sb.instantiateInitialController() as? HudWindowController
hudController!.setText(text: StatusItemBuilder(
title: musicPlayerManager.currentPlayer?.currentTrack?.title,
artist: musicPlayerManager.currentPlayer?.currentTrack?.artist,
albumName: musicPlayerManager.currentPlayer?.currentTrack?.album,
isPlaying: musicPlayerManager.currentPlayer?.playbackState == MusicPlaybackState.playing)
.hideWhenPaused(v: false)
.showTitle(v: true)
.showAlbumName(v: true)
.showArtist(v: true)
.showPlayingIcon(v: true)
.getString())
hudController?.showWindow(nil)
hudController?.window?.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
if let t = removeHudTimer {
t.invalidate()
}
removeHudTimer = Timer.scheduledTimer(
timeInterval: 4,
target: self,
selector: #selector(AppDelegate.removeHud),
userInfo: nil,
repeats: false)
}
@objc func removeHud() {
hudController = nil
}
@objc func updateTitle() {
let statusItemTitle = StatusItemBuilder(
title: musicPlayerManager.currentPlayer?.currentTrack?.title,
artist: musicPlayerManager.currentPlayer?.currentTrack?.artist,
albumName: musicPlayerManager.currentPlayer?.currentTrack?.album,
isPlaying: musicPlayerManager.currentPlayer?.playbackState == MusicPlaybackState.playing)
.hideWhenPaused(v: UserPreferences.hideTitleArtistWhenPaused)
.showTitle(v: UserPreferences.showTitle)
.showAlbumName(v: UserPreferences.showAlbumName)
.showArtist(v: UserPreferences.showArtist)
.showPlayingIcon(v: UserPreferences.showPlayingIcon)
.getString()
if lastStatusTitle != statusItemTitle {
updateTitle(newTitle: statusItemTitle)
}
}
// MARK: - Popover methods
@objc func openPrefs(_: NSMenuItem) {
preferencesController = (NSStoryboard(name: NSStoryboard.Name(rawValue: "Preferences"), bundle: nil).instantiateInitialController() as! NSWindowController)
preferencesController?.showWindow(self)
}
func openURL(url: URL?) {
if let url = url, NSWorkspace.shared.open(url) {
print("default browser was successfully opened")
}
}
@objc func openKmikiy(_: NSMenuItem) {
openURL(url: kmikiyURL)
}
@objc func openIssues(_: NSMenuItem) {
openURL(url: issuesURL)
}
@objc func quit(_: NSMenuItem) {
NSApp.terminate(self)
}
@objc func togglePopover(_ sender: AnyObject?) {
let event = NSApp.currentEvent!
switch (event.type, event.modifierFlags.contains(.control)) {
case (NSEvent.EventType.rightMouseUp, _),
(NSEvent.EventType.leftMouseUp, true) :
if hiddenController?.window?.isVisible ?? true {
closePopover(sender)
}
statusItem.menu = menu
statusItem.popUpMenu(menu)
// This is critical, otherwise clicks won't be processed again
statusItem.menu = nil
default:
if hiddenController?.window?.isVisible ?? true {
closePopover(sender)
} else {
// SpotifyAppleScript.startSpotify(hidden: true)
showPopover(sender)
}
}
}
@objc func checkForUpdates(_: NSMenuItem) {
SUUpdater.shared().checkForUpdates(nil)
}
// MARK: - Private methods
private func loadSubviews() {
guard let contentView = contentView else { return }
if let button = statusItem.button {
button.sendAction(on: [NSEvent.EventTypeMask.leftMouseUp, NSEvent.EventTypeMask.rightMouseUp])
button.action = #selector(AppDelegate.togglePopover(_:))
}
contentView.addSubview(scrollingStatusItemView)
NSLayoutConstraint.activate([
scrollingStatusItemView.topAnchor.constraint(equalTo: contentView.topAnchor),
scrollingStatusItemView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
scrollingStatusItemView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
scrollingStatusItemView.rightAnchor.constraint(equalTo: contentView.rightAnchor)])
}
private func updateTitle(newTitle: String) {
scrollingStatusItemView.icon = chooseIcon(musicPlayerName: musicPlayerManager.currentPlayer?.name)
scrollingStatusItemView.text = newTitle
lastStatusTitle = newTitle
if newTitle.count == 0 && statusItem.button != nil {
statusItem.length = scrollingStatusItemView.hasImage ? Constants.statusItemIconLength : 0
}
}
private func chooseIcon(musicPlayerName: MusicPlayerName?) -> NSImage! {
if !UserPreferences.showSpotMenuIcon {
return nil
}
if musicPlayerName == MusicPlayerName.iTunes {
return spotMenuIconItunes
} else {
return spotMenuIcon
}
}
private func showPopover(_: AnyObject?) {
let rect = statusItem.button?.window?.convertToScreen((statusItem.button?.frame)!)
let menubarHeight = rect?.height ?? 22
let height = hiddenController?.window?.frame.height ?? 300
let xOffset = UserPreferences.fixPopoverToTheRight ? ((hiddenController?.window?.contentView?.frame.minX)! - (statusItem.button?.frame.minX)!) : ((hiddenController?.window?.contentView?.frame.midX)! - (statusItem.button?.frame.midX)!)
let x = (rect?.origin.x)! - xOffset
let y = (rect?.origin.y)! // - (hiddenController?.contentViewController?.view.frame.maxY)!
hiddenController?.window?.setFrameOrigin(NSPoint(x: x, y: y-height+menubarHeight))
hiddenController?.showWindow(self)
eventMonitor?.start()
}
private func closePopover(_ sender: AnyObject?) {
hiddenController?.close()
eventMonitor?.stop()
}
}
extension AppDelegate: MusicPlayerManagerDelegate {
func manager(_: MusicPlayerManager, trackingPlayer _: MusicPlayer, didChangeTrack _: MusicTrack, atPosition _: TimeInterval) {
updateTitle()
}
func manager(_: MusicPlayerManager, trackingPlayer _: MusicPlayer, playbackStateChanged _: MusicPlaybackState, atPosition _: TimeInterval) {
updateTitle()
}
func manager(_: MusicPlayerManager, trackingPlayerDidQuit _: MusicPlayer) {
updateTitle()
}
func manager(_: MusicPlayerManager, trackingPlayerDidChange player: MusicPlayer) {
UserPreferences.lastMusicPlayer = player.name.rawValue
}
}
| mit | 08496530864b09db566885597f76e910 | 37.206304 | 242 | 0.648718 | 5.282884 | false | false | false | false |
czechboy0/XcodeServerSDK | XcodeServerSDK/API Routes/XcodeServer+Bot.swift | 1 | 8226 | //
// XcodeServer+Bot.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 01.07.2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
// MARK: - XcodeSever API Routes for Bot management
extension XcodeServer {
// MARK: Bot management
/**
Creates a new Bot from the passed in information. First validates Bot's Blueprint to make sure
that the credentials are sufficient to access the repository and that the communication between
the client and XCS will work fine. This might take a couple of seconds, depending on your proximity
to your XCS.
- parameter botOrder: Bot object which is wished to be created.
- parameter response: Response from the XCS.
*/
public final func createBot(botOrder: Bot, completion: (response: CreateBotResponse) -> ()) {
//first validate Blueprint
let blueprint = botOrder.configuration.sourceControlBlueprint
self.verifyGitCredentialsFromBlueprint(blueprint) { (response) -> () in
switch response {
case .Error(let error):
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
case .SSHFingerprintFailedToVerify(let fingerprint, _):
blueprint.certificateFingerprint = fingerprint
completion(response: XcodeServer.CreateBotResponse.BlueprintNeedsFixing(fixedBlueprint: blueprint))
return
case .Success(_, _): break
}
//blueprint verified, continue creating our new bot
//next, we need to fetch all the available platforms and pull out the one intended for this bot. (TODO: this could probably be sped up by smart caching)
self.getPlatforms({ (platforms, error) -> () in
if let error = error {
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
}
do {
//we have platforms, find the one in the bot config and replace it
try self.replacePlaceholderPlatformInBot(botOrder, platforms: platforms!)
} catch {
completion(response: .Error(error: error))
return
}
//cool, let's do it.
self.createBotNoValidation(botOrder, completion: completion)
})
}
}
/**
XCS API call for getting all available bots.
- parameter bots: Optional array of available bots.
- parameter error: Optional error.
*/
public final func getBots(completion: (bots: [Bot]?, error: NSError?) -> ()) {
self.sendRequestWithMethod(.GET, endpoint: .Bots, params: nil, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(bots: nil, error: error)
return
}
if let body = (body as? NSDictionary)?["results"] as? NSArray {
let (result, error): ([Bot]?, NSError?) = unthrow {
return try XcodeServerArray(body)
}
completion(bots: result, error: error)
} else {
completion(bots: nil, error: Error.withInfo("Wrong data returned: \(body)"))
}
}
}
/**
XCS API call for getting specific bot.
- parameter botTinyId: ID of bot about to be received.
- parameter bot: Optional Bot object.
- parameter error: Optional error.
*/
public final func getBot(botTinyId: String, completion: (bot: Bot?, error: NSError?) -> ()) {
let params = [
"bot": botTinyId
]
self.sendRequestWithMethod(.GET, endpoint: .Bots, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(bot: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (Bot?, NSError?) = unthrow {
return try Bot(json: body)
}
completion(bot: result, error: error)
} else {
completion(bot: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
XCS API call for deleting bot on specified revision.
- parameter botId: Bot's ID.
- parameter revision: Revision which should be deleted.
- parameter success: Operation result indicator.
- parameter error: Optional error.
*/
public final func deleteBot(botId: String, revision: String, completion: (success: Bool, error: NSError?) -> ()) {
let params = [
"rev": revision,
"bot": botId
]
self.sendRequestWithMethod(.DELETE, endpoint: .Bots, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(success: false, error: error)
return
}
if let response = response {
if response.statusCode == 204 {
completion(success: true, error: nil)
} else {
completion(success: false, error: Error.withInfo("Wrong status code: \(response.statusCode)"))
}
} else {
completion(success: false, error: Error.withInfo("Nil response"))
}
}
}
// MARK: Helpers
/**
Enum for handling Bot creation response.
- Success: Bot has been created successfully.
- BlueprintNeedsFixing: Source Control needs fixing.
- Error: Couldn't create Bot.
*/
public enum CreateBotResponse {
case Success(bot: Bot)
case BlueprintNeedsFixing(fixedBlueprint: SourceControlBlueprint)
case Error(error: ErrorType)
}
enum PlaceholderError: ErrorType {
case PlatformMissing
case DeviceFilterMissing
}
private func replacePlaceholderPlatformInBot(bot: Bot, platforms: [DevicePlatform]) throws {
if let filter = bot.configuration.deviceSpecification.filters.first {
let intendedPlatform = filter.platform
if let platform = platforms.findFirst({ $0.type == intendedPlatform.type }) {
//replace
filter.platform = platform
} else {
// Couldn't find intended platform in list of platforms
throw PlaceholderError.PlatformMissing
}
} else {
// Couldn't find device filter
throw PlaceholderError.DeviceFilterMissing
}
}
private func createBotNoValidation(botOrder: Bot, completion: (response: CreateBotResponse) -> ()) {
let body: NSDictionary = botOrder.dictionarify()
self.sendRequestWithMethod(.POST, endpoint: .Bots, params: nil, query: nil, body: body) { (response, body, error) -> () in
if let error = error {
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
}
guard let dictBody = body as? NSDictionary else {
let e = Error.withInfo("Wrong body \(body)")
completion(response: XcodeServer.CreateBotResponse.Error(error: e))
return
}
let (result, error): (Bot?, NSError?) = unthrow {
return try Bot(json: dictBody)
}
if let err = error {
completion(response: XcodeServer.CreateBotResponse.Error(error: err))
} else {
completion(response: XcodeServer.CreateBotResponse.Success(bot: result!))
}
}
}
}
| mit | 398c5f32319d31f1d863d27981070d3e | 35.878924 | 164 | 0.547787 | 5.185372 | false | false | false | false |
groue/RxGRDB | Documentation/RxGRDBDemo/RxGRDBDemo/UI/PlayersViewController.swift | 1 | 3860 | import UIKit
import RxDataSources
import RxSwift
/// An MVVM ViewController that displays PlayersViewModel
class PlayersViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var emptyView: UIView!
private let viewModel = PlayersViewModel()
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
setupToolbar()
setupTableView()
setupEmptyView()
}
private func setupNavigationItem() {
viewModel
.orderingButtonTitle
.subscribe(onNext: updateRightBarButtonItem)
.disposed(by: disposeBag)
}
private func updateRightBarButtonItem(title: String?) {
guard let title = title else {
navigationItem.rightBarButtonItem = nil
return
}
let barButtonItem = UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
barButtonItem.rx.action = viewModel.toggleOrdering
navigationItem.rightBarButtonItem = barButtonItem
}
private func setupToolbar() {
let deleteAllButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: nil, action: nil)
deleteAllButtonItem.rx.action = viewModel.deleteAll
let refreshButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: nil, action: nil)
refreshButtonItem.rx.action = viewModel.refresh
let stressTestButtonItem = UIBarButtonItem(title: "💣", style: .plain, target: nil, action: nil)
stressTestButtonItem.rx.action = viewModel.stressTest
toolbarItems = [
deleteAllButtonItem,
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
refreshButtonItem,
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
stressTestButtonItem,
]
}
private func setupTableView() {
let dataSource = RxTableViewSectionedAnimatedDataSource<Section>(configureCell: { (dataSource, tableView, indexPath, _) in
let section = dataSource.sectionModels[indexPath.section]
let player = section.items[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
cell.textLabel?.text = player.name
cell.detailTextLabel?.text = "\(player.score)"
return cell
})
dataSource.animationConfiguration = AnimationConfiguration(
insertAnimation: .fade,
reloadAnimation: .fade,
deleteAnimation: .fade)
dataSource.canEditRowAtIndexPath = { _, _ in true }
viewModel
.players
.asDriver(onErrorJustReturn: [])
.map { [Section(items: $0)] }
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx
.itemDeleted
.subscribe(onNext: { indexPath in
let player = dataSource[indexPath]
self.viewModel.deleteOne.execute(player)
})
.disposed(by: disposeBag)
}
private func setupEmptyView() {
viewModel
.players
.map { !$0.isEmpty }
.asDriver(onErrorJustReturn: false)
.drive(emptyView.rx.isHidden)
.disposed(by: disposeBag)
}
}
private struct Section {
var items: [Player]
}
extension Section: AnimatableSectionModelType {
var identity: Int { return 1 }
init(original: Section, items: [Player]) {
self.items = items
}
}
extension Player: IdentifiableType {
var identity: Int64 { return id! }
}
| mit | ef0894ca3a42d0f55173a517337ec432 | 33.132743 | 130 | 0.62406 | 5.494302 | false | false | false | false |
Brightify/Reactant | Source/Core/View/Impl/PickerView.swift | 2 | 1785 | //
// PickerView.swift
// Reactant
//
// Created by Matouš Hýbl on 02/04/2018.
// Copyright © 2018 Brightify. All rights reserved.
//
import RxSwift
#if os(iOS)
public class PickerView<MODEL>: ViewBase<MODEL, MODEL>, UIPickerViewDataSource, UIPickerViewDelegate {
private let pickerView = UIPickerView()
public let items: [MODEL]
public let titleSelection: (MODEL) -> String
public init(items: [MODEL], titleSelection: @escaping (MODEL) -> String) {
self.items = items
self.titleSelection = titleSelection
super.init()
}
public override func update() {
let title = titleSelection(componentState)
guard let index = items.firstIndex(where: { titleSelection($0) == title }) else { return }
pickerView.selectRow(index, inComponent: 0, animated: true)
}
public override func loadView() {
children(
pickerView
)
pickerView.dataSource = self
pickerView.delegate = self
}
public override func setupConstraints() {
pickerView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let model = items[row]
return titleSelection(model)
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let model = items[row]
perform(action: model)
}
}
#endif
| mit | 595be3dee231ef0ba741a404aa639325 | 26.415385 | 118 | 0.647587 | 4.72679 | false | false | false | false |
petester42/Moya | Source/Moya.swift | 1 | 11221 | import Foundation
import Alamofire
/// Closure to be executed when a request has completed.
public typealias Completion = (result: Moya.Result<Moya.Response, Moya.Error>) -> ()
/// Represents an HTTP method.
public enum Method: String {
case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT
}
/// Choice of parameter encoding.
public enum ParameterEncoding {
case URL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
internal var toAlamofire: Alamofire.ParameterEncoding {
switch self {
case .URL:
return .URL
case .JSON:
return .JSON
case .PropertyList(let format, let options):
return .PropertyList(format, options)
case .Custom(let closure):
return .Custom(closure)
}
}
}
public enum StubBehavior {
case Never
case Immediate
case Delayed(seconds: NSTimeInterval)
}
/// Protocol to define the base URL, path, method, parameters and sample data for a target.
public protocol TargetType {
var baseURL: NSURL { get }
var path: String { get }
var method: Moya.Method { get }
var parameters: [String: AnyObject]? { get }
var sampleData: NSData { get }
}
/// Protocol to define the opaque type returned from a request
public protocol Cancellable {
func cancel()
}
/// Request provider class. Requests should be made through this class only.
public class MoyaProvider<Target: TargetType> {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = Target -> Endpoint<Target>
/// Closure that resolves an Endpoint into an NSURLRequest.
public typealias RequestClosure = (Endpoint<Target>, NSURLRequest -> Void) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = Target -> Moya.StubBehavior
public let endpointClosure: EndpointClosure
public let requestClosure: RequestClosure
public let stubClosure: StubClosure
public let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
public let plugins: [PluginType]
/// Initializes a provider.
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [PluginType] = []) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
}
/// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure.
public func endpoint(token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method. Returns a Cancellable token to cancel the request later.
public func request(target: Target, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
var cancellableToken = CancellableWrapper()
let performNetworking = { (request: NSURLRequest) in
if cancellableToken.isCancelled { return }
switch stubBehavior {
case .Never:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, completion: completion)
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
/// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
internal func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let cancellableToken = CancellableToken { }
notifyPluginsOfImpendingStub(request, target: target)
let plugins = self.plugins
let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins)
switch stubBehavior {
case .Immediate:
stub()
case .Delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset)
dispatch_after(killTime, dispatch_get_main_queue()) {
stub()
}
case .Never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Mark: Defaults
public extension MoyaProvider {
// These functions are default mappings to endpoings and requests.
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: NSURLRequest -> Void) {
return closure(endpoint.urlRequest)
}
}
/// Mark: Stubbing
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func NeverStub(_: Target) -> Moya.StubBehavior {
return .Never
}
public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior {
return .Immediate
}
public final class func DelayedStub(seconds: NSTimeInterval)(_: Target) -> Moya.StubBehavior {
return .Delayed(seconds: seconds)
}
}
internal extension MoyaProvider {
func sendRequest(target: Target, request: NSURLRequest, completion: Moya.Completion) -> CancellableToken {
let request = manager.request(request)
let plugins = self.plugins
// Give plugins the chance to alter the outgoing request
plugins.forEach { $0.willSendRequest(request, target: target) }
// Perform the actual request
let alamoRequest = request.response { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
return CancellableToken(request: alamoRequest)
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
internal final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if (token.canceled) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(Moya.Result(failure: error), target: target) }
completion(result: Result(failure: error))
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(Moya.Result(success: response), target: target) }
completion(result: Moya.Result(success: response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(Moya.Result(failure: error), target: target) }
completion(result: Moya.Result(failure: error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
internal final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let request = manager.request(request)
plugins.forEach { $0.willSendRequest(request, target: target) }
}
}
internal func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> Moya.Result<Moya.Response, Moya.Error> {
switch (response, data, error) {
case let (.Some(response), .Some(data), .None):
let response = Moya.Response(statusCode: response.statusCode, data: data, response: response)
return Moya.Result(success: response)
case let (_, _, .Some(error)):
let error = Moya.Error.Underlying(error)
return Moya.Result(failure: error)
default:
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
return Moya.Result(failure: error)
}
}
/// Internal token that can be used to cancel requests
internal final class CancellableToken: Cancellable , CustomDebugStringConvertible{
let cancelAction: () -> Void
let request : Request?
private(set) var canceled: Bool = false
private var lock: OSSpinLock = OS_SPINLOCK_INIT
func cancel() {
OSSpinLockLock(&lock)
defer { OSSpinLockUnlock(&lock) }
guard !canceled else { return }
canceled = true
cancelAction()
}
init(action: () -> Void){
self.cancelAction = action
self.request = nil
}
init(request : Request){
self.request = request
self.cancelAction = {
request.cancel()
}
}
var debugDescription: String {
guard let request = self.request else {
return "Empty Request"
}
return request.debugDescription
}
}
private struct CancellableWrapper: Cancellable {
var innerCancellable: CancellableToken? = nil
private var isCancelled = false
func cancel() {
innerCancellable?.cancel()
}
}
/// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins.
extension Request: RequestType { }
| mit | 4851ca198a12eefab3809d6a62574012 | 38.097561 | 204 | 0.66233 | 5.147248 | false | false | false | false |
apple/swift | test/SILGen/if_while_binding.swift | 2 | 16680 |
// RUN: %target-swift-emit-silgen -module-name if_while_binding -Xllvm -sil-full-demangle %s | %FileCheck %s
func foo() -> String? { return "" }
func bar() -> String? { return "" }
func a(_ x: String) {}
func b(_ x: String) {}
func c(_ x: String) {}
func marker_1() {}
func marker_2() {}
func marker_3() {}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F
func if_no_else() {
// CHECK: [[FOO:%.*]] = function_ref @$s16if_while_binding3fooSSSgyF
// CHECK: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[NO:bb[0-9]+]]
//
// CHECK: [[NO]]:
// CHECK: br [[CONT:bb[0-9]+]]
if let x = foo() {
// CHECK: [[YES]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [lexical] [[VAL]]
// CHECK: [[A:%.*]] = function_ref @$s16if_while_binding1a
// CHECK: apply [[A]]([[BORROWED_VAL]])
// CHECK: end_borrow [[BORROWED_VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
a(x)
}
// CHECK: [[CONT]]:
// CHECK-NEXT: tuple ()
}
// CHECK: } // end sil function '$s16if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () {
func if_else_chain() {
// CHECK: [[FOO:%.*]] = function_ref @$s16if_while_binding3foo{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt: [[YESX:bb[0-9]+]], case #Optional.none!enumelt: [[NOX:bb[0-9]+]]
if let x = foo() {
// CHECK: [[YESX]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [lexical] [[VAL]]
// CHECK: debug_value [[BORROWED_VAL]] : $String, let, name "x"
// CHECK: [[A:%.*]] = function_ref @$s16if_while_binding1a
// CHECK: apply [[A]]([[BORROWED_VAL]])
// CHECK: end_borrow [[BORROWED_VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT_X:bb[0-9]+]]
a(x)
//
// CHECK: [[NOX]]:
// CHECK: alloc_box ${ var String }, var, name "y"
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt: [[YESY:bb[0-9]+]], case #Optional.none!enumelt: [[ELSE:bb[0-9]+]]
} else if var y = bar() {
// CHECK: [[YESY]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: br [[CONT_Y:bb[0-9]+]]
b(y)
} else {
// CHECK: [[ELSE]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: function_ref if_while_binding.c
c("")
// CHECK: br [[CONT_Y]]
}
// CHECK: [[CONT_Y]]:
// br [[CONT_X]]
// CHECK: [[CONT_X]]:
}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0B5_loopyyF : $@convention(thin) () -> () {
func while_loop() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
//
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt: [[LOOP_BODY:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NO_TRAMPOLINE]]:
// CHECK: br [[LOOP_EXIT:bb[0-9]+]]
while let x = foo() {
// CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : @owned $String):
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[FAILURE_DEST_2:bb[0-9]+]]
if let y = bar() {
// CHECK: [[YES]]([[Y:%[0-9]+]] : @owned $String):
a(y)
break
// CHECK: destroy_value [[Y]]
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_EXIT]]
}
// CHECK: [[FAILURE_DEST_2]]:
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_ENTRY]]
}
// CHECK: [[LOOP_EXIT]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// Don't leak alloc_stacks for address-only conditional bindings in 'while'.
// <rdar://problem/16202294>
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F
// CHECK: br [[COND:bb[0-9]+]]
// CHECK: [[COND]]:
// CHECK: [[X:%.*]] = alloc_stack [lexical] $T, let, name "x"
// CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T>
// CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt: [[LOOPBODY:bb.*]], case #Optional.none!enumelt: [[OUT:bb[0-9]+]]
// CHECK: [[LOOPBODY]]:
// CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr
// CHECK: copy_addr [take] [[ENUMVAL]] to [init] [[X]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK: br [[COND]]
// CHECK: [[OUT]]:
// CHECK: dealloc_stack [[OPTBUF]]
// CHECK: dealloc_stack [[X]]
// CHECK: return
// CHECK: } // end sil function '$s16if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F'
func while_loop_generic<T>(_ source: () -> T?) {
while let x = source() {
}
}
// <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0B11_loop_multiyyF
func while_loop_multi() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[LOOP_EXIT0:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [lexical] [[A]]
// CHECK: debug_value [[BORROWED_A]] : $String, let, name "a"
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[LOOP_BODY:bb.*]], case #Optional.none!enumelt: [[LOOP_EXIT2a:bb[0-9]+]]
// CHECK: [[LOOP_EXIT2a]]:
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_EXIT0]]
// CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : @owned $String):
while let a = foo(), let b = bar() {
// CHECK: [[BORROWED_B:%.*]] = begin_borrow [lexical] [[B]]
// CHECK: debug_value [[BORROWED_B]] : $String, let, name "b"
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
// CHECK: [[BORROWED_A_COPY:%.*]] = begin_borrow [lexical] [[A_COPY]]
// CHECK: debug_value [[BORROWED_A_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_A_COPY]]
// CHECK: destroy_value [[A_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_ENTRY]]
let c = a
}
// CHECK: [[LOOP_EXIT0]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A6_multiyyF
func if_multi() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[IF_DONE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [lexical] [[A]]
// CHECK: debug_value [[BORROWED_A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[B_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[B]]
// CHECK: [[PB:%[0-9]+]] = project_box [[B_LIFETIME]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: end_borrow [[B_LIFETIME]]
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
let c = a
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A11_multi_elseyyF
func if_multi_else() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[ELSE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [lexical] [[A]]
// CHECK: debug_value [[BORROWED_A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[B_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[B]]
// CHECK: [[PB:%[0-9]+]] = project_box [[B_LIFETIME]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[ELSE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: end_borrow [[B_LIFETIME]]
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE:bb[0-9]+]]
let c = a
} else {
let d = 0
// CHECK: [[ELSE]]:
// CHECK: debug_value {{.*}} : $Int, let, name "d"
// CHECK: br [[IF_DONE]]
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A12_multi_whereyyF
func if_multi_where() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[DONE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [lexical] [[A]]
// CHECK: debug_value [[BORROWED_A]] : $String, let, name "a"
// CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[BBOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[BBOX]]
// CHECK: [[PB:%[0-9]+]] = project_box [[BBOX_LIFETIME]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[CHECK_WHERE:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[DONE]]
// CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : @owned $String):
// CHECK: struct_extract {{.*}}
// CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]]
if let a = foo(), var b = bar(), a == b {
// CHECK: [[IF_BODY]]:
// CHECK: end_borrow [[BBOX_LIFETIME]]
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[DONE]]
let c = a
}
// CHECK: [[IF_EXIT3]]:
// CHECK: end_borrow [[BBOX_LIFETIME]]
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[DONE]]
// CHECK: [[DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified.
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding0A16_leading_booleanyySiF
func if_leading_boolean(_ a : Int) {
// Test the boolean condition.
// CHECK: debug_value %0 : $Int, let, name "a"
// CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool
// CHECK: [[EQRESULTI1:%[0-9]+]] = struct_extract {{.*}} : $Bool, #Bool._value
// CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[ELSE:bb[0-9]+]]
// Call Foo and test for the optional being present.
// CHECK: [[CHECKFOO]]:
// CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String>
// CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt: [[SUCCESS:bb.*]], case #Optional.none!enumelt: [[IFDONE:bb[0-9]+]]
// CHECK: [[SUCCESS]]([[B:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_B:%.*]] = begin_borrow [lexical] [[B]]
// CHECK: debug_value [[BORROWED_B]] : $String, let, name "b"
// CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]]
// CHECK: [[BORROWED_B_COPY:%.*]] = begin_borrow [lexical] [[B_COPY]]
// CHECK: debug_value [[BORROWED_B_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_B_COPY]]
// CHECK: destroy_value [[B_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: br [[IFDONE:bb[0-9]+]]
if a == a, let b = foo() {
let c = b
}
// CHECK: [[ELSE]]:
// CHECK: br [[IFDONE]]
// CHECK: [[IFDONE]]:
// CHECK-NEXT: tuple ()
}
/// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let'
class BaseClass {}
class DerivedClass : BaseClass {}
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding20testAsPatternInIfLetyyAA9BaseClassCSgF
func testAsPatternInIfLet(_ a : BaseClass?) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<BaseClass>):
// CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a"
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Optional<BaseClass>
// CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt: [[OPTPRESENTBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
// CHECK: [[NILBB]]:
// CHECK: br [[EXITBB:bb[0-9]+]]
// CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : @owned $BaseClass):
// CHECK: checked_cast_br [[CLS]] : $BaseClass to DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : @owned $DerivedClass):
// CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt, [[DERIVED_CLS]] : $DerivedClass
// CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>)
// CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : @owned $BaseClass):
// CHECK: destroy_value [[BASECLASS]] : $BaseClass
// CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt
// CHECK: br [[MERGE]](
// CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : @owned $Optional<DerivedClass>):
// CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt: [[ISDERIVEDBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : @owned $DerivedClass):
// CHECK: [[BORROWED_DERIVED_VAL:%.*]] = begin_borrow [lexical] [[DERIVEDVAL]]
// CHECK: debug_value [[BORROWED_DERIVED_VAL]] : $DerivedClass
// => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val.
// CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass
// CHECK: br [[EXITBB]]
// CHECK: [[EXITBB]]:
// CHECK: tuple ()
// CHECK: return
if case let b as DerivedClass = a {
}
}
// <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet
// CHECK-LABEL: sil hidden [ossa] @$s16if_while_binding12testCaseBoolyySbSgF
func testCaseBool(_ value : Bool?) {
// CHECK: bb0([[ARG:%.*]] : $Optional<Bool>):
// CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[CONT_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[PAYLOAD:%.*]] : $Bool):
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD]] : $Bool, #Bool._value
// CHECK: cond_br [[ISTRUE]], [[TRUE_BB:bb[0-9]+]], [[FALSE_TRAMPOLINE:bb[0-9]+]]
// CHECK: [[FALSE_TRAMPOLINE]]:
// CHECK: br [[CONT_BB]]
// CHECK: [[TRUE_BB]]:
// CHECK: function_ref @$s16if_while_binding8marker_1yyF
// CHECK: br [[CONT_BB]]
if case true? = value {
marker_1()
}
// CHECK: [[CONT_BB]]:
// CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt: [[SUCC_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE_2:bb[0-9]+]]
// CHECK: [[NO_TRAMPOLINE_2]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
// CHECK: [[SUCC_BB_2]]([[PAYLOAD2:%.*]] : $Bool):
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD2]] : $Bool, #Bool._value
// CHECK: cond_br [[ISTRUE]], [[TRUE3_BB:bb[0-9]+]], [[FALSE2_BB:bb[0-9]+]]
// CHECK: [[TRUE3_BB]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[FALSE2_BB]]:
// CHECK: function_ref @$s16if_while_binding8marker_2yyF
// CHECK: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK: return
if case false? = value {
marker_2()
}
}
| apache-2.0 | 971b9b1991d6bcc71510c7fc948a6ed1 | 39.882353 | 167 | 0.551739 | 3.020098 | false | false | false | false |
testpress/ios-app | ios-app/Utils/Permissions.swift | 1 | 4282 | //
// Permissions.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import AVFoundation
import Photos
import TTGSnackbar
import UIKit
func checkCameraAuthorizationStatus(viewController: UIViewController,
completion: @escaping (Bool) -> Void) {
let cameraMediaType = AVMediaType.video
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: cameraMediaType)
let message = Strings.NEEDS_PERMISSION_TO_ACCESS + Strings.CAMERA
switch cameraAuthorizationStatus {
case .authorized:
completion(true)
break
case .restricted:
TTGSnackbar(message: message, duration: .middle).show()
completion(false)
break
case .notDetermined:
// Prompting user for the permission to use the camera.
AVCaptureDevice.requestAccess(for: cameraMediaType) { granted in
completion(granted)
}
case .denied:
showGoToSettingsAlert(title: message, viewController: viewController)
break
}
}
func checkPhotoLibraryAuthorizationStatus(viewController: UIViewController,
completion: @escaping (Bool) -> Void) {
let message = Strings.NEEDS_PERMISSION_TO_ACCESS + Strings.PHOTO_LIBRARY
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
completion(true)
break
case .restricted:
TTGSnackbar(message: message, duration: .middle).show()
completion(false)
break
case .notDetermined:
PHPhotoLibrary.requestAuthorization() { status in
completion( status == .authorized ? true : false)
}
case .denied:
showGoToSettingsAlert(title: message, viewController: viewController)
break
case .limited:
showGoToSettingsAlert(title: message, viewController: viewController)
break
}
}
func showGoToSettingsAlert(title: String, viewController: UIViewController) {
let alertController = UIAlertController (title: title, message: Strings.GO_TO_SETTINGS,
preferredStyle: .alert)
let settingsAction =
UIAlertAction(title: Strings.SETTINGS, style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
} else {
UIApplication.shared.openURL(settingsUrl)
}
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: Strings.CANCEL, style: .default, handler: nil)
alertController.addAction(cancelAction)
viewController.present(alertController, animated: true, completion: nil)
}
| mit | 277caa0a574e826fde03c6a7646223f4 | 36.884956 | 93 | 0.656856 | 5.096429 | false | false | false | false |
LawrenceHan/iOS-project-playground | Swift_A_Big_Nerd_Ranch_Guide/ErrorHandling.playground/Contents.swift | 1 | 4548 | //: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
enum Token {
case Number(Int)
case Plus
case Minus
}
class Lexer {
enum Error: ErrorType {
case InvalidCharacter(String.CharacterView.Index, Character)
}
let input:String.CharacterView
var position: String.CharacterView.Index
init(input: String) {
self.input = input.characters
self.position = self.input.startIndex
}
func peek() -> Character? {
guard position < input.endIndex else {
return nil
}
return input[position]
}
func advance() {
assert(position < input.endIndex, "Cannot advance past the end!")
++position
}
func getNumber() -> Int {
var value = 0
while let nextCharacter = peek() {
switch nextCharacter {
case "0" ... "9":
// Another digit - add it into value
let digitValue = Int(String(nextCharacter))!
value = 10*value + digitValue
advance()
default:
// A non-digit - go back to regular lexing
return value
}
}
return value
}
func lex() throws -> [Token] {
var tokens = [Token]()
while let nextCharacter = peek() {
switch nextCharacter {
case "0" ... "9":
// Start of a number - need to grab the rest
let value = getNumber()
tokens.append(.Number(value))
case "+":
tokens.append(.Plus)
advance()
case "-":
tokens.append(.Minus)
advance()
case " ":
// Just advance to ignore spaces
advance()
default:
// Something unexpected - need to send back an error
throw Error.InvalidCharacter(position, nextCharacter)
}
}
return tokens
}
}
class Parser {
enum Error: ErrorType {
case UnexpectedEndOfInput
case InvalidToken(Int, Token)
}
let tokens: [Token]
var position = 0
init(tokens: [Token]) {
self.tokens = tokens
}
func getNextToken() -> Token? {
guard position < tokens.count else {
return nil
}
return tokens[position++]
}
func getNumber() throws -> Int {
guard let token = getNextToken() else {
throw Error.UnexpectedEndOfInput
}
switch token {
case .Number(let value):
return value
case .Plus, .Minus:
throw Error.InvalidToken(position, token)
}
}
func parse() throws -> Int {
// Require a number first
var value = try getNumber()
while let token = getNextToken() {
switch token {
// Getting a Plus after a number is legal
case .Plus:
// After a plus, we must get another number
let nextNumber = try getNumber()
value += nextNumber
case .Minus:
let nextNumber = try getNumber()
value -= nextNumber
// Getting a number after a Number is not legal
case .Number:
throw Error.InvalidToken(position, token)
}
}
return value
}
}
func evaluate(input: String) {
print("Evaluating: \(input)")
let lexer = Lexer(input: input)
do {
let tokens = try lexer.lex()
print("Lexer output: \(tokens)")
let parser = Parser(tokens: tokens)
let result = try parser.parse()
print("Parser output: \(result)")
} catch Parser.Error.UnexpectedEndOfInput {
print("Unexpected end of input during parsing")
} catch Parser.Error.InvalidToken(let index, let token) {
print("Invalid token during parsing at index: \(index) \(token)")
} catch Lexer.Error.InvalidCharacter(let position, let character) {
print("Input contained an invalid character at index: \(position) \(character)")
} catch {
print("An error occurred: \(error)")
}
}
evaluate("10 + 3 + 5")
evaluate("10 + 5 - 3 - 1")
evaluate("10 -3 3 + 4")
| mit | 50a432b90692994481d3dd6cd4db4fa9 | 25.137931 | 88 | 0.505057 | 5.064588 | false | false | false | false |
algolia/algoliasearch-client-swift | Tests/AlgoliaSearchClientTests/Doc/Methods/ManageIndicesSnippets.swift | 1 | 3635 | //
// ManageIndicesSnippets.swift
//
//
// Created by Vladislav Fitc on 01/07/2020.
//
import Foundation
import AlgoliaSearchClient
struct ManageIndicesSnippets: SnippetsCollection {}
//MARK: - List indices
extension ManageIndicesSnippets {
static var listIndices = """
client.listIndices(
requestOptions: __RequestOptions?__ = nil,
completion: __Result<IndicesListResponse> -> Void__
)
"""
func listIndices() {
client.listIndices { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
//MARK: - Delete index
extension ManageIndicesSnippets {
static var deleteIndex = """
index.delete(
requestOptions: __RequestOptions?__ = nil,
completion: __Result<WaitableWrapper<IndexDeletion>> -> Void__
)
"""
func deleteIndex() {
index.delete { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
//MARK: - Copy index
extension ManageIndicesSnippets {
static var copyIndex = """
client.copyIndex(
from [source](#method-param-indexnamesrc): __IndexName__,
to [destination](#method-param-indexnamedest): __IndexName__,
#{scope}: __Scope__ = .all,
requestOptions: __RequestOptions?__ = nil,
completion: __Result<WaitableWrapper<IndexRevision>> -> Void__
)
ClientAccount.copyIndex(
[source](#method-param-indexsrc): __Index__,
[destination](#method-param-indexdest): __Index__,
requestOptions: RequestOptions? = nil,
completion: __Result<WaitableWrapper<[IndexTask]>, Swift.Error>) -> Void__
)
"""
func copyIndex() {
// Copy indexNameSrc to indexNameDest
client.copyIndex(from: "indexNameSrc", to: "indexNameDest") { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func partialCopyIndex() {
// Copy settings and synonyms (but not rules) from "indexNameSrc" to "indexNameDest".
client.copyIndex(from: "indexNameSrc",
to: "indexNameDest",
scope: [.settings, .synonyms]) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func crossAppCopyIndex() throws {
let index1 = SearchClient(appID: "APP_ID_1", apiKey: "API_KEY_1").index(withName: "index1")
let index2 = SearchClient(appID: "APP_ID_2", apiKey: "API_KEY_2").index(withName: "index2")
try AccountClient.copyIndex(source: index1, destination: index2) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
//MARK: - Move index
extension ManageIndicesSnippets {
static var moveIndex = """
client.moveIndex(
from [source](#method-param-indexnamesrc): __IndexName__,
to [destination](#method-param-indexnamedest): __IndexName__,
requestOptions: __RequestOptions?__ = nil,
completion: __Result<WaitableWrapper<IndexRevision>> -> Void__
)
"""
func moveIndex() {
// Rename indexNameSrc to indexNameDest (and overwrite it)
client.moveIndex(from: "indexNameSrc", to: "indexNameDest") { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
//MARK: - Index exists
extension ManageIndicesSnippets {
static var indexExists = """
index.exists(completion: __Result<Bool> -> Void__)
"""
func indexExists() {
index.exists { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
| mit | 881f8155e143bbf94aa8f983c5db887c | 23.233333 | 95 | 0.62641 | 3.959695 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/TwoFactorViewModel.swift | 1 | 6822 | import Foundation
import KsApi
import Prelude
import ReactiveExtensions
import ReactiveSwift
public protocol TwoFactorViewModelInputs {
/// Call when code textfield is updated
func codeChanged(_ code: String?)
/// Call to set email and password
func email(_ email: String, password: String)
/// Call when the environment has been logged into
func environmentLoggedIn()
/// Call to set facebook token
func facebookToken(_ token: String)
/// Call when resend button pressed
func resendPressed()
/// Call when submit button pressed
func submitPressed()
/// Call when the view did load.
func viewDidLoad()
/// Call when view will appear
func viewWillAppear()
}
public protocol TwoFactorViewModelOutputs {
/// Emits when the code text field is the first responder.
var codeTextFieldBecomeFirstResponder: Signal<(), Never> { get }
/// Emits whether the form is valid or not
var isFormValid: Signal<Bool, Never> { get }
/// Emits whether a request is loading or not
var isLoading: Signal<Bool, Never> { get }
/// Emits an access token envelope that can be used to update the environment.
var logIntoEnvironment: Signal<AccessTokenEnvelope, Never> { get }
/// Emits when a login success notification should be posted.
var postNotification: Signal<(Notification, Notification), Never> { get }
/// Emits when code was resent successfully
var resendSuccess: Signal<(), Never> { get }
/// Emits a message when the code submitted is not correct or login fails
var showError: Signal<String, Never> { get }
}
public protocol TwoFactorViewModelType {
var inputs: TwoFactorViewModelInputs { get }
var outputs: TwoFactorViewModelOutputs { get }
}
public final class TwoFactorViewModel: TwoFactorViewModelType, TwoFactorViewModelInputs,
TwoFactorViewModelOutputs {
// A simple type to hold all the data needed to login.
fileprivate struct TfaData {
fileprivate let email: String?
fileprivate let password: String?
fileprivate let facebookToken: String?
fileprivate let code: String?
fileprivate enum lens {
fileprivate static let code = Lens<TfaData, String?>(
view: { $0.code },
set: { TfaData(email: $1.email, password: $1.password, facebookToken: $1.facebookToken, code: $0) }
)
}
}
public init() {
let isLoading = MutableProperty(false)
let loginData = SignalProducer.combineLatest(
self.emailProperty.producer,
self.passwordProperty.producer,
self.facebookTokenProperty.producer,
self.codeProperty.producer
)
.map(TfaData.init)
let resendData = loginData.map(TfaData.lens.code .~ nil)
let loginEvent = loginData
.takeWhen(self.submitPressedProperty.signal)
.switchMap { data in
login(data, apiService: AppEnvironment.current.apiService, isLoading: isLoading)
.materialize()
}
self.codeTextFieldBecomeFirstResponder = self.viewDidLoadProperty.signal
self.logIntoEnvironment = loginEvent.values()
self.resendSuccess = resendData
.takeWhen(self.resendPressedProperty.signal)
.switchMap { data in
login(data, apiService: AppEnvironment.current.apiService, isLoading: isLoading)
.materialize()
.errors()
.filter { error in error.ksrCode == .TfaRequired }
.ignoreValues()
}
self.isLoading = isLoading.signal
self.isFormValid = Signal.merge([
self.codeProperty.signal.map { code in code?.count == 6 },
self.viewWillAppearProperty.signal.mapConst(false)
])
.skipRepeats()
let codeMismatch = loginEvent.errors()
.filter { $0.ksrCode == .TfaFailed }
.map { $0.errorMessages.first ?? Strings.two_factor_error_message() }
let genericFail = loginEvent.errors()
.filter { $0.ksrCode != .TfaFailed }
.map { $0.errorMessages.first ?? Strings.login_errors_unable_to_log_in() }
self.showError = Signal.merge([codeMismatch, genericFail])
self.postNotification = self.environmentLoggedInProperty.signal
.mapConst((
Notification(name: .ksr_sessionStarted),
Notification(
name: .ksr_showNotificationsDialog,
userInfo: [UserInfoKeys.context: PushNotificationDialog.Context.login]
)
))
}
fileprivate let codeProperty = MutableProperty<String?>(nil)
public func codeChanged(_ code: String?) {
self.codeProperty.value = code
}
fileprivate let emailProperty = MutableProperty<String?>(nil)
fileprivate let passwordProperty = MutableProperty<String?>(nil)
public func email(_ email: String, password: String) {
self.emailProperty.value = email
self.passwordProperty.value = password
}
fileprivate let environmentLoggedInProperty = MutableProperty(())
public func environmentLoggedIn() {
self.environmentLoggedInProperty.value = ()
}
fileprivate let facebookTokenProperty = MutableProperty<String?>(nil)
public func facebookToken(_ token: String) {
self.facebookTokenProperty.value = token
}
fileprivate let resendPressedProperty = MutableProperty(())
public func resendPressed() {
self.resendPressedProperty.value = ()
}
fileprivate let submitPressedProperty = MutableProperty(())
public func submitPressed() {
self.submitPressedProperty.value = ()
}
fileprivate let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
fileprivate let viewWillAppearProperty = MutableProperty(())
public func viewWillAppear() {
self.viewWillAppearProperty.value = ()
}
public let codeTextFieldBecomeFirstResponder: Signal<(), Never>
public let isFormValid: Signal<Bool, Never>
public let isLoading: Signal<Bool, Never>
public let logIntoEnvironment: Signal<AccessTokenEnvelope, Never>
public let postNotification: Signal<(Notification, Notification), Never>
public let resendSuccess: Signal<(), Never>
public let showError: Signal<String, Never>
public var inputs: TwoFactorViewModelInputs { return self }
public var outputs: TwoFactorViewModelOutputs { return self }
}
private func login(
_ tfaData: TwoFactorViewModel.TfaData,
apiService: ServiceType,
isLoading: MutableProperty<Bool>
) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> {
let login: SignalProducer<AccessTokenEnvelope, ErrorEnvelope>
if let email = tfaData.email, let password = tfaData.password {
login = apiService.login(email: email, password: password, code: tfaData.code)
} else if let facebookToken = tfaData.facebookToken {
login = apiService.login(facebookAccessToken: facebookToken, code: tfaData.code)
} else {
login = .empty
}
return login
.on(
starting: { isLoading.value = true },
terminated: { isLoading.value = false }
)
}
| apache-2.0 | 40456ee99f058a58ea47d28c89254bd8 | 30.878505 | 107 | 0.7146 | 4.538922 | false | false | false | false |
alobanov/Dribbble | Dribbble/shared/extensions/observable/Observable+GreatMapper.swift | 1 | 6844 | //
// Observable+Networking.swift
// Tavern
//
// Created by Lobanov on 13.10.15.
// Copyright © 2015 Lobanov Aleksey. All rights reserved.
//
import RxSwift
import ObjectMapper
import RealmSwift
import Moya
// MARK:- Network json mappier
extension Observable {
func mapSimpleJSON() -> Observable<[String: AnyObject]> {
return map {representor in
guard let response = representor as? Response else {
throw ORMError.ormNoRepresentor.error
}
// Allow successful HTTP codes
if let err = ErrorManager.sharedInstance.haveResponseError(response.response as? HTTPURLResponse) {
throw err
}
guard let json = try JSONSerialization.jsonObject(with: response.data, options: .mutableContainers) as? [String: AnyObject] else {
throw ORMError.ormCouldNotMakeObjectError(objectName: "Raw json").error
}
if let code = json["ReturnCode"] as? Int, let message = json["Message"] as? String {
if code != 0 {
throw NSError(domain:ErrorManager.justDomain, code:code, userInfo: [NSLocalizedDescriptionKey: message])
}
}
return json
}
}
func mapJSONObject<T: ObjectMappable>(_ type: T.Type, realm: Realm? = nil) -> Observable<T> {
func resultFromJSON(_ object: [String: AnyObject], classType: T.Type) -> T? {
return Mapper<T>().map(JSON: object)
}
return map {representor in
guard let response = representor as? Response else {
throw ORMError.ormNoRepresentor.error
}
// Allow successful HTTP codes
if let err = ErrorManager.sharedInstance.haveResponseError(response.response as? HTTPURLResponse) {
throw err
}
guard let json = try JSONSerialization.jsonObject(with: response.data, options: .mutableContainers) as? [String: AnyObject] else {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
let obj: T = resultFromJSON(json, classType: type)!
do {
if let r = realm {
let objR: T = resultFromJSON(json, classType: type)!
r.beginWrite()
r.add(objR, update: true)
try r.commitWrite()
}
return obj
} catch {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
}
}
func mapJSONObjectArray<T: ObjectMappable>(_ type: T.Type, realm: Realm? = nil) -> Observable < [T] > {
func resultFromJSON(_ object: [String: AnyObject], classType: T.Type) -> T? {
return Mapper<T>().map(JSON: object)
}
return map {response in
guard let response = response as? Response else {
throw ORMError.ormNoRepresentor.error
}
// Allow successful HTTP codes
if let err = ErrorManager.sharedInstance.haveResponseError(response.response as? HTTPURLResponse) {
throw err
}
guard let json = try JSONSerialization.jsonObject(with: response.data, options: .mutableContainers) as? [[String : AnyObject]] else {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
// Objects are not guaranteed, thus cannot directly map.
var objects = [T]()
for dict in json {
if let obj = resultFromJSON(dict, classType: type) {
objects.append(obj)
}
}
if let r = realm {
do {
var objectsR = [T]()
for dict in json {
if let obj = resultFromJSON(dict, classType: type) {
objectsR.append(obj)
}
}
r.beginWrite()
r.add(objectsR, update: true)
try r.commitWrite()
} catch {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
}
return objects
}
}
}
// MARK:- Mapping from serialized dictionary
extension Observable {
func mapModelFromDict<T: ObjectMappable>(_ type: T.Type, realm: Realm? = nil) -> Observable<T> {
func resultFromJSON(_ object: [String: AnyObject], classType: T.Type) -> T? {
return Mapper<T>().map(JSON: object)
}
return map { dataDict in
guard let json = dataDict as? [String: AnyObject] else {
throw ORMError.ormNoRepresentor.error
}
let obj: T = resultFromJSON(json, classType: type)!
if let r = realm {
do {
let objR: T = resultFromJSON(json, classType: type)!
r.beginWrite()
r.add(objR, update: true)
try r.commitWrite()
} catch {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
}
return obj
}
}
func mapModelFromArray<T: ObjectMappable>(_ type: T.Type, realm: Realm? = nil) -> Observable < [T] > {
func resultFromJSON(_ object: [String: AnyObject], classType: T.Type) -> T? {
return Mapper<T>().map(JSON: object)
}
return map { dataArray in
guard let json = dataArray as? [[String: AnyObject]] else {
throw ORMError.ormNoRepresentor.error
}
var objects = [T]()
for dict in json {
if let obj = resultFromJSON(dict, classType: type) {
objects.append(obj)
}
}
if let r = realm {
do {
var objectsR = [T]()
for dict in json {
if let obj = resultFromJSON(dict, classType: type) {
objectsR.append(obj)
}
}
r.beginWrite()
r.add(objectsR, update: true)
try r.commitWrite()
} catch {
throw ORMError.ormCouldNotMakeObjectError(objectName: NSStringFromClass(T.self)).error
}
}
return objects
}
}
}
// Mapper for local models without Realm and saving
extension Observable {
func mapJSONLocalObject<T: Mappable>(_ type: T.Type) -> Observable<T> {
func resultFromJSON(_ object: [String: AnyObject], classType: T.Type) -> T? {
return Mapper<T>().map(JSON: object)
}
return map {representor in
guard let response = representor as? Response else {
throw ORMError.ormNoRepresentor.error
}
// Allow successful HTTP codes
if let err = ErrorManager.sharedInstance.haveResponseError(response.response as? HTTPURLResponse) {
throw err
}
guard let json = try JSONSerialization.jsonObject(with: response.data, options: .mutableContainers) as? [String: AnyObject] else {
throw ORMError.ormCouldNotMakeObjectError(objectName: "\(T.self)").error
}
let obj: T = resultFromJSON(json, classType: type)!
return obj
}
}
}
| mit | 05a892076cd4ab3a657f605bb9f358c3 | 30.104545 | 139 | 0.603098 | 4.331013 | false | false | false | false |
wavecos/curso_ios_3 | QuakeRadar/QuakeRadar/Service/QuakeService.swift | 1 | 1649 | //
// QuakeService.swift
// QuakeRadar
//
// Created by onix on 11/22/14.
// Copyright (c) 2014 tekhne. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import CoreLocation
class QuakeService {
let quakeUrl = "http://earthquake.usgs.gov/earthquakes/feed/v0.1/summary/all_hour.geojson"
var delegate : QuakeDelegate?
init() {
}
func getAllQuakesFromLastHour() {
var quakes : [Quake] = [Quake]()
Alamofire.request(.GET, quakeUrl).responseJSON { (request, response, dataJson, error) -> Void in
if error == nil {
let json = JSON(dataJson!)
let features = json["features"].arrayValue
for feature in features {
let magnitude = feature["properties"]["mag"].doubleValue
let place = feature["properties"]["place"].stringValue
let time = feature["properties"]["time"].doubleValue
let date = NSDate(timeIntervalSince1970: time / 1000)
let url = feature["properties"]["url"].stringValue
let urlInfo = NSURL(string: url)
let longitud = feature["geometry"]["coordinates"][0].doubleValue
let latitude = feature["geometry"]["coordinates"][1].doubleValue
let location = CLLocation(latitude: latitude, longitude: longitud)
let quake = Quake(magnitude: magnitude, place: place, date: date, urlInfo: urlInfo!, location: location)
quakes.append(quake)
}
self.delegate?.quakesReceived(quakes)
}
}
}
}
| apache-2.0 | 5cb34663f6c90ec5b235ac662a8f41fb | 23.61194 | 114 | 0.590661 | 4.606145 | false | false | false | false |
sandym/swiftpp | tests/6/test.swift | 1 | 392 |
class MySimple : Simple
{
override func method1( s : String ) -> String
{
if ( s == "This" )
{
return s + super.method1( " " )
}
else if ( s == "is" )
{
return s + super.method1( " corr" )
}
else
{
return s
}
}
}
print( "\u{1B}[32m" )
print( "--> 6. re-entrency" )
let s1 = MySimple()
print( s1.method1( "This" ) )
print( "\u{1B}[0m" )
| mit | 5fa86743a92a52f8132bf38642fe5df5 | 13 | 49 | 0.479592 | 2.404908 | false | false | false | false |
soapyigu/LeetCode_Swift | Array/ThreeSum.swift | 1 | 1832 | /**
* Question Link: https://leetcode.com/problems/3sum/
* Primary idea: Sort the array, and traverse it, increment left or decrease right
* predicated on their sum is greater or not than the target
* Time Complexity: O(n^2), Space Complexity: O(nC3)
*/
class ThreeSum {
func threeSum(nums: [Int]) -> [[Int]] {
var nums = nums.sorted(by: <)
var res = [[Int]]()
if nums.count <= 2 {
return res
}
for i in 0...nums.count - 3 {
if i == 0 || nums[i] != nums[i - 1] {
var remain = -nums[i]
var left = i + 1
var right = nums.count - 1
while left < right {
if nums[left] + nums[right] == remain {
var temp = [Int]()
temp.append(nums[i])
temp.append(nums[left])
temp.append(nums[right])
res.append(temp)
repeat {
left += 1
} while (left < right && nums[left] == nums[left - 1])
repeat {
right -= 1
} while (left < right && nums[right] == nums[right + 1])
} else if nums[left] + nums[right] < remain {
repeat {
left += 1
} while (left < right && nums[left] == nums[left - 1])
} else {
repeat {
right -= 1
} while (left < right && nums[right] == nums[right + 1])
}
}
}
}
return res
}
} | mit | 78191731dd2a11cf69aa378b42850f9a | 34.941176 | 83 | 0.367904 | 4.833773 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Timetable/Models/LessonDetailsSelectionField.swift | 1 | 4188 | //
// LessonDetailsSelectionField.swift
// HTWDD
//
// Created by Chris Herlemann on 07.01.21.
// Copyright © 2021 HTW Dresden. All rights reserved.
//
protocol LessonDetailsSelectionFieldDelegate {
func done( _ selectionOptions: LessonDetailsOptions)
}
class LessonDetailsSelectionField: UITextField, UITextFieldDelegate {
var selectionOptions: LessonDetailsOptions!
var selectionDelegate: LessonDetailsSelectionFieldDelegate?
let pickerView = UIPickerView()
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
createPickerView()
dismissPickerView()
}
func setup(isEditable: Bool) {
guard isEditable else {
self.isEnabled = false
return
}
createDropDownIcon()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
guard textField.text == "" else {
return
}
switch selectionOptions {
case .lectureType(_): selectionOptions = .lectureType(selection: LessonType.allCasesWithoutDuplicates.first)
case .weekRotation(_): selectionOptions = .weekRotation(selection: .once)
case .weekDay(_): selectionOptions = .weekDay(selection: CalendarWeekDay.allCases.first)
default: break
}
self.text = selectionOptions?.localizedDescription ?? ""
}
func textFieldDidEndEditing(_ textField: UITextField) {
selectionDelegate?.done(selectionOptions)
}
func createDropDownIcon() {
let dropDownIcon = UIImage(named: "Down")
let button = UIButton(frame: CGRect(x: 20, y: 0, width: 30, height: 30))
button.addTarget(self, action: #selector(iconTapped), for: .touchUpInside)
button.setImage(dropDownIcon, for: .normal)
button.tintColor = UIColor.htw.Icon.primary
rightView = button
rightViewMode = .always
}
@objc private func iconTapped() {
self.becomeFirstResponder()
}
}
extension LessonDetailsSelectionField: UIPickerViewDelegate, UIPickerViewDataSource {
func createPickerView() {
pickerView.delegate = self
self.inputView = pickerView
}
func dismissPickerView() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let button = UIBarButtonItem(title: R.string.localizable.done(), style: .plain, target: self, action: #selector(saveSelection))
toolBar.setItems([button], animated: true)
toolBar.isUserInteractionEnabled = true
self.inputAccessoryView = toolBar
}
@objc func saveSelection() {
self.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return selectionOptions?.count ?? 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch selectionOptions {
case .lectureType(_): return LessonType.allCasesWithoutDuplicates[row].localizedDescription
case .weekRotation(_): return CalendarWeekRotation.allCases[row].localizedDescription
case .weekDay(_): return CalendarWeekDay.allCases[row].localizedDescription
default: return ""
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch selectionOptions {
case .lectureType(_): selectionOptions = .lectureType(selection: LessonType.allCasesWithoutDuplicates[row])
case .weekRotation(_): selectionOptions = .weekRotation(selection: CalendarWeekRotation.allCases[row])
case .weekDay(_): selectionOptions = .weekDay(selection: CalendarWeekDay.allCases[row])
default: break
}
self.text = selectionOptions?.localizedDescription ?? ""
}
@objc func cancelDatePicker(){
self.endEditing(true)
}
}
| gpl-2.0 | 224c9f395fad47b7aff34523a4438b7f | 31.457364 | 135 | 0.640793 | 5.27995 | false | false | false | false |
MrZoidberg/metapp | metapp/Pods/RxDataSources/Sources/DataSources/Differentiator.swift | 17 | 25684 | //
// Differentiator.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public enum DifferentiatorError
: Error
, CustomDebugStringConvertible {
case duplicateItem(item: Any)
case duplicateSection(section: Any)
case invalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any)
}
extension DifferentiatorError {
public var debugDescription: String {
switch self {
case let .duplicateItem(item):
return "Duplicate item \(item)"
case let .duplicateSection(section):
return "Duplicate section \(section)"
case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier):
return "Wrong initializer implementation for: \(section)\n" +
"Expected it should return items: \(expectedItems)\n" +
"Expected it should have id: \(expectedIdentifier)"
}
}
}
enum EditEvent : CustomDebugStringConvertible {
case inserted // can't be found in old sections
case insertedAutomatically // Item inside section being inserted
case deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated
case deletedAutomatically // Item inside section that is being deleted
case moved // same item, but was on different index, and needs explicit move
case movedAutomatically // don't need to specify any changes for those rows
case untouched
}
extension EditEvent {
var debugDescription: String {
get {
switch self {
case .inserted:
return "Inserted"
case .insertedAutomatically:
return "InsertedAutomatically"
case .deleted:
return "Deleted"
case .deletedAutomatically:
return "DeletedAutomatically"
case .moved:
return "Moved"
case .movedAutomatically:
return "MovedAutomatically"
case .untouched:
return "Untouched"
}
}
}
}
struct SectionAssociatedData {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: Int?
}
extension SectionAssociatedData : CustomDebugStringConvertible {
var debugDescription: String {
get {
return "\(event), \(indexAfterDelete)"
}
}
}
extension SectionAssociatedData {
static var initial: SectionAssociatedData {
return SectionAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
struct ItemAssociatedData {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: ItemPath?
}
extension ItemAssociatedData : CustomDebugStringConvertible {
var debugDescription: String {
get {
return "\(event) \(indexAfterDelete)"
}
}
}
extension ItemAssociatedData {
static var initial : ItemAssociatedData {
return ItemAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
func indexSections<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Identity : Int] {
var indexedSections: [S.Identity : Int] = [:]
for (i, section) in sections.enumerated() {
guard indexedSections[section.identity] == nil else {
#if DEBUG
if indexedSections[section.identity] != nil {
print("Section \(section) has already been indexed at \(indexedSections[section.identity]!)")
}
#endif
throw DifferentiatorError.duplicateItem(item: section)
}
indexedSections[section.identity] = i
}
return indexedSections
}
func indexSectionItems<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Item.Identity : (Int, Int)] {
var totalItems = 0
for i in 0 ..< sections.count {
totalItems += sections[i].items.count
}
// let's make sure it's enough
var indexedItems: [S.Item.Identity : (Int, Int)] = Dictionary(minimumCapacity: totalItems * 3)
for i in 0 ..< sections.count {
for (j, item) in sections[i].items.enumerated() {
guard indexedItems[item.identity] == nil else {
#if DEBUG
if indexedItems[item.identity] != nil {
print("Item \(item) has already been indexed at \(indexedItems[item.identity]!)" )
}
#endif
throw DifferentiatorError.duplicateItem(item: item)
}
indexedItems[item.identity] = (i, j)
}
}
return indexedItems
}
/*
I've uncovered this case during random stress testing of logic.
This is the hardest generic update case that causes two passes, first delete, and then move/insert
[
NumberSection(model: "1", items: [1111]),
NumberSection(model: "2", items: [2222]),
]
[
NumberSection(model: "2", items: [0]),
NumberSection(model: "1", items: []),
]
If update is in the form
* Move section from 2 to 1
* Delete Items at paths 0 - 0, 1 - 0
* Insert Items at paths 0 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 1 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 0 - 0
it crashes table view.
No matter what change is performed, it fails for me.
If anyone knows how to make this work for one Changeset, PR is welcome.
*/
// If you are considering working out your own algorithm, these are tricky
// transition cases that you can use.
// case 1
/*
from = [
NumberSection(model: "section 4", items: [10, 11, 12]),
NumberSection(model: "section 9", items: [25, 26, 27]),
]
to = [
HashableSectionModel(model: "section 9", items: [11, 26, 27]),
HashableSectionModel(model: "section 4", items: [10, 12])
]
*/
// case 2
/*
from = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 7", items: [5, 29]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 5", items: [16]),
HashableSectionModel(model: "section 4", items: []),
HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20])
]
to = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 9", items: [3]),
HashableSectionModel(model: "section 5", items: [16, 8]),
HashableSectionModel(model: "section 8", items: [15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20]),
HashableSectionModel(model: "Section 2", items: [7])
]
*/
// case 3
/*
from = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: []),
HashableSectionModel(model: "section 2", items: [2, 26]),
HashableSectionModel(model: "section 8", items: [23]),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
to = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: [16]),
HashableSectionModel(model: "section 7", items: [17, 15, 4]),
HashableSectionModel(model: "section 2", items: [2, 26, 23]),
HashableSectionModel(model: "section 8", items: []),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
*/
// Generates differential changes suitable for sectioned view consumption.
// It will not only detect changes between two states, but it will also try to compress those changes into
// almost minimal set of changes.
//
// I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and
// avoids UITableView quirks.
//
// Please take into consideration that I was also convinced about 20 times that I've found a simple general
// solution, but then UITableView falls apart under stress testing :(
//
// Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think
// that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :)
//
// Maybe it can be made somewhat simpler, but don't think it can be made much simpler.
//
// The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates.
//
// * stage 1 - remove deleted sections and items
// * stage 2 - move sections into place
// * stage 3 - fix moved and new items
//
// There maybe exists a better division, but time will tell.
//
public func differencesForSectionedView<S: AnimatableSectionModelType>(
_ initialSections: [S],
finalSections: [S]
)
throws -> [Changeset<S>] {
typealias I = S.Item
var result: [Changeset<S>] = []
var sectionCommands = try CommandGenerator<S>.generatorForInitialSections(initialSections, finalSections: finalSections)
result.append(contentsOf: try sectionCommands.generateDeleteSections())
result.append(contentsOf: try sectionCommands.generateInsertAndMoveSections())
result.append(contentsOf: try sectionCommands.generateNewAndMovedItems())
return result
}
private extension AnimatableSectionModelType {
init(safeOriginal: Self, safeItems: [Item]) throws {
self.init(original: safeOriginal, items: safeItems)
if self.items != safeItems || self.identity != safeOriginal.identity {
throw DifferentiatorError.invalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity)
}
}
}
struct CommandGenerator<S: AnimatableSectionModelType> {
let initialSections: [S]
let finalSections: [S]
let initialSectionData: [SectionAssociatedData]
let finalSectionData: [SectionAssociatedData]
let initialItemData: [[ItemAssociatedData]]
let finalItemData: [[ItemAssociatedData]]
static func generatorForInitialSections(
_ initialSections: [S],
finalSections: [S]
) throws -> CommandGenerator<S> {
let (initialSectionData, finalSectionData) = try calculateSectionMovementsForInitialSections(initialSections, finalSections: finalSections)
let (initialItemData, finalItemData) = try calculateItemMovementsForInitialSections(initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData
)
return CommandGenerator<S>(
initialSections: initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData,
initialItemData: initialItemData,
finalItemData: finalItemData
)
}
static func calculateItemMovementsForInitialSections(_ initialSections: [S], finalSections: [S],
initialSectionData: [SectionAssociatedData], finalSectionData: [SectionAssociatedData]) throws -> ([[ItemAssociatedData]], [[ItemAssociatedData]]) {
var initialItemData = initialSections.map { s in
return [ItemAssociatedData](repeating: ItemAssociatedData.initial, count: s.items.count)
}
var finalItemData = finalSections.map { s in
return [ItemAssociatedData](repeating: ItemAssociatedData.initial, count: s.items.count)
}
let initialItemIndexes = try indexSectionItems(initialSections)
for i in 0 ..< finalSections.count {
for (j, item) in finalSections[i].items.enumerated() {
guard let initialItemIndex = initialItemIndexes[item.identity] else {
continue
}
if initialItemData[initialItemIndex.0][initialItemIndex.1].moveIndex != nil {
throw DifferentiatorError.duplicateItem(item: item)
}
initialItemData[initialItemIndex.0][initialItemIndex.1].moveIndex = ItemPath(sectionIndex: i, itemIndex: j)
finalItemData[i][j].moveIndex = ItemPath(sectionIndex: initialItemIndex.0, itemIndex: initialItemIndex.1)
}
}
let findNextUntouchedOldIndex = { (initialSectionIndex: Int, initialSearchIndex: Int?) -> Int? in
guard var i2 = initialSearchIndex else {
return nil
}
while i2 < initialSections[initialSectionIndex].items.count {
if initialItemData[initialSectionIndex][i2].event == .untouched {
return i2
}
i2 = i2 + 1
}
return nil
}
// first mark deleted items
for i in 0 ..< initialSections.count {
guard let _ = initialSectionData[i].moveIndex else {
continue
}
var indexAfterDelete = 0
for j in 0 ..< initialSections[i].items.count {
guard let finalIndexPath = initialItemData[i][j].moveIndex else {
initialItemData[i][j].event = .deleted
continue
}
// from this point below, section has to be move type because it's initial and not deleted
// because there is no move to inserted section
if finalSectionData[finalIndexPath.sectionIndex].event == .inserted {
initialItemData[i][j].event = .deleted
continue
}
initialItemData[i][j].indexAfterDelete = indexAfterDelete
indexAfterDelete += 1
}
}
// mark moved or moved automatically
for i in 0 ..< finalSections.count {
guard let originalSectionIndex = finalSectionData[i].moveIndex else {
continue
}
var untouchedIndex: Int? = 0
for j in 0 ..< finalSections[i].items.count {
untouchedIndex = findNextUntouchedOldIndex(originalSectionIndex, untouchedIndex)
guard let originalIndex = finalItemData[i][j].moveIndex else {
finalItemData[i][j].event = .inserted
continue
}
// In case trying to move from deleted section, abort, otherwise it will crash table view
if initialSectionData[originalIndex.sectionIndex].event == .deleted {
finalItemData[i][j].event = .inserted
continue
}
// original section can't be inserted
else if initialSectionData[originalIndex.sectionIndex].event == .inserted {
try rxPrecondition(false, "New section in initial sections, that is wrong")
}
let initialSectionEvent = initialSectionData[originalIndex.sectionIndex].event
try rxPrecondition(initialSectionEvent == .moved || initialSectionEvent == .movedAutomatically, "Section not moved")
let eventType = originalIndex == ItemPath(sectionIndex: originalSectionIndex, itemIndex: untouchedIndex ?? -1)
? EditEvent.movedAutomatically : EditEvent.moved
initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].event = eventType
finalItemData[i][j].event = eventType
}
}
return (initialItemData, finalItemData)
}
static func calculateSectionMovementsForInitialSections(_ initialSections: [S], finalSections: [S]) throws -> ([SectionAssociatedData], [SectionAssociatedData]) {
let initialSectionIndexes = try indexSections(initialSections)
var initialSectionData = [SectionAssociatedData](repeating: SectionAssociatedData.initial, count: initialSections.count)
var finalSectionData = [SectionAssociatedData](repeating: SectionAssociatedData.initial, count: finalSections.count)
for (i, section) in finalSections.enumerated() {
guard let initialSectionIndex = initialSectionIndexes[section.identity] else {
continue
}
if initialSectionData[initialSectionIndex].moveIndex != nil {
throw DifferentiatorError.duplicateSection(section: section)
}
initialSectionData[initialSectionIndex].moveIndex = i
finalSectionData[i].moveIndex = initialSectionIndex
}
var sectionIndexAfterDelete = 0
// deleted sections
for i in 0 ..< initialSectionData.count {
if initialSectionData[i].moveIndex == nil {
initialSectionData[i].event = .deleted
continue
}
initialSectionData[i].indexAfterDelete = sectionIndexAfterDelete
sectionIndexAfterDelete += 1
}
// moved sections
var untouchedOldIndex: Int? = 0
let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in
guard var i = initialSearchIndex else {
return nil
}
while i < initialSections.count {
if initialSectionData[i].event == .untouched {
return i
}
i = i + 1
}
return nil
}
// inserted and moved sections {
// this should fix all sections and move them into correct places
// 2nd stage
for i in 0 ..< finalSections.count {
untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex)
// oh, it did exist
if let oldSectionIndex = finalSectionData[i].moveIndex {
let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.moved : EditEvent.movedAutomatically
finalSectionData[i].event = moveType
initialSectionData[oldSectionIndex].event = moveType
}
else {
finalSectionData[i].event = .inserted
}
}
// inserted sections
for (i, section) in finalSectionData.enumerated() {
if section.moveIndex == nil {
_ = finalSectionData[i].event == .inserted
}
}
return (initialSectionData, finalSectionData)
}
mutating func generateDeleteSections() throws -> [Changeset<S>] {
var deletedSections = [Int]()
var deletedItems = [ItemPath]()
var updatedItems = [ItemPath]()
var afterDeleteState = [S]()
// mark deleted items {
// 1rst stage again (I know, I know ...)
for (i, initialSection) in initialSections.enumerated() {
let event = initialSectionData[i].event
// Deleted section will take care of deleting child items.
// In case of moving an item from deleted section, tableview will
// crash anyway, so this is not limiting anything.
if event == .deleted {
deletedSections.append(i)
continue
}
var afterDeleteItems: [S.Item] = []
for j in 0 ..< initialSection.items.count {
let event = initialItemData[i][j].event
switch event {
case .deleted:
deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved, .movedAutomatically:
let finalItemIndex = try initialItemData[i][j].moveIndex.unwrap()
let finalItem = finalSections[finalItemIndex]
if finalItem != initialSections[i].items[j] {
updatedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
}
afterDeleteItems.append(finalItem)
default:
try rxPrecondition(false, "Unhandled case")
}
}
afterDeleteState.append(try S(safeOriginal: initialSection, safeItems: afterDeleteItems))
}
// }
if deletedItems.count == 0 && deletedSections.count == 0 && updatedItems.count == 0 {
return []
}
return [Changeset(
finalSections: afterDeleteState,
deletedSections: deletedSections,
deletedItems: deletedItems,
updatedItems: updatedItems
)]
}
func generateInsertAndMoveSections() throws -> [Changeset<S>] {
var movedSections = [(from: Int, to: Int)]()
var insertedSections = [Int]()
for i in 0 ..< initialSections.count {
switch initialSectionData[i].event {
case .deleted:
break
case .moved:
movedSections.append((from: try initialSectionData[i].indexAfterDelete.unwrap(), to: try initialSectionData[i].moveIndex.unwrap()))
case .movedAutomatically:
break
default:
try rxPrecondition(false, "Unhandled case in initial sections")
}
}
for i in 0 ..< finalSections.count {
switch finalSectionData[i].event {
case .inserted:
insertedSections.append(i)
default:
break
}
}
if insertedSections.count == 0 && movedSections.count == 0 {
return []
}
// sections should be in place, but items should be original without deleted ones
let sectionsAfterChange: [S] = try self.finalSections.enumerated().map { i, s -> S in
let event = self.finalSectionData[i].event
if event == .inserted {
// it's already set up
return s
}
else if event == .moved || event == .movedAutomatically {
let originalSectionIndex = try finalSectionData[i].moveIndex.unwrap()
let originalSection = initialSections[originalSectionIndex]
var items: [S.Item] = []
for (j, _) in originalSection.items.enumerated() {
let initialData = self.initialItemData[originalSectionIndex][j]
guard initialData.event != .deleted else {
continue
}
guard let finalIndex = initialData.moveIndex else {
try rxPrecondition(false, "Item was moved, but no final location.")
continue
}
items.append(self.finalSections[finalIndex.sectionIndex].items[finalIndex.itemIndex])
}
let modifiedSection = try S(safeOriginal: s, safeItems: items)
return modifiedSection
}
else {
try rxPrecondition(false, "This is weird, this shouldn't happen")
return s
}
}
return [Changeset(
finalSections: sectionsAfterChange,
insertedSections: insertedSections,
movedSections: movedSections
)]
}
mutating func generateNewAndMovedItems() throws -> [Changeset<S>] {
var insertedItems = [ItemPath]()
var movedItems = [(from: ItemPath, to: ItemPath)]()
// mark new and moved items {
// 3rd stage
for i in 0 ..< finalSections.count {
let finalSection = finalSections[i]
let sectionEvent = finalSectionData[i].event
// new and deleted sections cause reload automatically
if sectionEvent != .moved && sectionEvent != .movedAutomatically {
continue
}
for j in 0 ..< finalSection.items.count {
let currentItemEvent = finalItemData[i][j].event
try rxPrecondition(currentItemEvent != .untouched, "Current event is not untouched")
let event = finalItemData[i][j].event
switch event {
case .inserted:
insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved:
let originalIndex = try finalItemData[i][j].moveIndex.unwrap()
let finalSectionIndex = try initialSectionData[originalIndex.sectionIndex].moveIndex.unwrap()
let moveFromItemWithIndex = try initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].indexAfterDelete.unwrap()
let moveCommand = (
from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex),
to: ItemPath(sectionIndex: i, itemIndex: j)
)
movedItems.append(moveCommand)
default:
break
}
}
}
// }
if insertedItems.count == 0 && movedItems.count == 0 {
return []
}
return [Changeset(
finalSections: finalSections,
insertedItems: insertedItems,
movedItems: movedItems
)]
}
}
| mpl-2.0 | a54337dfc1c3740093dbd0e81c6885ef | 35.378187 | 166 | 0.604213 | 5.223307 | false | false | false | false |
fgengine/quickly | Quickly/Table/QTableController.swift | 1 | 28431 | //
// Quickly
//
open class QTableController : NSObject, IQTableController, IQTableCellDelegate, IQTableDecorDelegate {
public typealias TableView = IQTableController.TableView
public typealias Decor = IQTableController.Decor
public typealias Cell = IQTableController.Cell
public weak var tableView: TableView? {
didSet { if self.tableView != nil { self.configure() } }
}
public var estimatedRowHeight: CGFloat {
didSet { if let tableView = self.tableView { tableView.estimatedRowHeight = self.estimatedRowHeight } }
}
public var estimatedSectionHeaderHeight: CGFloat {
didSet { if let tableView = self.tableView { tableView.estimatedSectionHeaderHeight = self.estimatedSectionHeaderHeight } }
}
public var estimatedSectionFooterHeight: CGFloat {
didSet { if let tableView = self.tableView { tableView.estimatedSectionFooterHeight = self.estimatedSectionFooterHeight } }
}
public var sections: [IQTableSection] = [] {
willSet { self._unbindSections() }
didSet { self._bindSections() }
}
var indexPaths: [IndexPath] {
return self.sections.flatMap({ return $0.indexPaths })
}
public var rows: [IQTableRow] {
return self.sections.flatMap({ (section: IQTableSection) -> [IQTableRow] in
return section.rows
})
}
public var selectedRows: [IQTableRow] {
get {
guard
let tableView = self.tableView,
let selectedIndexPaths = tableView.indexPathsForSelectedRows
else { return [] }
return selectedIndexPaths.compactMap({ (indexPath: IndexPath) -> IQTableRow? in
return self.sections[indexPath.section].rows[indexPath.row]
})
}
}
public var canEdit: Bool = true
public var canMove: Bool = true
public var postVisibleIndexPaths: [IndexPath] = []
public var preVisibleIndexPaths: [IndexPath] = []
public var visibleCells: [UITableViewCell] = []
public private(set) var isBatchUpdating: Bool = false
private var _decors: [IQTableDecor.Type]
private var _aliasDecors: [QMetatype : IQTableDecor.Type]
private var _cells: [IQTableCell.Type]
private var _aliasCells: [QMetatype : IQTableCell.Type]
private var _cacheHeight: [Int : [Int : CGFloat]]
private var _observer: QObserver< IQTableControllerObserver >
public init(
cells: [IQTableCell.Type]
) {
self.estimatedRowHeight = 44
self.estimatedSectionHeaderHeight = 44
self.estimatedSectionFooterHeight = 44
self._decors = []
self._aliasDecors = [:]
self._cells = cells
self._aliasCells = [:]
self._cacheHeight = [:]
self._observer = QObserver< IQTableControllerObserver >()
super.init()
self.setup()
}
public init(
decors: [IQTableDecor.Type],
cells: [IQTableCell.Type]
) {
self.estimatedRowHeight = 44
self.estimatedSectionHeaderHeight = 44
self.estimatedSectionFooterHeight = 44
self._decors = decors
self._aliasDecors = [:]
self._cells = cells
self._aliasCells = [:]
self._cacheHeight = [:]
self._observer = QObserver< IQTableControllerObserver >()
super.init()
self.setup()
}
open func setup() {
}
open func configure() {
if let tableView = self.tableView {
for type in self._decors {
type.register(tableView: tableView)
}
for type in self._cells {
type.register(tableView: tableView)
}
tableView.estimatedRowHeight = self.estimatedRowHeight
tableView.estimatedSectionHeaderHeight = self.estimatedSectionHeaderHeight
tableView.estimatedSectionFooterHeight = self.estimatedSectionFooterHeight
}
self.rebuild()
}
open func rebuild() {
self.reload([])
}
open func add(observer: IQTableControllerObserver, priority: UInt) {
self._observer.add(observer, priority: priority)
}
open func remove(observer: IQTableControllerObserver) {
self._observer.remove(observer)
}
open func section(index: Int) -> IQTableSection {
return self.sections[index]
}
open func index(section: IQTableSection) -> Int? {
return section.index
}
open func header(index: Int) -> IQTableData? {
return self.sections[index].header
}
open func index(header: IQTableData) -> Int? {
guard let section = header.section else { return nil }
return section.index
}
open func footer(index: Int) -> IQTableData? {
return self.sections[index].footer
}
open func index(footer: IQTableData) -> Int? {
guard let section = footer.section else { return nil }
return section.index
}
open func row(indexPath: IndexPath) -> IQTableRow {
return self.sections[indexPath.section].rows[indexPath.row]
}
open func row(predicate: (IQTableRow) -> Bool) -> IQTableRow? {
for section in self.sections {
for row in section.rows {
if predicate(row) {
return row
}
}
}
return nil
}
open func indexPath(row: IQTableRow) -> IndexPath? {
return row.indexPath
}
open func indexPath(predicate: (IQTableRow) -> Bool) -> IndexPath? {
for existSection in self.sections {
for existRow in existSection.rows {
if predicate(existRow) {
return existRow.indexPath
}
}
}
return nil
}
open func header(data: IQTableData) -> IQTableDecor? {
guard
let tableView = self.tableView,
let index = self.index(header: data)
else { return nil }
return tableView.headerView(forSection: index) as? IQTableDecor
}
open func footer(data: IQTableData) -> IQTableDecor? {
guard
let tableView = self.tableView,
let index = self.index(footer: data)
else { return nil }
return tableView.footerView(forSection: index) as? IQTableDecor
}
open func cell(row: IQTableRow) -> IQTableCell? {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row)
else { return nil }
return tableView.cellForRow(at: indexPath) as? IQTableCell
}
open func dequeue(data: IQTableData) -> Decor? {
guard
let tableView = self.tableView,
let decorClass = self._decorClass(data: data),
let decorView = decorClass.dequeue(tableView: tableView)
else { return nil }
decorView.tableDelegate = self
return decorView
}
open func dequeue(row: IQTableRow, indexPath: IndexPath) -> Cell? {
guard
let tableView = self.tableView,
let cellClass = self._cellClass(row: row),
let tableCell = cellClass.dequeue(tableView: tableView, indexPath: indexPath)
else { return nil }
tableCell.tableDelegate = self;
return tableCell
}
open func reload(_ options: QTableControllerReloadOption) {
if options.contains(.resetCache) == true {
self.sections.forEach({ $0.resetCache() })
}
if let tableView = self.tableView {
tableView.reloadData()
self._notifyUpdate()
}
}
open func insertSection(_ sections: [IQTableSection], index: Int, with animation: UITableView.RowAnimation? = nil) {
self.sections.insert(contentsOf: sections, at: index)
self._bindSections(from: index, to: self.sections.endIndex)
var indexSet = IndexSet()
for section in self.sections {
if let sectionIndex = section.index {
indexSet.insert(sectionIndex)
}
}
if indexSet.count > 0 {
if let tableView = self.tableView, let animation = animation {
tableView.insertSections(indexSet, with: animation)
}
}
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
open func deleteSection(_ sections: [IQTableSection], with animation: UITableView.RowAnimation? = nil) {
var indexSet = IndexSet()
for section in sections {
if let index = self.sections.firstIndex(where: { return ($0 === section) }) {
indexSet.insert(index)
}
}
if indexSet.count > 0 {
for index in indexSet.reversed() {
let section = self.sections[index]
self.sections.remove(at: index)
section.unbind()
}
self._bindSections(from: indexSet.first!, to: self.sections.endIndex)
if let tableView = self.tableView, let animation = animation {
tableView.deleteSections(indexSet, with: animation)
}
}
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
open func reloadSection(_ sections: [IQTableSection], with animation: UITableView.RowAnimation? = nil) {
var indexSet = IndexSet()
for section in sections {
if let index = self.sections.firstIndex(where: { return ($0 === section) }) {
indexSet.insert(index)
}
}
if indexSet.count > 0 {
if let tableView = self.tableView, let animation = animation {
tableView.reloadSections(indexSet, with: animation)
}
}
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
open func performBatchUpdates(_ updates: (() -> Void)) {
if self.isBatchUpdating == false {
self.isBatchUpdating = true
if let tableView = self.tableView {
tableView.beginUpdates()
}
updates()
if let tableView = self.tableView {
tableView.endUpdates()
}
self.isBatchUpdating = false
self._notifyUpdate()
} else {
updates()
}
}
open func scroll(row: IQTableRow, scroll: UITableView.ScrollPosition, animated: Bool) {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row)
else { return }
tableView.scrollToRow(at: indexPath, at: scroll, animated: animated)
}
open func isSelected(row: IQTableRow) -> Bool {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row),
let selectedIndexPaths = tableView.indexPathsForSelectedRows
else { return false }
return selectedIndexPaths.contains(indexPath)
}
open func select(row: IQTableRow, scroll: UITableView.ScrollPosition, animated: Bool) {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row)
else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scroll)
}
open func deselect(row: IQTableRow, animated: Bool) {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row)
else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
open func update(header: IQTableData, animated: Bool) {
guard
let tableView = self.tableView,
let index = self.index(header: header),
let decorView = tableView.headerView(forSection: index) as? IQTableDecor
else { return }
decorView.prepare(any: header, spec: tableView, animated: animated)
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
open func update(footer: IQTableData, animated: Bool) {
guard
let tableView = self.tableView,
let index = self.index(footer: footer),
let decorView = tableView.headerView(forSection: index) as? IQTableDecor
else { return }
decorView.prepare(any: footer, spec: tableView, animated: animated)
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
open func update(row: IQTableRow, animated: Bool) {
guard
let tableView = self.tableView,
let indexPath = self.indexPath(row: row),
let cell = tableView.cellForRow(at: indexPath) as? IQTableCell
else { return }
cell.prepare(any: row, spec: tableView, animated: animated)
if self.isBatchUpdating == false {
self._notifyUpdate()
}
}
}
// MARK: Private
private extension QTableController {
func _bindSections() {
var sectionIndex: Int = 0
for section in self.sections {
section.bind(self, sectionIndex)
sectionIndex += 1
}
}
func _bindSections(from: Int, to: Int) {
for index in from..<to {
self.sections[index].bind(self, index)
}
}
func _unbindSections() {
for section in self.sections {
section.unbind()
}
}
func _notifyUpdate() {
self._observer.notify({ $0.update(self) })
}
func _decorClass(data: IQTableData) -> IQTableDecor.Type? {
let dataMetatype = QMetatype(data)
if let metatype = self._aliasDecors.first(where: { return $0.key == dataMetatype }) {
return metatype.value
}
if let decorType = self._aliasDecors[dataMetatype] {
return decorType
}
let usings = self._decors.filter({ return $0.using(any: data) })
if usings.count > 1 {
let typeOfData = type(of: data)
let levels = usings.compactMap({ (type) -> (IQTableDecor.Type, UInt)? in
guard let level = type.usingLevel(any: typeOfData) else { return nil }
return (type, level)
})
let sorted = levels.sorted(by: { return $0.1 > $1.1 })
if let sortedFirst = sorted.first {
self._aliasDecors[dataMetatype] = sortedFirst.0
return sortedFirst.0
}
} else if let usingFirst = usings.first {
self._aliasDecors[dataMetatype] = usingFirst
return usingFirst
}
return nil
}
func _cellClass(row: IQTableRow) -> IQTableCell.Type? {
let rowMetatype = QMetatype(row)
if let metatype = self._aliasCells.first(where: { return $0.key == rowMetatype }) {
return metatype.value
}
if let cellType = self._aliasCells[rowMetatype] {
return cellType
}
let usings = self._cells.filter({ return $0.using(any: row) })
if usings.count > 1 {
let typeOfData = type(of: row)
let levels = usings.compactMap({ (type) -> (IQTableCell.Type, UInt)? in
guard let level = type.usingLevel(any: typeOfData) else { return nil }
return (type, level)
})
let sorted = levels.sorted(by: { return $0.1 > $1.1 })
if let sortedFirst = sorted.first {
self._aliasCells[rowMetatype] = sortedFirst.0
return sortedFirst.0
}
} else if let usingFirst = usings.first {
self._aliasCells[rowMetatype] = usingFirst
return usingFirst
}
return nil
}
func _updateVisibleIndexPaths(_ tableView: UITableView) {
if let visibleIndexPaths = tableView.indexPathsForVisibleRows {
let indexPaths = self.indexPaths
if let visibleIndexPath = visibleIndexPaths.first, let index = indexPaths.firstIndex(of: visibleIndexPath) {
let start = 0
let end = max(0, index - 1)
self.postVisibleIndexPaths = Array(indexPaths[start..<end])
} else {
self.postVisibleIndexPaths = []
}
if let visibleIndexPath = visibleIndexPaths.last, let index = indexPaths.firstIndex(of: visibleIndexPath) {
let start = min(index + 1, indexPaths.count)
let end = indexPaths.count
self.preVisibleIndexPaths = Array(indexPaths[start..<end])
} else {
self.preVisibleIndexPaths = []
}
} else {
self.postVisibleIndexPaths = []
self.preVisibleIndexPaths = []
}
}
}
// MARK: UIScrollViewDelegate
extension QTableController : UIScrollViewDelegate {
@objc
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
let tableView = self.tableView!
self._observer.notify({ $0.beginScroll(self, tableView: tableView) })
}
@objc
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
let tableView = self.tableView!
self._observer.notify({ $0.scroll(self, tableView: tableView) })
}
@objc
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {
let tableView = self.tableView!
self._observer.notify({ $0.endScroll(self, tableView: tableView) })
}
}
@objc
open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer< CGPoint >) {
let tableView = self.tableView!
var targetContentOffsets: [CGPoint] = []
self._observer.notify({
if let contentOffset = $0.finishScroll(self, tableView: tableView, velocity: velocity) {
targetContentOffsets.append(contentOffset)
}
})
if targetContentOffsets.count > 0 {
var avgTargetContentOffset = targetContentOffsets.first!
if targetContentOffsets.count > 1 {
for nextTargetContentOffset in targetContentOffsets {
avgTargetContentOffset = CGPoint(
x: (avgTargetContentOffset.x + nextTargetContentOffset.x) / 2,
y: (avgTargetContentOffset.y + nextTargetContentOffset.y) / 2
)
}
}
targetContentOffset.pointee = avgTargetContentOffset
}
}
@objc
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let tableView = self.tableView!
self._observer.notify({ $0.endScroll(self, tableView: tableView) })
}
@objc
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
}
}
// MARK: UITableViewDataSource
extension QTableController : UITableViewDataSource {
@objc
open func numberOfSections(
in tableView: UITableView
) -> Int {
return self.sections.count
}
@objc
open func tableView(
_ tableView: UITableView,
numberOfRowsInSection index: Int
) -> Int {
let section = self.section(index: index)
if section.hidden == true {
return 0
}
return section.rows.count
}
@objc
open func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let row = self.row(indexPath: indexPath)
let cell = self.dequeue(row: row, indexPath: indexPath).unsafelyUnwrapped
cell.prepare(any: row, spec: tableView as! TableView, animated: false)
return cell
}
@objc
open func tableView(
_ tableView: UITableView,
canEditRowAt indexPath: IndexPath
) -> Bool {
let section = self.section(index: indexPath.section)
if section.canEdit == false {
return false;
}
let row = section.rows[indexPath.row]
return row.canEdit;
}
@objc
open func tableView(
_ tableView: UITableView,
canMoveRowAt indexPath: IndexPath
) -> Bool {
let section = self.section(index: indexPath.section)
if section.canMove == false {
return false;
}
let row = section.rows[indexPath.row]
return row.canMove;
}
}
// MARK: UITableViewDelegate
extension QTableController : UITableViewDelegate {
@objc
open func tableView(
_ tableView: UITableView,
viewForHeaderInSection section: Int
) -> UIView? {
if let data = self.header(index: section) {
if let decorClass = self._decorClass(data: data) {
let decor = decorClass.dequeue(tableView: tableView).unsafelyUnwrapped
decor.prepare(any: data, spec: tableView as! TableView, animated: false)
return decor
}
}
return nil
}
@objc
open func tableView(
_ tableView: UITableView,
viewForFooterInSection section: Int
) -> UIView? {
if let data = self.footer(index: section) {
if let decorClass = self._decorClass(data: data) {
let decor = decorClass.dequeue(tableView: tableView).unsafelyUnwrapped
decor.prepare(any: data, spec: tableView as! TableView, animated: false)
return decor
}
}
return nil
}
@objc
open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let row = self.row(indexPath: indexPath)
self.visibleCells.append(cell)
self._updateVisibleIndexPaths(tableView)
if let cell = cell as? IQTableCell {
cell.beginDisplay()
}
row.cacheHeight = cell.frame.height
}
@objc
open func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let index = self.visibleCells.firstIndex(where: { return $0 === cell }) {
self.visibleCells.remove(at: index)
}
self._updateVisibleIndexPaths(tableView)
if let cell = cell as? IQTableCell {
cell.endDisplay()
}
}
@objc
open func tableView(
_ tableView: UITableView,
willDisplayHeaderView view: UIView,
forSection section: Int
) {
guard let data = self.header(index: section) else { return }
if let decorView = view as? IQTableDecor {
decorView.beginDisplay()
}
data.cacheHeight = view.frame.height
}
@objc
open func tableView(
_ tableView: UITableView,
didEndDisplayingHeaderView view: UIView,
forSection section: Int
) {
if let decorView = view as? IQTableDecor {
decorView.endDisplay()
}
}
@objc
open func tableView(
_ tableView: UITableView,
willDisplayFooterView view: UIView,
forSection section: Int
) {
guard let data = self.footer(index: section) else { return }
if let decorView = view as? IQTableDecor {
decorView.beginDisplay()
}
data.cacheHeight = view.frame.height
}
@objc
open func tableView(
_ tableView: UITableView,
didEndDisplayingFooterView view: UIView,
forSection section: Int
) {
if let decorView = view as? IQTableDecor {
decorView.endDisplay()
}
}
@objc
open func tableView(
_ tableView: UITableView,
heightForRowAt indexPath: IndexPath
) -> CGFloat {
let row = self.row(indexPath: indexPath)
if let cacheHeight = row.cacheHeight {
return cacheHeight
}
var caclulatedHeight: CGFloat = 0
if let cellClass = self._cellClass(row: row) {
caclulatedHeight = cellClass.height(any: row, spec: tableView as! TableView)
} else {
caclulatedHeight = 0
}
if caclulatedHeight != UITableView.automaticDimension {
row.cacheHeight = caclulatedHeight
}
return caclulatedHeight
}
@objc
open func tableView(
_ tableView: UITableView,
heightForHeaderInSection section: Int
) -> CGFloat {
guard let data = self.header(index: section) else { return 0 }
if let cacheHeight = data.cacheHeight {
return cacheHeight
}
var caclulatedHeight: CGFloat = 0
if let decorClass = self._decorClass(data: data) {
caclulatedHeight = decorClass.height(any: data, spec: tableView as! TableView)
} else {
caclulatedHeight = 0
}
if caclulatedHeight != UITableView.automaticDimension {
data.cacheHeight = caclulatedHeight
}
return caclulatedHeight
}
@objc
open func tableView(
_ tableView: UITableView,
heightForFooterInSection section: Int
) -> CGFloat {
guard let data = self.footer(index: section) else { return 0 }
if let cacheHeight = data.cacheHeight {
return cacheHeight
}
var caclulatedHeight: CGFloat = 0
if let decorClass = self._decorClass(data: data) {
caclulatedHeight = decorClass.height(any: data, spec: tableView as! TableView)
} else {
caclulatedHeight = 0
}
if caclulatedHeight != UITableView.automaticDimension {
data.cacheHeight = caclulatedHeight
}
return caclulatedHeight
}
@objc
open func tableView(
_ tableView: UITableView,
estimatedHeightForRowAt indexPath: IndexPath
) -> CGFloat {
let row = self.row(indexPath: indexPath)
return row.cacheHeight ?? self.estimatedRowHeight
}
@objc
open func tableView(
_ tableView: UITableView,
estimatedHeightForHeaderInSection section: Int
) -> CGFloat {
guard let data = self.header(index: section) else { return self.estimatedSectionFooterHeight }
return data.cacheHeight ?? self.estimatedSectionFooterHeight
}
@objc
open func tableView(
_ tableView: UITableView,
estimatedHeightForFooterInSection section: Int
) -> CGFloat {
guard let data = self.footer(index: section) else { return self.estimatedSectionFooterHeight }
return data.cacheHeight ?? self.estimatedSectionFooterHeight
}
@objc
open func tableView(
_ tableView: UITableView,
shouldHighlightRowAt indexPath: IndexPath
) -> Bool {
let row = self.row(indexPath: indexPath)
return row.canSelect
}
@objc
open func tableView(
_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath
) -> IndexPath? {
let row = self.row(indexPath: indexPath)
if row.canSelect == false {
return nil
}
return indexPath
}
@objc
open func tableView(
_ tableView: UITableView,
willDeselectRowAt indexPath: IndexPath
) -> IndexPath? {
let row = self.row(indexPath: indexPath)
if row.canSelect == false {
return nil
}
return indexPath
}
@objc
open func tableView(
_ tableView: UITableView,
editingStyleForRowAt indexPath: IndexPath
) -> UITableViewCell.EditingStyle {
let row = self.row(indexPath: indexPath)
return row.editingStyle
}
@objc
@available(iOS 11.0, *)
open func tableView(
_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let row = self.row(indexPath: indexPath)
return row.leadingSwipeConfiguration
}
@objc
@available(iOS 11.0, *)
open func tableView(
_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let row = self.row(indexPath: indexPath)
return row.trailingSwipeConfiguration
}
}
| mit | c2129d3ac7f09fc6d5791a963bd12936 | 31.830254 | 155 | 0.592698 | 4.89346 | false | false | false | false |
PlanTeam/BSON | Sources/BSON/Codable/Decoding/KeyedBSONDecodingContainer.swift | 1 | 8318 | import Foundation
internal struct KeyedBSONDecodingContainer<K: CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = K
var codingPath: [CodingKey]
var allKeys: [K] {
return self.document.keys.compactMap(K.init)
}
let decoder: _BSONDecoder
var document: Document {
// Guaranteed to be a document when initialized
return self.decoder.document!
}
init(for decoder: _BSONDecoder, codingPath: [CodingKey]) {
self.codingPath = codingPath
self.decoder = decoder
}
func path(forKey key: K) -> [String] {
return self.codingPath.map { decoder.converted($0.stringValue) } + [decoder.converted(key.stringValue)]
}
func contains(_ key: K) -> Bool {
if let value = self.document[decoder.converted(key.stringValue)], !(value is Null) {
return true
} else {
return false
}
}
func decodeNil(forKey key: K) throws -> Bool {
return !self.contains(key)
}
func decode(_ type: Bool.Type, forKey key: K) throws -> Bool {
return try self.document.assertPrimitive(typeOf: type, forKey: decoder.converted(key.stringValue))
}
func decode(_ type: String.Type, forKey key: K) throws -> String {
return try self.decoder.settings.stringDecodingStrategy.decode(from: decoder, forKey: key, path: path(forKey: key))
}
func decode(_ type: Double.Type, forKey key: K) throws -> Double {
return try self.decoder.settings.doubleDecodingStrategy.decode(
from: decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Float.Type, forKey key: K) throws -> Float {
return try self.decoder.settings.floatDecodingStrategy.decode(
stringKey: decoder.converted(key.stringValue),
in: self.decoder.wrapped,
path: path(forKey: key)
)
}
func decode(_ type: Int.Type, forKey key: K) throws -> Int {
return try self.decoder.settings.intDecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 {
return try self.decoder.settings.int8DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 {
return try self.decoder.settings.int16DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 {
return try self.decoder.settings.int32DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 {
return try self.decoder.settings.int64DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: UInt.Type, forKey key: K) throws -> UInt {
return try self.decoder.settings.uintDecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 {
return try self.decoder.settings.uint8DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 {
return try self.decoder.settings.uint16DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 {
return try self.decoder.settings.uint32DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 {
return try self.decoder.settings.uint64DecodingStrategy.decode(
from: self.decoder,
forKey: key,
path: path(forKey: key)
)
}
func decode(_ type: Primitive.Protocol, forKey key: K) throws -> Primitive {
guard let value = self.document[decoder.converted(key.stringValue)] else {
throw BSONValueNotFound(type: Primitive.self, path: path(forKey: key))
}
return value
}
func decodeIfPresent(_ type: Primitive.Protocol, forKey key: K) throws -> Primitive? {
return self.document[decoder.converted(key.stringValue)]
}
func decode<T>(_ type: T.Type, forKey codingKey: K) throws -> T where T: Decodable {
let key = decoder.converted(codingKey.stringValue)
if let instance = self as? T {
return instance
} else if T.self == Date.self {
do {
guard let date = document[key] as? T else {
throw BSONTypeConversionError(from: document[key], to: Date.self)
}
return date
} catch {
if decoder.settings.decodeDateFromTimestamp {
switch self.document[key] {
case let int as Int:
return Date(timeIntervalSince1970: Double(int)) as! T
case let int as Int32:
return Date(timeIntervalSince1970: Double(int)) as! T
case let double as Double:
return Date(timeIntervalSince1970: double) as! T
default:
throw error
}
} else {
throw error
}
}
} else if let type = T.self as? BSONPrimitiveConvertible.Type {
return try type.init(primitive: self.document[key]) as! T
} else {
let value = self.document[key]
// Decoding strategy for Primitives, like Date
if let value = value as? T {
return value
}
let decoderValue: DecoderValue
if let document = value as? Document {
decoderValue = .document(document)
} else {
decoderValue = .primitive(value)
}
let decoder = _BSONDecoder(
wrapped: decoderValue,
settings: self.decoder.settings,
codingPath: self.codingPath + [codingKey],
userInfo: self.decoder.userInfo
)
return try T.init(from: decoder)
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
let document = self.document[decoder.converted(key.stringValue), as: Document.self] ?? Document()
let decoder = _BSONDecoder(wrapped: .document(document), settings: self.decoder.settings, codingPath: self.codingPath, userInfo: self.decoder.userInfo)
return KeyedDecodingContainer(KeyedBSONDecodingContainer<NestedKey>(for: decoder, codingPath: self.codingPath + [key]))
}
func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
let document = try self.decode(Document.self, forKey: key)
let decoder = _BSONDecoder(wrapped: .document(document), settings: self.decoder.settings, codingPath: self.codingPath, userInfo: self.decoder.userInfo)
return try UnkeyedBSONDecodingContainer(decoder: decoder, codingPath: self.codingPath + [key])
}
func superDecoder() throws -> Decoder {
// TODO: Use `super` key
return decoder
}
func superDecoder(forKey key: K) throws -> Decoder {
// TODO: Respect given key
return decoder
}
}
| mit | 39262eb03021240871f7cfc0431ad73f | 34.547009 | 159 | 0.569368 | 4.649525 | false | false | false | false |
moowahaha/Chuck | Chuck/Score.swift | 1 | 1697 | //
// Score.swift
// Chuck
//
// Created by Stephen Hardisty on 15/10/15.
// Copyright © 2015 Mr. Stephen. All rights reserved.
//
import SpriteKit
class Score {
var lastScore = 0
var totalScore = 0
let scoreContainer: UIView!
let totalScoreLabel: UILabel!
let lastScoreLabel: UILabel!
init(scoreContainer: UIView, totalScoreLabel: UILabel, lastScoreLabel: UILabel) {
self.scoreContainer = scoreContainer
self.totalScoreLabel = totalScoreLabel
self.lastScoreLabel = lastScoreLabel
}
func display(location: CGPoint) {
if (self.totalScore == 0 && self.lastScore == 0) {
return
}
self.totalScoreLabel.text = "\(self.totalScore)"
self.lastScoreLabel.text = "+\(self.lastScore)"
self.scoreContainer.center = location
UIView.animateWithDuration(
0.2,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
self.lastScoreLabel.alpha = 1.0
self.scoreContainer.alpha = 1.0
},
completion: nil
)
UIView.animateWithDuration(
0.2,
delay: 0.2,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
self.totalScoreLabel.alpha = 1.0
},
completion: nil
)
}
func hide() {
self.totalScoreLabel.alpha = 0.0
self.lastScoreLabel.alpha = 0.0
self.scoreContainer.alpha = 0.0
}
func add(score: Int) {
self.lastScore = score
self.totalScore = self.totalScore + score
}
} | mit | 718914a7cb5b2ea289d5b797864cd78a | 25.107692 | 85 | 0.568396 | 4.486772 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/modules/request-permissions/managers/presenters/dialog/interactive/data-source/SPRequestPermissionDialogInteractiveDataSource.swift | 2 | 5995 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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
open class SPRequestPermissionDialogInteractiveDataSource: NSObject, SPRequestPermissionDialogInteractiveDataSourceInterface {
open func iconForNormalPermissionControl(_ permission: SPRequestPermissionType) -> UIImage {
var iconBezierPath = UIBezierPath()
let requestWidth: CGFloat = 100
switch permission {
case .camera:
iconBezierPath = SPBezierPathFigure.icons.camera()
case .photoLibrary:
iconBezierPath = SPBezierPathFigure.icons.photo_library()
case .notification:
iconBezierPath = SPBezierPathFigure.icons.notification()
case .microphone:
iconBezierPath = SPBezierPathFigure.icons.microphone()
case .calendar:
iconBezierPath = SPBezierPathFigure.icons.calendar()
case .locationWhenInUse:
iconBezierPath = SPBezierPathFigure.icons.location()
case .locationAlways:
iconBezierPath = SPBezierPathFigure.icons.location()
case .locationWithBackground:
iconBezierPath = SPBezierPathFigure.icons.location()
case .contacts:
iconBezierPath = SPBezierPathFigure.icons.contacts()
case .reminders:
iconBezierPath = SPBezierPathFigure.icons.reminders()
}
iconBezierPath.resizeTo(width: requestWidth)
return iconBezierPath.convertToImage(fill: true, stroke: false, color: UIColor.black)
}
open func iconForAllowedPermissionControl(_ permission: SPRequestPermissionType) -> UIImage {
let requestWidth: CGFloat = 100
let checkedBezierPath = SPBezierPathFigure.icons.checked()
checkedBezierPath.resizeTo(width: requestWidth)
return checkedBezierPath.convertToImage(fill: true, stroke: false, color: UIColor.black)
}
open func titleForPermissionControl(_ permission: SPRequestPermissionType) -> String {
var title = String()
switch permission {
case .camera:
title = SPRequestPermissionData.texts.enable_camera()
case .photoLibrary:
title = SPRequestPermissionData.texts.enable_photoLibrary()
case .notification:
title = SPRequestPermissionData.texts.enable_notification()
case .microphone:
title = SPRequestPermissionData.texts.enable_microphone()
case .calendar:
title = SPRequestPermissionData.texts.enable_calendar()
case .locationWhenInUse:
title = SPRequestPermissionData.texts.enable_location()
case .locationAlways:
title = SPRequestPermissionData.texts.enable_location()
case .locationWithBackground:
title = SPRequestPermissionData.texts.enable_location()
case .contacts:
title = SPRequestPermissionData.texts.enable_contacts()
case .reminders:
title = SPRequestPermissionData.texts.enable_reminedrs()
}
return title
}
open func headerBackgroundView() -> UIView {
let patternView = SPRequestPermissionData.views.patternView()
let gradientView = SPGradientWithPictureView.init()
gradientView.startColor = SPRequestPermissionData.colors.gradient.dark.lightColor()
gradientView.endColor = SPRequestPermissionData.colors.gradient.dark.darkColor()
gradientView.startColorPoint = CGPoint.init(x: 0.5, y: 0)
gradientView.endColorPoint = CGPoint.init(x: 0.5, y: 1)
gradientView.pictureView = patternView
return gradientView
}
open func headerTitle() -> String {
return SPRequestPermissionData.texts.title()
}
open func headerSubtitle() -> String {
return SPRequestPermissionData.texts.subtitile()
}
open func topAdviceTitle() -> String {
return SPRequestPermissionData.texts.advice()
}
open func bottomAdviceTitle() -> String {
return SPRequestPermissionData.texts.advice_additional()
}
open func underDialogAdviceTitle() -> String {
return SPRequestPermissionData.texts.swipe_for_hide()
}
open func titleForAlertDenidPermission() -> String {
return SPRequestPermissionData.texts.titleForDenidPermission()
}
open func subtitleForAlertDenidPermission() -> String {
return SPRequestPermissionData.texts.subtitleForDenidPermission()
}
open func cancelForAlertDenidPermission() -> String {
return SPRequestPermissionData.texts.cancel()
}
open func settingForAlertDenidPermission() -> String {
return SPRequestPermissionData.texts.settings()
}
open func mainColor() -> UIColor {
return UIColor.init(hex: "#27AEE8")
}
open func secondColor() -> UIColor {
return UIColor.white
}
}
| mit | 3b275a6cb541df639d3cedfea5867f3a | 40.054795 | 126 | 0.692192 | 5.079661 | false | false | false | false |
dropbox/SwiftyDropbox | Source/SwiftyDropbox/Shared/Handwritten/DropboxClientsManager.swift | 1 | 8880 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import Foundation
import Alamofire
/// This is a convenience class for the typical single user case. To use this
/// class, see details in the tutorial at:
/// https://www.dropbox.com/developers/documentation/swift#tutorial
///
/// For information on the available API methods, see the documentation for DropboxClient
open class DropboxClientsManager {
/// An authorized client. This will be set to nil if unlinked.
public static var authorizedClient: DropboxClient?
/// An authorized team client. This will be set to nil if unlinked.
public static var authorizedTeamClient: DropboxTeamClient?
/// Sets up access to the Dropbox User API
static func setupWithOAuthManager(_ appKey: String, oAuthManager: DropboxOAuthManager, transportClient: DropboxTransportClient?) {
precondition(DropboxOAuthManager.sharedOAuthManager == nil, "Only call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` once")
DropboxOAuthManager.sharedOAuthManager = oAuthManager
if let token = DropboxOAuthManager.sharedOAuthManager.getFirstAccessToken() {
setupAuthorizedClient(token, transportClient:transportClient)
}
Keychain.checkAccessibilityMigrationOneTime
}
/// Sets up access to the Dropbox User API
static func setupWithOAuthManagerMultiUser(_ appKey: String, oAuthManager: DropboxOAuthManager, transportClient: DropboxTransportClient?, tokenUid: String?) {
precondition(DropboxOAuthManager.sharedOAuthManager == nil, "Only call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` once")
DropboxOAuthManager.sharedOAuthManager = oAuthManager
if let token = DropboxOAuthManager.sharedOAuthManager.getAccessToken(tokenUid) {
setupAuthorizedClient(token, transportClient:transportClient)
}
Keychain.checkAccessibilityMigrationOneTime
}
/// Sets up access to the Dropbox Business (Team) API
static func setupWithOAuthManagerTeam(_ appKey: String, oAuthManager: DropboxOAuthManager, transportClient: DropboxTransportClient?) {
precondition(DropboxOAuthManager.sharedOAuthManager == nil, "Only call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` once")
DropboxOAuthManager.sharedOAuthManager = oAuthManager
if let token = DropboxOAuthManager.sharedOAuthManager.getFirstAccessToken() {
setupAuthorizedTeamClient(token, transportClient:transportClient)
}
Keychain.checkAccessibilityMigrationOneTime
}
/// Sets up access to the Dropbox Business (Team) API in multi-user case
static func setupWithOAuthManagerMultiUserTeam(_ appKey: String, oAuthManager: DropboxOAuthManager, transportClient: DropboxTransportClient?, tokenUid: String?) {
precondition(DropboxOAuthManager.sharedOAuthManager == nil, "Only call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` once")
DropboxOAuthManager.sharedOAuthManager = oAuthManager
if let token = DropboxOAuthManager.sharedOAuthManager.getAccessToken(tokenUid) {
setupAuthorizedTeamClient(token, transportClient:transportClient)
}
Keychain.checkAccessibilityMigrationOneTime
}
public static func reauthorizeClient(_ tokenUid: String) {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` before calling this method")
if let token = DropboxOAuthManager.sharedOAuthManager.getAccessToken(tokenUid) {
setupAuthorizedClient(token, transportClient:nil)
}
Keychain.checkAccessibilityMigrationOneTime
}
public static func reauthorizeTeamClient(_ tokenUid: String) {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` before calling this method")
if let token = DropboxOAuthManager.sharedOAuthManager.getAccessToken(tokenUid) {
setupAuthorizedTeamClient(token, transportClient:nil)
}
Keychain.checkAccessibilityMigrationOneTime
}
static func setupAuthorizedClient(_ accessToken: DropboxAccessToken?, transportClient: DropboxTransportClient?) {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` before calling this method")
if let accessToken = accessToken, let oauthManager = DropboxOAuthManager.sharedOAuthManager {
let accessTokenProvider = oauthManager.accessTokenProviderForToken(accessToken)
if let transportClient = transportClient {
transportClient.accessTokenProvider = accessTokenProvider
authorizedClient = DropboxClient(transportClient: transportClient)
} else {
authorizedClient = DropboxClient(accessTokenProvider: accessTokenProvider)
}
} else {
if let transportClient = transportClient {
authorizedClient = DropboxClient(transportClient: transportClient)
}
}
}
static func setupAuthorizedTeamClient(_ accessToken: DropboxAccessToken?, transportClient: DropboxTransportClient?) {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` before calling this method")
if let accessToken = accessToken, let oauthManager = DropboxOAuthManager.sharedOAuthManager {
let accessTokenProvider = oauthManager.accessTokenProviderForToken(accessToken)
if let transportClient = transportClient {
transportClient.accessTokenProvider = accessTokenProvider
authorizedTeamClient = DropboxTeamClient(transportClient: transportClient)
} else {
authorizedTeamClient = DropboxTeamClient(accessTokenProvider: accessTokenProvider)
}
} else {
if let transportClient = transportClient {
authorizedTeamClient = DropboxTeamClient(transportClient: transportClient)
}
}
}
/// Handle a redirect and automatically initialize the client and save the token.
///
/// - parameters:
/// - url: The URL to attempt to handle.
/// - completion: The callback closure to receive auth result.
/// - returns: Whether the redirect URL can be handled.
///
@discardableResult
public static func handleRedirectURL(_ url: URL, completion: @escaping DropboxOAuthCompletion) -> Bool {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` before calling this method")
return DropboxOAuthManager.sharedOAuthManager.handleRedirectURL(url, completion: { result in
if let result = result {
switch result {
case .success(let accessToken):
setupAuthorizedClient(accessToken, transportClient: nil)
case .cancel, .error:
break
}
}
completion(result)
})
}
/// Handle a redirect and automatically initialize the client and save the token.
///
/// - parameters:
/// - url: The URL to attempt to handle.
/// - completion: The callback closure to receive auth result.
/// - returns: Whether the redirect URL can be handled.
///
@discardableResult
public static func handleRedirectURLTeam(_ url: URL, completion: @escaping DropboxOAuthCompletion) -> Bool {
precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithTeamAppKey` before calling this method")
return DropboxOAuthManager.sharedOAuthManager.handleRedirectURL(url, completion: { result in
if let result = result {
switch result {
case .success(let accessToken):
setupAuthorizedTeamClient(accessToken, transportClient: nil)
case .cancel, .error:
break
}
}
completion(result)
})
}
/// Unlink the user.
public static func unlinkClients() {
if let oAuthManager = DropboxOAuthManager.sharedOAuthManager {
_ = oAuthManager.clearStoredAccessTokens()
resetClients()
}
}
/// Unlink the user.
public static func resetClients() {
if DropboxClientsManager.authorizedClient == nil && DropboxClientsManager.authorizedTeamClient == nil {
// already unlinked
return
}
DropboxClientsManager.authorizedClient = nil
DropboxClientsManager.authorizedTeamClient = nil
}
}
| mit | 51039e2613ca38a666492bcab7ce8760 | 47.791209 | 172 | 0.704955 | 5.740142 | false | false | false | false |
tomisacat/AudioTips | AudioTips/AudioFormatService.playground/Contents.swift | 1 | 3434 | //: Playground - noun: a place where people can play
import UIKit
import AudioToolbox
// function
func openFile() -> AudioFileID? {
let url = Bundle.main.url(forResource: "guitar", withExtension: "m4a")
var fd: AudioFileID? = nil
AudioFileOpenURL(url! as CFURL, .readPermission, kAudioFileM4AType, &fd)
// Or in iOS platform, the file type could be 0 directly
// AudioFileOpenURL(url! as CFURL, .readPermission, 0, &fd)
return fd
}
func closeFile(fd: AudioFileID) {
AudioFileClose(fd)
}
// use
let fd: AudioFileID? = openFile()
if let fd = fd {
var status: OSStatus = noErr
var propertySize: UInt32 = 0
var writable: UInt32 = 0
// magic cookie
status = AudioFileGetPropertyInfo(fd, kAudioFilePropertyMagicCookieData, &propertySize, &writable)
// if status != noErr {
// return
// }
let magic: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: Int(propertySize))
status = AudioFileGetProperty(fd, kAudioFilePropertyMagicCookieData, &propertySize, magic)
// if status != noErr {
// return
// }
// format info
var desc: AudioStreamBasicDescription = AudioStreamBasicDescription()
var descSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, propertySize, magic, &descSize, &desc)
// if status != noErr {
// return
// }
print(desc)
// format name
status = AudioFileGetProperty(fd, kAudioFilePropertyDataFormat, &descSize, &desc)
// if status != noErr {
// return
// }
var formatName: CFString = String() as CFString
var formatNameSize: UInt32 = UInt32(MemoryLayout<CFString>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatName, descSize, &desc, &formatNameSize, &formatName)
// if status != noErr {
// return
// }
print(formatName)
// format info
var formatInfo: AudioFormatInfo = AudioFormatInfo(mASBD: desc,
mMagicCookie: magic,
mMagicCookieSize: propertySize)
var outputFormatInfoSize: UInt32 = 0
status = AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize)
// format list
let formatListItem: UnsafeMutablePointer<AudioFormatListItem> = UnsafeMutablePointer<AudioFormatListItem>.allocate(capacity: Int(outputFormatInfoSize))
status = AudioFormatGetProperty(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize,
formatListItem)
// if status != noErr {
// return
// }
let itemCount = outputFormatInfoSize / UInt32(MemoryLayout<AudioFormatListItem>.size)
for idx in 0..<itemCount {
let item: AudioFormatListItem = formatListItem.advanced(by: Int(idx)).pointee
print("channel layout tag is \(item.mChannelLayoutTag), mASBD is \(item.mASBD)")
}
closeFile(fd: fd)
}
| mit | 55b27c307b0e03ab71bc0ef989775278 | 33.34 | 155 | 0.618521 | 4.58478 | false | false | false | false |
cnbin/MarkdownTextView | MarkdownTextView/HighlighterTextStorage.swift | 1 | 3508 | //
// RegularExpressionTextStorage.swift
// MarkdownTextView
//
// Created by Indragie on 4/28/15.
// Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//
import UIKit
/**
* Text storage with support for automatically highlighting text
* as it changes.
*/
public class HighlighterTextStorage: NSTextStorage {
private let backingStore: NSMutableAttributedString
private var highlighters = [HighlighterType]()
/// Default attributes to use for styling text.
public var defaultAttributes: [String: AnyObject] = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
] {
didSet { editedAll(.EditedAttributes) }
}
// MARK: API
/**
Adds a highlighter to use for highlighting text.
Highlighters are invoked in the order in which they are added.
:param: highlighter The highlighter to add.
*/
public func addHighlighter(highlighter: HighlighterType) {
highlighters.append(highlighter)
editedAll(.EditedAttributes)
}
// MARK: Initialization
public override init() {
backingStore = NSMutableAttributedString(string: "", attributes: defaultAttributes)
super.init()
}
required public init(coder aDecoder: NSCoder) {
backingStore = NSMutableAttributedString(string: "", attributes: defaultAttributes)
super.init(coder: aDecoder)
}
// MARK: NSTextStorage
public override var string: String {
return backingStore.string
}
public override func attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [NSObject : AnyObject] {
return backingStore.attributesAtIndex(location, effectiveRange: range)
}
public override func replaceCharactersInRange(range: NSRange, withAttributedString attrString: NSAttributedString) {
backingStore.replaceCharactersInRange(range, withAttributedString: attrString)
edited(.EditedCharacters, range: range, changeInLength: attrString.length - range.length)
}
public override func setAttributes(attrs: [NSObject : AnyObject]?, range: NSRange) {
backingStore.setAttributes(attrs, range: range)
edited(.EditedAttributes, range: range, changeInLength: 0)
}
public override func processEditing() {
// This is inefficient but necessary because certain
// edits can cause formatting changes that span beyond
// line or paragraph boundaries. This should be alright
// for small amounts of text (which is the use case that
// this was designed for), but would need to be optimized
// for any kind of heavy editing.
highlightRange(NSRange(location: 0, length: (string as NSString).length))
super.processEditing()
}
private func editedAll(actions: NSTextStorageEditActions) {
edited(actions, range: NSRange(location: 0, length: backingStore.length), changeInLength: 0)
}
private func highlightRange(range: NSRange) {
backingStore.beginEditing()
setAttributes(defaultAttributes, range: range)
var attrString = backingStore.attributedSubstringFromRange(range).mutableCopy() as! NSMutableAttributedString
for highlighter in highlighters {
highlighter.highlightAttributedString(attrString)
}
replaceCharactersInRange(range, withAttributedString: attrString)
backingStore.endEditing()
}
}
| mit | 4c45b42ba5d5dcb7619e98722d1baba1 | 35.164948 | 123 | 0.695268 | 5.243647 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/Utils/UserActivityManager.swift | 1 | 3448 | //
// UserActivityManager.swift
// WaniKani
//
// Created by Andriy K. on 1/22/16.
// Copyright © 2016 Andriy K. All rights reserved.
//
import UIKit
import CoreSpotlight
import DataKit
class UserActivityManager: NSObject {
private var lastInexedLevelSetting = IntUserDefault(key: "lastInexedLevelDefaultsKey")
override init() {
super.init()
appDelegate.notificationCenterManager.addObserver(self, notification: .NewStudyQueueReceivedNotification, selector: "newStudyQueueData:")
appDelegate.notificationCenterManager.addObserver(self, notification: .UpdatedKanjiListNotification, selector: "newKanjiData:")
}
deinit {
appDelegate.notificationCenterManager.removeObserver(self)
}
func newStudyQueueData(notification: NSNotification) {
guard #available(iOS 9.0, *) else { return }
guard let studyQueue = user?.studyQueue else { return }
var updatedShortcutItems = [UIMutableApplicationShortcutItem]()
if studyQueue.reviewsAvaliable > 0 {
let reviewItem = UIMutableApplicationShortcutItem(type: "Review", localizedTitle: "Review")
reviewItem.icon = UIApplicationShortcutIcon(templateImageName: "reviews_quick")
updatedShortcutItems.append(reviewItem)
}
if studyQueue.lessonsAvaliable > 0 {
let lessonsItem = UIMutableApplicationShortcutItem(type: "Lessons", localizedTitle: "Lessons")
lessonsItem.icon = UIApplicationShortcutIcon(templateImageName: "lessons_quick")
updatedShortcutItems.append(lessonsItem)
}
UIApplication.sharedApplication().shortcutItems = updatedShortcutItems
}
func newKanjiData(notification: NSNotification) {
guard #available(iOS 9.0, *) else { return }
guard let level = notification.object as? Int, let currentLvl = user?.level where level <= currentLvl else { return }
let lastIndexedLevel = lastInexedLevelSetting.value
let numberOfLevelsToIndex = 5
if (lastIndexedLevel != 0) && (lastIndexedLevel != currentLvl) {
let oldMinIndexedLevel = max(lastIndexedLevel - numberOfLevelsToIndex + 1, 1)
let minLevelToIndex = max(currentLvl - numberOfLevelsToIndex + 1, 1)
let levelsToRemoveFromIndex = [Int](oldMinIndexedLevel..<min(minLevelToIndex, oldMinIndexedLevel + lastIndexedLevel))
let domainIdentifiersToRemove = levelsToRemoveFromIndex.map { (index) -> String in
return Kanji.searchIdentifierForLevel(index)
}
CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithIdentifiers(domainIdentifiersToRemove, completionHandler: { (error) -> Void in
print(error)
})
}
let levelsToIndex = [Int](max(lastIndexedLevel + 1, currentLvl - numberOfLevelsToIndex + 1)...currentLvl)
if levelsToIndex.contains(level) {
if let levelKanji = user?.levels?.levelDataForLevel(level)?.kanjiList {
let kanjiSearchableItems = levelKanji.map({ (kanji) -> CSSearchableItem in
let item = CSSearchableItem(uniqueIdentifier: kanji.uniqueIdentifier, domainIdentifier: kanji.domainIdentifier, attributeSet: kanji.attributeSet)
return item
})
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(kanjiSearchableItems, completionHandler: { (error) -> Void in
print(error)
})
}
}
// Add items
print(currentLvl)
print(level)
}
}
| gpl-3.0 | 6d6f456435c7cc8193bf245d0adf6256 | 35.284211 | 155 | 0.713084 | 4.709016 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Collections/NoResultsView.swift | 1 | 2500 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// 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 Foundation
import WireCommonComponents
import UIKit
import WireSystem
final class NoResultsView: UIView {
let label = UILabel()
private let iconView = UIImageView()
var placeholderText: String? {
get {
return label.text
}
set {
label.text = newValue
label.accessibilityLabel = newValue
}
}
var icon: StyleKitIcon? {
didSet {
iconView.image = icon?.makeImage(size: 160, color: placeholderColor)
iconView.tintColor = placeholderColor
}
}
var placeholderColor: UIColor {
let backgroundColor = SemanticColors.Label.textSettingsPasswordPlaceholder
return backgroundColor
}
override init(frame: CGRect) {
super.init(frame: frame)
accessibilityElements = [label]
label.numberOfLines = 0
label.textColor = SemanticColors.Label.textSettingsPasswordPlaceholder
label.textAlignment = .center
label.font = FontSpec.mediumSemiboldFont.font!
addSubview(label)
iconView.contentMode = .scaleAspectFit
addSubview(iconView)
[label, iconView].prepareForLayout()
NSLayoutConstraint.activate([
iconView.topAnchor.constraint(equalTo: topAnchor),
iconView.centerXAnchor.constraint(equalTo: centerXAnchor),
label.topAnchor.constraint(equalTo: iconView.bottomAnchor, constant: 24),
label.bottomAnchor.constraint(equalTo: bottomAnchor),
label.leadingAnchor.constraint(equalTo: leadingAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatal("init?(coder:) is not implemented")
}
}
| gpl-3.0 | 0aa7d33b667f241f8cbb02399d670a97 | 30.25 | 83 | 0.678 | 5.040323 | false | false | false | false |
beckasaurus/skin-ios | skin/Pods/RealmSwift/RealmSwift/LinkingObjects.swift | 13 | 18268 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/// :nodoc:
/// Internal class. Do not use directly. Used for reflection and initialization
public class LinkingObjectsBase: NSObject, NSFastEnumeration {
internal let objectClassName: String
internal let propertyName: String
fileprivate var cachedRLMResults: RLMResults<AnyObject>?
@objc fileprivate var object: RLMWeakObjectHandle?
@objc fileprivate var property: RLMProperty?
internal var rlmResults: RLMResults<AnyObject> {
if cachedRLMResults == nil {
if let object = self.object, let property = self.property {
cachedRLMResults = RLMDynamicGet(object.object, property)! as? RLMResults
self.object = nil
self.property = nil
} else {
cachedRLMResults = RLMResults.emptyDetached()
}
}
return cachedRLMResults!
}
init(fromClassName objectClassName: String, property propertyName: String) {
self.objectClassName = objectClassName
self.propertyName = propertyName
}
// MARK: Fast Enumeration
public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>,
objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>,
count len: Int) -> Int {
return Int(rlmResults.countByEnumerating(with: state,
objects: buffer,
count: UInt(len)))
}
}
/**
`LinkingObjects` is an auto-updating container type. It represents zero or more objects that are linked to its owning
model object through a property relationship.
`LinkingObjects` can be queried with the same predicates as `List<Element>` and `Results<Element>`.
`LinkingObjects` always reflects the current state of the Realm on the current thread, including during write
transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always
enumerate over the linking objects that were present when the enumeration is begun, even if some of them are deleted or
modified to no longer link to the target object during the enumeration.
`LinkingObjects` can only be used as a property on `Object` models. Properties of this type must be declared as `let`
and cannot be `dynamic`.
*/
public final class LinkingObjects<Element: Object>: LinkingObjectsBase {
/// The type of the objects represented by the linking objects.
public typealias ElementType = Element
// MARK: Properties
/// The Realm which manages the linking objects, or `nil` if the linking objects are unmanaged.
public var realm: Realm? { return rlmResults.isAttached ? Realm(rlmResults.realm) : nil }
/// Indicates if the linking objects are no longer valid.
///
/// The linking objects become invalid if `invalidate()` is called on the containing `realm` instance.
///
/// An invalidated linking objects can be accessed, but will always be empty.
public var isInvalidated: Bool { return rlmResults.isInvalidated }
/// The number of linking objects.
public var count: Int { return Int(rlmResults.count) }
// MARK: Initializers
/**
Creates an instance of a `LinkingObjects`. This initializer should only be called when declaring a property on a
Realm model.
- parameter type: The type of the object owning the property the linking objects should refer to.
- parameter propertyName: The property name of the property the linking objects should refer to.
*/
public init(fromType type: Element.Type, property propertyName: String) {
let className = (Element.self as Object.Type).className()
super.init(fromClassName: className, property: propertyName)
}
/// A human-readable description of the objects represented by the linking objects.
public override var description: String {
return RLMDescriptionWithMaxDepth("LinkingObjects", rlmResults, RLMDescriptionMaxDepth)
}
// MARK: Index Retrieval
/**
Returns the index of an object in the linking objects, or `nil` if the object is not present.
- parameter object: The object whose index is being queried.
*/
public func index(of object: Element) -> Int? {
return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject()))
}
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: predicate))
}
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat,
argumentArray: unwrapOptionals(in: args))))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(index: Int) -> Element {
get {
throwForNegativeIndex(index)
return unsafeBitCast(rlmResults[UInt(index)], to: Element.self)
}
}
/// Returns the first object in the linking objects, or `nil` if the linking objects are empty.
public var first: Element? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<Element>.self) }
/// Returns the last object in the linking objects, or `nil` if the linking objects are empty.
public var last: Element? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<Element>.self) }
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the linking objects.
- parameter key: The name of the property whose values are desired.
*/
public override func value(forKey key: String) -> Any? {
return value(forKeyPath: key)
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the linking
objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
public override func value(forKeyPath keyPath: String) -> Any? {
return rlmResults.value(forKeyPath: keyPath)
}
/**
Invokes `setValue(_:forKey:)` on each of the linking objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The value to set the property to.
- parameter key: The name of the property whose value should be set on each object.
*/
public override func setValue(_ value: Any?, forKey key: String) {
return rlmResults.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the linking objects.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return Results(rlmResults.objects(with: NSPredicate(format: predicateFormat,
argumentArray: unwrapOptionals(in: args))))
}
/**
Returns a `Results` containing all objects matching the given predicate in the linking objects.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> {
return Results(rlmResults.objects(with: predicate))
}
// MARK: Sorting
/**
Returns a `Results` containing all the linking objects, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing all the linking objects, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return Results(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the linking objects, or `nil` if the linking
objects are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmResults.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the linking objects, or `nil` if the linking
objects are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmResults.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the linking objects.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T {
return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the linking objects, or `nil` if the linking objects are
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<T: AddableType>(ofProperty property: String) -> T? {
return rlmResults.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(_ block: @escaping (RealmCollectionChange<LinkingObjects>) -> Void) -> NotificationToken {
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
}
}
}
extension LinkingObjects: RealmCollection {
// MARK: Sequence Support
/// Returns an iterator that yields successive elements in the linking objects.
public func makeIterator() -> RLMIterator<Element> {
return RLMIterator(collection: rlmResults)
}
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after: Int) -> Int {
return after + 1
}
public func index(before: Int) -> Int {
return before - 1
}
/// :nodoc:
public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) ->
NotificationToken {
let anyCollection = AnyRealmCollection(self)
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
}
}
}
// MARK: AssistedObjectiveCBridgeable
extension LinkingObjects: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> LinkingObjects {
guard let metadata = metadata as? LinkingObjectsBridgingMetadata else { preconditionFailure() }
let swiftValue = LinkingObjects(fromType: Element.self, property: metadata.propertyName)
switch (objectiveCValue, metadata) {
case (let object as RLMObjectBase, .uncached(let property)):
swiftValue.object = RLMWeakObjectHandle(object: object)
swiftValue.property = property
case (let results as RLMResults<AnyObject>, .cached):
swiftValue.cachedRLMResults = results
default:
preconditionFailure()
}
return swiftValue
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
if let results = cachedRLMResults {
return (objectiveCValue: results,
metadata: LinkingObjectsBridgingMetadata.cached(propertyName: propertyName))
} else {
return (objectiveCValue: (object!.copy() as! RLMWeakObjectHandle).object,
metadata: LinkingObjectsBridgingMetadata.uncached(property: property!))
}
}
}
internal enum LinkingObjectsBridgingMetadata {
case uncached(property: RLMProperty)
case cached(propertyName: String)
fileprivate var propertyName: String {
switch self {
case .uncached(let property): return property.name
case .cached(let propertyName): return propertyName
}
}
}
| mit | fcd87188e78818e9f5fd331d03ef5d14 | 40.518182 | 122 | 0.674349 | 5.097098 | false | false | false | false |
j-chao/venture | source/Pods/BrightFutures/Sources/BrightFutures/SequenceType+BrightFutures.swift | 3 | 6361 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// 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 Result
extension Sequence {
/// Turns a sequence of T's into an array of `Future<U>`'s by calling the given closure for each element in the sequence.
/// If no context is provided, the given closure is executed on `Queue.global`
public func traverse<U, E, A: AsyncType>(_ context: @escaping ExecutionContext = DispatchQueue.global().context, f: (Iterator.Element) -> A) -> Future<[U], E> where A.Value: ResultProtocol, A.Value.Value == U, A.Value.Error == E {
return map(f).fold(context, zero: [U]()) { (list: [U], elem: U) -> [U] in
return list + [elem]
}
}
}
extension Sequence where Iterator.Element: AsyncType {
/// Returns a future that returns with the first future from the given sequence that completes
/// (regardless of whether that future succeeds or fails)
public func firstCompleted() -> Iterator.Element {
let res = Async<Iterator.Element.Value>()
for fut in self {
fut.onComplete(DispatchQueue.global().context) {
res.tryComplete($0)
}
}
return Iterator.Element(other: res)
}
}
extension Sequence where Iterator.Element: AsyncType, Iterator.Element.Value: ResultProtocol {
//// The free functions in this file operate on sequences of Futures
/// Performs the fold operation over a sequence of futures. The folding is performed
/// on `Queue.global`.
/// (The Swift compiler does not allow a context parameter with a default value
/// so we define some functions twice)
public func fold<R>(_ zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> {
return fold(DispatchQueue.global().context, zero: zero, f: f)
}
/// Performs the fold operation over a sequence of futures. The folding is performed
/// in the given context.
public func fold<R>(_ context: @escaping ExecutionContext, zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> {
return reduce(Future<R, Iterator.Element.Value.Error>(value: zero)) { zero, elem in
return zero.flatMap(MaxStackDepthExecutionContext) { zeroVal in
elem.map(context) { elemVal in
return f(zeroVal, elemVal)
}
}
}
}
/// Turns a sequence of `Future<T>`'s into a future with an array of T's (Future<[T]>)
/// If one of the futures in the given sequence fails, the returned future will fail
/// with the error of the first future that comes first in the list.
public func sequence() -> Future<[Iterator.Element.Value.Value], Iterator.Element.Value.Error> {
return traverse(ImmediateExecutionContext) {
return $0
}
}
/// See `find<S: SequenceType, T where S.Iterator.Element == Future<T>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T>`
public func find(_ p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> {
return find(DispatchQueue.global().context, p: p)
}
/// Returns a future that succeeds with the value from the first future in the given
/// sequence that passes the test `p`.
/// If any of the futures in the given sequence fail, the returned future fails with the
/// error of the first failed future in the sequence.
/// If no futures in the sequence pass the test, a future with an error with NoSuchElement is returned.
public func find(_ context: @escaping ExecutionContext, p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> {
return sequence().mapError(ImmediateExecutionContext) { error in
return BrightFuturesError(external: error)
}.flatMap(context) { val -> Result<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> in
for elem in val {
if (p(elem)) {
return Result(value: elem)
}
}
return Result(error: .noSuchElement)
}
}
}
extension Sequence where Iterator.Element: ResultProtocol {
/// Turns a sequence of `Result<T>`'s into a Result with an array of T's (`Result<[T]>`)
/// If one of the results in the given sequence is a .failure, the returned result is a .failure with the
/// error from the first failed result from the sequence.
public func sequence() -> Result<[Iterator.Element.Value], Iterator.Element.Error> {
return reduce(Result(value: [])) { (res, elem) -> Result<[Iterator.Element.Value], Iterator.Element.Error> in
switch res {
case .success(let resultSequence):
return elem.analysis(ifSuccess: {
let newSeq = resultSequence + [$0]
return Result(value: newSeq)
}, ifFailure: {
return Result(error: $0)
})
case .failure(_):
return res
}
}
}
}
| mit | b39b110dd3d4972b825ba7b5ebd86a44 | 49.484127 | 234 | 0.656815 | 4.429666 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBBScheduledActivity+Filters.swift | 1 | 3938 | //
// SBBScheduledActivity+Filters.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension SBBScheduledActivity {
public static func unfinishedPredicate() -> NSPredicate {
return NSPredicate(format: "%K == nil", #keyPath(finishedOn))
}
public static func finishedTodayPredicate() -> NSPredicate {
return NSPredicate(day: Date(), dateKey: #keyPath(finishedOn))
}
public static func scheduledTodayPredicate() -> NSPredicate {
return NSPredicate(day: Date(), dateKey: #keyPath(scheduledOn))
}
public static func scheduledTomorrowPredicate() -> NSPredicate {
return NSPredicate(day: Date().addingNumberOfDays(1), dateKey: #keyPath(scheduledOn))
}
public static func scheduledComingUpPredicate(numberOfDays: Int) -> NSPredicate {
return NSPredicate(date: Date().addingNumberOfDays(1), dateKey: #keyPath(scheduledOn), numberOfDays: numberOfDays)
}
public static func expiredYesterdayPredicate() -> NSPredicate {
return NSPredicate(day: Date().addingNumberOfDays(-1), dateKey: #keyPath(expiresOn))
}
public static func optionalPredicate() -> NSPredicate {
return NSPredicate(format: "%K == 1", #keyPath(persistent))
}
public static func availableTodayPredicate() -> NSPredicate {
let startOfToday = Date().startOfDay()
let startOfTomorrow = startOfToday.addingNumberOfDays(1)
// Scheduled today or prior
let scheduledKey = #keyPath(scheduledOn)
let todayOrBefore = NSPredicate(format: "%K == nil OR %K < %@", scheduledKey, scheduledKey, startOfTomorrow as CVarArg)
// Unfinished or done today
let unfinishedOrFinishedToday = NSCompoundPredicate(orPredicateWithSubpredicates: [unfinishedPredicate(), finishedTodayPredicate()])
// Not expired
let expiredKey = #keyPath(expiresOn)
let notExpired = NSPredicate(format: "%K == nil OR %K > %@", expiredKey, expiredKey, startOfToday as CVarArg)
// And
let availableToday = NSCompoundPredicate(andPredicateWithSubpredicates: [todayOrBefore, unfinishedOrFinishedToday, notExpired])
return availableToday
}
}
| bsd-3-clause | 8dc8c09a8b63c6ca0e430bfdd6e3e3c3 | 44.77907 | 140 | 0.718821 | 4.97096 | false | false | false | false |
imzyf/99-projects-of-swift | 005-change-font-name/005-change-font-name/ViewController.swift | 1 | 1153 | //
// ViewController.swift
// 005-change-font-name
//
// Created by moma on 2017/10/15.
// Copyright © 2017年 yifans. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var changeButton: UIButton!
var familyNames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
familyNames = UIFont.familyNames
for familyName in familyNames {
print("++++++ \(familyName)")
let fontNames = UIFont.fontNames(forFamilyName: familyName)
for fontName in fontNames {
print("----- \(fontName)")
}
}
}
@IBAction func changeFontFamily() {
let name = familyNames[randomCustom(min: 0, max: familyNames.count)]
nameLabel.text = name
titleLabel.font = UIFont(name: name, size: 20)
}
// 左闭右开
func randomCustom(min: Int, max: Int) -> Int {
let y = arc4random() % UInt32(max) + UInt32(min)
print(y)
return Int(y)
}
}
| mit | 48e0b71895fe4ec2844eaeab38f22c16 | 23.826087 | 76 | 0.584939 | 4.293233 | false | false | false | false |
phatblat/realm-cocoa | Realm/ObjectServerTests/SwiftObjectServerTests.swift | 1 | 121061 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#if os(macOS)
import Combine
import Realm
import RealmSwift
import XCTest
#if canImport(RealmTestSupport)
import RealmSwiftSyncTestSupport
import RealmSyncTestSupport
import RealmTestSupport
#endif
@available(OSX 10.14, *)
@objc(SwiftObjectServerTests)
class SwiftObjectServerTests: SwiftSyncTestCase {
/// It should be possible to successfully open a Realm configured for sync.
func testBasicSwiftSync() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: #function, user: user)
XCTAssert(realm.isEmpty, "Freshly synced Realm was not empty...")
} catch {
XCTFail("Got an error: \(error)")
}
}
func testBasicSwiftSyncWithAnyBSONPartitionValue() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: .string(#function), user: user)
XCTAssert(realm.isEmpty, "Freshly synced Realm was not empty...")
} catch {
XCTFail("Got an error: \(error)")
}
}
func testBasicSwiftSyncWithNilPartitionValue() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: .null, user: user)
XCTAssert(realm.isEmpty, "Freshly synced Realm was not empty...")
} catch {
XCTFail("Got an error: \(error)")
}
}
/// If client B adds objects to a Realm, client A should see those new objects.
func testSwiftAddObjects() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: #function, user: user)
if isParent {
checkCount(expected: 0, realm, SwiftPerson.self)
checkCount(expected: 0, realm, SwiftTypesSyncObject.self)
executeChild()
waitForDownloads(for: realm)
checkCount(expected: 4, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftTypesSyncObject.self)
let obj = realm.objects(SwiftTypesSyncObject.self).first!
XCTAssertEqual(obj.boolCol, true)
XCTAssertEqual(obj.intCol, 1)
XCTAssertEqual(obj.doubleCol, 1.1)
XCTAssertEqual(obj.stringCol, "string")
XCTAssertEqual(obj.binaryCol, "string".data(using: String.Encoding.utf8)!)
XCTAssertEqual(obj.decimalCol, Decimal128(1))
XCTAssertEqual(obj.dateCol, Date(timeIntervalSince1970: -1))
XCTAssertEqual(obj.longCol, Int64(1))
XCTAssertEqual(obj.uuidCol, UUID(uuidString: "85d4fbee-6ec6-47df-bfa1-615931903d7e")!)
XCTAssertEqual(obj.anyCol.value.intValue, 1)
XCTAssertEqual(obj.objectCol!.firstName, "George")
} else {
// Add objects
try realm.write {
realm.add(SwiftPerson(firstName: "Ringo", lastName: "Starr"))
realm.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realm.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
realm.add(SwiftTypesSyncObject(person: SwiftPerson(firstName: "George", lastName: "Harrison")))
}
waitForUploads(for: realm)
checkCount(expected: 4, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftTypesSyncObject.self)
}
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testSwiftRountripForDistinctPrimaryKey() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: #function, user: user)
if isParent {
checkCount(expected: 0, realm, SwiftPerson.self) // ObjectId
checkCount(expected: 0, realm, SwiftUUIDPrimaryKeyObject.self)
checkCount(expected: 0, realm, SwiftStringPrimaryKeyObject.self)
checkCount(expected: 0, realm, SwiftIntPrimaryKeyObject.self)
executeChild()
waitForDownloads(for: realm)
checkCount(expected: 1, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftUUIDPrimaryKeyObject.self)
checkCount(expected: 1, realm, SwiftStringPrimaryKeyObject.self)
checkCount(expected: 1, realm, SwiftIntPrimaryKeyObject.self)
let swiftOjectIdPrimaryKeyObject = realm.object(ofType: SwiftPerson.self,
forPrimaryKey: ObjectId("1234567890ab1234567890ab"))!
XCTAssertEqual(swiftOjectIdPrimaryKeyObject.firstName, "Ringo")
XCTAssertEqual(swiftOjectIdPrimaryKeyObject.lastName, "Starr")
let swiftUUIDPrimaryKeyObject = realm.object(ofType: SwiftUUIDPrimaryKeyObject.self,
forPrimaryKey: UUID(uuidString: "85d4fbee-6ec6-47df-bfa1-615931903d7e")!)!
XCTAssertEqual(swiftUUIDPrimaryKeyObject.strCol, "Steve")
XCTAssertEqual(swiftUUIDPrimaryKeyObject.intCol, 10)
let swiftStringPrimaryKeyObject = realm.object(ofType: SwiftStringPrimaryKeyObject.self,
forPrimaryKey: "1234567890ab1234567890ab")!
XCTAssertEqual(swiftStringPrimaryKeyObject.strCol, "Paul")
XCTAssertEqual(swiftStringPrimaryKeyObject.intCol, 20)
let swiftIntPrimaryKeyObject = realm.object(ofType: SwiftIntPrimaryKeyObject.self,
forPrimaryKey: 1234567890)!
XCTAssertEqual(swiftIntPrimaryKeyObject.strCol, "Jackson")
XCTAssertEqual(swiftIntPrimaryKeyObject.intCol, 30)
} else {
try realm.write {
let swiftPerson = SwiftPerson(firstName: "Ringo", lastName: "Starr")
swiftPerson._id = ObjectId("1234567890ab1234567890ab")
realm.add(swiftPerson)
realm.add(SwiftUUIDPrimaryKeyObject(id: UUID(uuidString: "85d4fbee-6ec6-47df-bfa1-615931903d7e")!, strCol: "Steve", intCol: 10))
realm.add(SwiftStringPrimaryKeyObject(id: "1234567890ab1234567890ab", strCol: "Paul", intCol: 20))
realm.add(SwiftIntPrimaryKeyObject(id: 1234567890, strCol: "Jackson", intCol: 30))
}
waitForUploads(for: realm)
checkCount(expected: 1, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftUUIDPrimaryKeyObject.self)
checkCount(expected: 1, realm, SwiftStringPrimaryKeyObject.self)
checkCount(expected: 1, realm, SwiftIntPrimaryKeyObject.self)
}
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testSwiftAddObjectsWithNilPartitionValue() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: .null, user: user)
if isParent {
checkCount(expected: 0, realm, SwiftPerson.self)
executeChild()
waitForDownloads(for: realm)
checkCount(expected: 3, realm, SwiftPerson.self)
try realm.write {
realm.deleteAll()
}
waitForUploads(for: realm)
} else {
// Add objects
try realm.write {
realm.add(SwiftPerson(firstName: "Ringo", lastName: "Starr"))
realm.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realm.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
}
waitForUploads(for: realm)
checkCount(expected: 3, realm, SwiftPerson.self)
}
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
/// If client B removes objects from a Realm, client A should see those changes.
func testSwiftDeleteObjects() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: #function, user: user)
if isParent {
try realm.write {
realm.add(SwiftPerson(firstName: "Ringo", lastName: "Starr"))
realm.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realm.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
realm.add(SwiftTypesSyncObject(person: SwiftPerson(firstName: "George", lastName: "Harrison")))
}
waitForUploads(for: realm)
checkCount(expected: 4, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftTypesSyncObject.self)
executeChild()
} else {
checkCount(expected: 4, realm, SwiftPerson.self)
checkCount(expected: 1, realm, SwiftTypesSyncObject.self)
try realm.write {
realm.deleteAll()
}
waitForUploads(for: realm)
checkCount(expected: 0, realm, SwiftPerson.self)
checkCount(expected: 0, realm, SwiftTypesSyncObject.self)
}
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
/// A client should be able to open multiple Realms and add objects to each of them.
func testMultipleRealmsAddObjects() {
let partitionValueA = #function
let partitionValueB = "\(#function)bar"
let partitionValueC = "\(#function)baz"
do {
let user = try logInUser(for: basicCredentials())
let realmA = try openRealm(partitionValue: partitionValueA, user: user)
let realmB = try openRealm(partitionValue: partitionValueB, user: user)
let realmC = try openRealm(partitionValue: partitionValueC, user: user)
if self.isParent {
checkCount(expected: 0, realmA, SwiftPerson.self)
checkCount(expected: 0, realmB, SwiftPerson.self)
checkCount(expected: 0, realmC, SwiftPerson.self)
executeChild()
waitForDownloads(for: realmA)
waitForDownloads(for: realmB)
waitForDownloads(for: realmC)
checkCount(expected: 3, realmA, SwiftPerson.self)
checkCount(expected: 2, realmB, SwiftPerson.self)
checkCount(expected: 5, realmC, SwiftPerson.self)
XCTAssertEqual(realmA.objects(SwiftPerson.self).filter("firstName == %@", "Ringo").count, 1)
XCTAssertEqual(realmB.objects(SwiftPerson.self).filter("firstName == %@", "Ringo").count, 0)
} else {
// Add objects.
try realmA.write {
realmA.add(SwiftPerson(firstName: "Ringo", lastName: "Starr"))
realmA.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realmA.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
}
try realmB.write {
realmB.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realmB.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
}
try realmC.write {
realmC.add(SwiftPerson(firstName: "Ringo", lastName: "Starr"))
realmC.add(SwiftPerson(firstName: "John", lastName: "Lennon"))
realmC.add(SwiftPerson(firstName: "Paul", lastName: "McCartney"))
realmC.add(SwiftPerson(firstName: "George", lastName: "Harrison"))
realmC.add(SwiftPerson(firstName: "Pete", lastName: "Best"))
}
waitForUploads(for: realmA)
waitForUploads(for: realmB)
waitForUploads(for: realmC)
checkCount(expected: 3, realmA, SwiftPerson.self)
checkCount(expected: 2, realmB, SwiftPerson.self)
checkCount(expected: 5, realmC, SwiftPerson.self)
}
} catch {
XCTFail(error.localizedDescription)
}
}
func testConnectionState() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try immediatelyOpenRealm(partitionValue: #function, user: user)
let session = realm.syncSession!
func wait(forState desiredState: SyncSession.ConnectionState) {
let ex = expectation(description: "Wait for connection state: \(desiredState)")
let token = session.observe(\SyncSession.connectionState, options: .initial) { s, _ in
if s.connectionState == desiredState {
ex.fulfill()
}
}
waitForExpectations(timeout: 5.0)
token.invalidate()
}
wait(forState: .connected)
session.suspend()
wait(forState: .disconnected)
session.resume()
wait(forState: .connecting)
wait(forState: .connected)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
// MARK: - Client reset
func testClientReset() {
do {
let user = try logInUser(for: basicCredentials())
let realm = try openRealm(partitionValue: #function, user: user)
var theError: SyncError?
let ex = expectation(description: "Waiting for error handler to be called...")
app.syncManager.errorHandler = { (error, _) in
if let error = error as? SyncError {
theError = error
} else {
XCTFail("Error \(error) was not a sync error. Something is wrong.")
}
ex.fulfill()
}
user.simulateClientResetError(forSession: #function)
waitForExpectations(timeout: 10, handler: nil)
XCTAssertNotNil(theError)
guard let error = theError else { return }
XCTAssertTrue(error.code == SyncError.Code.clientResetError)
guard let resetInfo = error.clientResetInfo() else {
XCTAssertNotNil(error.clientResetInfo())
return
}
XCTAssertTrue(resetInfo.0.contains("mongodb-realm/\(self.appId)/recovered-realms/recovered_realm"))
XCTAssertNotNil(realm)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testClientResetManualInitiation() {
do {
let user = try logInUser(for: basicCredentials())
var theError: SyncError?
try autoreleasepool {
let realm = try openRealm(partitionValue: #function, user: user)
let ex = expectation(description: "Waiting for error handler to be called...")
app.syncManager.errorHandler = { (error, _) in
if let error = error as? SyncError {
theError = error
} else {
XCTFail("Error \(error) was not a sync error. Something is wrong.")
}
ex.fulfill()
}
user.simulateClientResetError(forSession: #function)
waitForExpectations(timeout: 10, handler: nil)
XCTAssertNotNil(theError)
XCTAssertNotNil(realm)
}
guard let error = theError else { return }
let (path, errorToken) = error.clientResetInfo()!
XCTAssertFalse(FileManager.default.fileExists(atPath: path))
SyncSession.immediatelyHandleError(errorToken, syncManager: self.app.syncManager)
XCTAssertTrue(FileManager.default.fileExists(atPath: path))
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
// MARK: - Progress notifiers
func testStreamingDownloadNotifier() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
populateRealm(user: user, partitionValue: #function)
return
}
var callCount = 0
var transferred = 0
var transferrable = 0
let realm = try immediatelyOpenRealm(partitionValue: #function, user: user)
guard let session = realm.syncSession else {
XCTFail("Session must not be nil")
return
}
let ex = expectation(description: "streaming-downloads-expectation")
var hasBeenFulfilled = false
let token = session.addProgressNotification(for: .download, mode: .reportIndefinitely) { p in
callCount += 1
XCTAssertGreaterThanOrEqual(p.transferredBytes, transferred)
XCTAssertGreaterThanOrEqual(p.transferrableBytes, transferrable)
transferred = p.transferredBytes
transferrable = p.transferrableBytes
if p.transferredBytes > 0 && p.isTransferComplete && !hasBeenFulfilled {
ex.fulfill()
hasBeenFulfilled = true
}
}
XCTAssertNotNil(token)
// Wait for the child process to upload all the data.
executeChild()
waitForExpectations(timeout: 60.0, handler: nil)
token!.invalidate()
XCTAssert(callCount > 1)
XCTAssert(transferred >= transferrable)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testStreamingUploadNotifier() {
do {
var transferred = 0
var transferrable = 0
let user = try logInUser(for: basicCredentials())
let config = user.configuration(testName: #function)
let realm = try openRealm(configuration: config)
let session = realm.syncSession
XCTAssertNotNil(session)
var ex = expectation(description: "initial upload")
let token = session!.addProgressNotification(for: .upload, mode: .reportIndefinitely) { p in
XCTAssert(p.transferredBytes >= transferred)
XCTAssert(p.transferrableBytes >= transferrable)
transferred = p.transferredBytes
transferrable = p.transferrableBytes
if p.transferredBytes > 0 && p.isTransferComplete {
ex.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
ex = expectation(description: "write transaction upload")
try realm.write {
for _ in 0..<SwiftSyncTestCase.bigObjectCount {
realm.add(SwiftHugeSyncObject.create())
}
}
waitForExpectations(timeout: 10.0, handler: nil)
token!.invalidate()
XCTAssert(transferred >= transferrable)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
// MARK: - Download Realm
func testDownloadRealm() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
populateRealm(user: user, partitionValue: #function)
return
}
// Wait for the child process to upload everything.
executeChild()
let ex = expectation(description: "download-realm")
let config = user.configuration(testName: #function)
let pathOnDisk = ObjectiveCSupport.convert(object: config).pathOnDisk
XCTAssertFalse(FileManager.default.fileExists(atPath: pathOnDisk))
Realm.asyncOpen(configuration: config) { result in
switch result {
case .success(let realm):
self.checkCount(expected: SwiftSyncTestCase.bigObjectCount, realm, SwiftHugeSyncObject.self)
case .failure(let error):
XCTFail("No realm on async open: \(error)")
}
ex.fulfill()
}
func fileSize(path: String) -> Int {
if let attr = try? FileManager.default.attributesOfItem(atPath: path) {
return attr[.size] as! Int
}
return 0
}
XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
waitForExpectations(timeout: 10.0, handler: nil)
XCTAssertGreaterThan(fileSize(path: pathOnDisk), 0)
XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testDownloadRealmToCustomPath() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
populateRealm(user: user, partitionValue: #function)
return
}
// Wait for the child process to upload everything.
executeChild()
let ex = expectation(description: "download-realm")
let customFileURL = realmURLForFile("copy")
var config = user.configuration(testName: #function)
config.fileURL = customFileURL
let pathOnDisk = ObjectiveCSupport.convert(object: config).pathOnDisk
XCTAssertEqual(pathOnDisk, customFileURL.path)
XCTAssertFalse(FileManager.default.fileExists(atPath: pathOnDisk))
Realm.asyncOpen(configuration: config) { result in
switch result {
case .success(let realm):
self.checkCount(expected: SwiftSyncTestCase.bigObjectCount, realm, SwiftHugeSyncObject.self)
case .failure(let error):
XCTFail("No realm on async open: \(error)")
}
ex.fulfill()
}
func fileSize(path: String) -> Int {
if let attr = try? FileManager.default.attributesOfItem(atPath: path) {
return attr[.size] as! Int
}
return 0
}
XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
waitForExpectations(timeout: 10.0, handler: nil)
XCTAssertGreaterThan(fileSize(path: pathOnDisk), 0)
XCTAssertFalse(RLMHasCachedRealmForPath(pathOnDisk))
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testCancelDownloadRealm() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
populateRealm(user: user, partitionValue: #function)
return
}
// Wait for the child process to upload everything.
executeChild()
// Use a serial queue for asyncOpen to ensure that the first one adds
// the completion block before the second one cancels it
RLMSetAsyncOpenQueue(DispatchQueue(label: "io.realm.asyncOpen"))
let ex = expectation(description: "async open")
let config = user.configuration(testName: #function)
Realm.asyncOpen(configuration: config) { result in
guard case .failure = result else {
XCTFail("No error on cancelled async open")
return ex.fulfill()
}
ex.fulfill()
}
let task = Realm.asyncOpen(configuration: config) { _ in
XCTFail("Cancelled completion handler was called")
}
task.cancel()
waitForExpectations(timeout: 10.0, handler: nil)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testAsyncOpenProgress() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
populateRealm(user: user, partitionValue: #function)
return
}
// Wait for the child process to upload everything.
executeChild()
let ex1 = expectation(description: "async open")
let ex2 = expectation(description: "download progress")
let config = user.configuration(testName: #function)
let task = Realm.asyncOpen(configuration: config) { result in
XCTAssertNotNil(try? result.get())
ex1.fulfill()
}
task.addProgressNotification { progress in
if progress.isTransferComplete {
ex2.fulfill()
}
}
waitForExpectations(timeout: 10.0, handler: nil)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
func testAsyncOpenTimeout() {
let proxy = TimeoutProxyServer(port: 5678, targetPort: 9090)
try! proxy.start()
let appId = try! RealmServer.shared.createApp()
let appConfig = AppConfiguration(baseURL: "http://localhost:5678",
transport: AsyncOpenConnectionTimeoutTransport(),
localAppName: nil, localAppVersion: nil)
let app = App(id: appId, configuration: appConfig)
let syncTimeoutOptions = SyncTimeoutOptions()
syncTimeoutOptions.connectTimeout = 2000
app.syncManager.timeoutOptions = syncTimeoutOptions
let user: User
do {
user = try logInUser(for: basicCredentials(app: app), app: app)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
return
}
var config = user.configuration(partitionValue: #function, cancelAsyncOpenOnNonFatalErrors: true)
config.objectTypes = []
// Two second timeout with a one second delay should work
autoreleasepool {
proxy.delay = 1.0
let ex = expectation(description: "async open")
Realm.asyncOpen(configuration: config) { result in
let realm = try? result.get()
XCTAssertNotNil(realm)
realm?.syncSession?.suspend()
ex.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// Two second timeout with a two second delay should fail
autoreleasepool {
proxy.delay = 3.0
let ex = expectation(description: "async open")
Realm.asyncOpen(configuration: config) { result in
guard case .failure(let error) = result else {
XCTFail("Did not fail: \(result)")
return
}
if let error = error as NSError? {
XCTAssertEqual(error.code, Int(ETIMEDOUT))
XCTAssertEqual(error.domain, NSPOSIXErrorDomain)
}
ex.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
proxy.stop()
}
func testAppCredentialSupport() {
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.facebook(accessToken: "accessToken")),
RLMCredentials(facebookToken: "accessToken"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.google(serverAuthCode: "serverAuthCode")),
RLMCredentials(googleAuthCode: "serverAuthCode"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.apple(idToken: "idToken")),
RLMCredentials(appleToken: "idToken"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.emailPassword(email: "email", password: "password")),
RLMCredentials(email: "email", password: "password"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.jwt(token: "token")),
RLMCredentials(jwt: "token"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.function(payload: ["dog": ["name": "fido"]])),
RLMCredentials(functionPayload: ["dog": ["name" as NSString: "fido" as NSString] as NSDictionary]))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.userAPIKey("key")),
RLMCredentials(userAPIKey: "key"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.serverAPIKey("key")),
RLMCredentials(serverAPIKey: "key"))
XCTAssertEqual(ObjectiveCSupport.convert(object: Credentials.anonymous),
RLMCredentials.anonymous())
}
// MARK: - Authentication
func testInvalidCredentials() {
do {
let email = "testInvalidCredentialsEmail"
let credentials = basicCredentials()
let user = try logInUser(for: credentials)
XCTAssertEqual(user.state, .loggedIn)
let credentials2 = Credentials.emailPassword(email: email, password: "NOT_A_VALID_PASSWORD")
let ex = expectation(description: "Should fail to log in the user")
self.app.login(credentials: credentials2) { result in
guard case .failure = result else {
XCTFail("Login should not have been successful")
return ex.fulfill()
}
ex.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
// MARK: - User-specific functionality
func testUserExpirationCallback() {
do {
let user = try logInUser(for: basicCredentials())
// Set a callback on the user
var blockCalled = false
let ex = expectation(description: "Error callback should fire upon receiving an error")
app.syncManager.errorHandler = { (error, _) in
XCTAssertNotNil(error)
blockCalled = true
ex.fulfill()
}
// Screw up the token on the user.
manuallySetAccessToken(for: user, value: badAccessToken())
manuallySetRefreshToken(for: user, value: badAccessToken())
// Try to open a Realm with the user; this will cause our errorHandler block defined above to be fired.
XCTAssertFalse(blockCalled)
_ = try immediatelyOpenRealm(partitionValue: "realm_id", user: user)
waitForExpectations(timeout: 10.0, handler: nil)
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
private func realmURLForFile(_ fileName: String) -> URL {
let testDir = RLMRealmPathForFile("mongodb-realm")
let directory = URL(fileURLWithPath: testDir, isDirectory: true)
return directory.appendingPathComponent(fileName, isDirectory: false)
}
// MARK: - App tests
let appName = "translate-utwuv"
private func appConfig() -> AppConfiguration {
return AppConfiguration(baseURL: "http://localhost:9090",
transport: nil,
localAppName: "auth-integration-tests",
localAppVersion: "20180301")
}
func testAppInit() {
let appWithNoConfig = App(id: appName)
XCTAssertEqual(appWithNoConfig.allUsers.count, 0)
let appWithConfig = App(id: appName, configuration: appConfig())
XCTAssertEqual(appWithConfig.allUsers.count, 0)
}
func testAppLogin() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
var syncUser: User?
app.login(credentials: Credentials.emailPassword(email: email, password: password)) { result in
switch result {
case .success(let user):
syncUser = user
case .failure:
XCTFail("Should login user")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
XCTAssertEqual(syncUser?.id, app.currentUser?.id)
XCTAssertEqual(app.allUsers.count, 1)
}
func testAppSwitchAndRemove() {
let email1 = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password1 = randomString(10)
let email2 = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password2 = randomString(10)
let registerUser1Ex = expectation(description: "Register user 1")
let registerUser2Ex = expectation(description: "Register user 2")
app.emailPasswordAuth.registerUser(email: email1, password: password1) { (error) in
XCTAssertNil(error)
registerUser1Ex.fulfill()
}
app.emailPasswordAuth.registerUser(email: email2, password: password2) { (error) in
XCTAssertNil(error)
registerUser2Ex.fulfill()
}
wait(for: [registerUser1Ex, registerUser2Ex], timeout: 4.0)
let login1Ex = expectation(description: "Login user 1")
let login2Ex = expectation(description: "Login user 2")
var syncUser1: User?
var syncUser2: User?
app.login(credentials: Credentials.emailPassword(email: email1, password: password1)) { result in
if case .success(let user) = result {
syncUser1 = user
} else {
XCTFail("Should login user 1")
}
login1Ex.fulfill()
}
wait(for: [login1Ex], timeout: 4.0)
app.login(credentials: Credentials.emailPassword(email: email2, password: password2)) { result in
if case .success(let user) = result {
syncUser2 = user
} else {
XCTFail("Should login user 2")
}
login2Ex.fulfill()
}
wait(for: [login2Ex], timeout: 4.0)
XCTAssertEqual(app.allUsers.count, 2)
XCTAssertEqual(syncUser2!.id, app.currentUser!.id)
app.switch(to: syncUser1!)
XCTAssertTrue(syncUser1!.id == app.currentUser?.id)
let removeEx = expectation(description: "Remove user 1")
syncUser1?.remove { (error) in
XCTAssertNil(error)
removeEx.fulfill()
}
wait(for: [removeEx], timeout: 4.0)
XCTAssertEqual(syncUser2!.id, app.currentUser!.id)
XCTAssertEqual(app.allUsers.count, 1)
}
func testAppLinkUser() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
var syncUser: User!
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: Credentials.anonymous) { result in
if case .success(let user) = result {
syncUser = user
} else {
XCTFail("Should login user")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
let linkEx = expectation(description: "Link user")
syncUser.linkUser(credentials: credentials) { result in
switch result {
case .success(let user):
syncUser = user
case .failure:
XCTFail("Should link user")
}
linkEx.fulfill()
}
wait(for: [linkEx], timeout: 4.0)
XCTAssertEqual(syncUser?.id, app.currentUser?.id)
XCTAssertEqual(syncUser?.identities.count, 2)
}
// MARK: - Provider Clients
func testEmailPasswordProviderClient() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let confirmUserEx = expectation(description: "Confirm user")
app.emailPasswordAuth.confirmUser("atoken", tokenId: "atokenid") { (error) in
XCTAssertNotNil(error)
confirmUserEx.fulfill()
}
wait(for: [confirmUserEx], timeout: 4.0)
let resendEmailEx = expectation(description: "Resend email confirmation")
app.emailPasswordAuth.resendConfirmationEmail("atoken") { (error) in
XCTAssertNotNil(error)
resendEmailEx.fulfill()
}
wait(for: [resendEmailEx], timeout: 4.0)
let retryCustomEx = expectation(description: "Retry custom confirmation")
app.emailPasswordAuth.retryCustomConfirmation(email) { (error) in
XCTAssertNotNil(error)
retryCustomEx.fulfill()
}
wait(for: [retryCustomEx], timeout: 4.0)
let resendResetPasswordEx = expectation(description: "Resend reset password email")
app.emailPasswordAuth.sendResetPasswordEmail("atoken") { (error) in
XCTAssertNotNil(error)
resendResetPasswordEx.fulfill()
}
wait(for: [resendResetPasswordEx], timeout: 4.0)
let resetPasswordEx = expectation(description: "Reset password email")
app.emailPasswordAuth.resetPassword(to: "password", token: "atoken", tokenId: "tokenId") { (error) in
XCTAssertNotNil(error)
resetPasswordEx.fulfill()
}
wait(for: [resetPasswordEx], timeout: 4.0)
let callResetFunctionEx = expectation(description: "Reset password function")
app.emailPasswordAuth.callResetPasswordFunction(email: email,
password: randomString(10),
args: [[:]]) { (error) in
XCTAssertNotNil(error)
callResetFunctionEx.fulfill()
}
wait(for: [callResetFunctionEx], timeout: 4.0)
}
func testUserAPIKeyProviderClient() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
let credentials = Credentials.emailPassword(email: email, password: password)
var syncUser: User?
app.login(credentials: credentials) { result in
switch result {
case .success(let user):
syncUser = user
case .failure:
XCTFail("Should link user")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
let createAPIKeyEx = expectation(description: "Create user api key")
var apiKey: UserAPIKey?
syncUser?.apiKeysAuth.createAPIKey(named: "my-api-key") { (key, error) in
XCTAssertNotNil(key)
XCTAssertNil(error)
apiKey = key
createAPIKeyEx.fulfill()
}
wait(for: [createAPIKeyEx], timeout: 4.0)
let fetchAPIKeyEx = expectation(description: "Fetch user api key")
syncUser?.apiKeysAuth.fetchAPIKey(apiKey!.objectId) { (key, error) in
XCTAssertNotNil(key)
XCTAssertNil(error)
fetchAPIKeyEx.fulfill()
}
wait(for: [fetchAPIKeyEx], timeout: 4.0)
let fetchAPIKeysEx = expectation(description: "Fetch user api keys")
syncUser?.apiKeysAuth.fetchAPIKeys(completion: { (keys, error) in
XCTAssertNotNil(keys)
XCTAssertEqual(keys!.count, 1)
XCTAssertNil(error)
fetchAPIKeysEx.fulfill()
})
wait(for: [fetchAPIKeysEx], timeout: 4.0)
let disableKeyEx = expectation(description: "Disable API key")
syncUser?.apiKeysAuth.disableAPIKey(apiKey!.objectId) { (error) in
XCTAssertNil(error)
disableKeyEx.fulfill()
}
wait(for: [disableKeyEx], timeout: 4.0)
let enableKeyEx = expectation(description: "Enable API key")
syncUser?.apiKeysAuth.enableAPIKey(apiKey!.objectId) { (error) in
XCTAssertNil(error)
enableKeyEx.fulfill()
}
wait(for: [enableKeyEx], timeout: 4.0)
let deleteKeyEx = expectation(description: "Delete API key")
syncUser?.apiKeysAuth.deleteAPIKey(apiKey!.objectId) { (error) in
XCTAssertNil(error)
deleteKeyEx.fulfill()
}
wait(for: [deleteKeyEx], timeout: 4.0)
}
func testApiKeyAuthResultCompletion() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
let credentials = Credentials.emailPassword(email: email, password: password)
var syncUser: User?
app.login(credentials: credentials) { result in
switch result {
case .success(let user):
syncUser = user
case .failure:
XCTFail("Should login")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
let createAPIKeyEx = expectation(description: "Create user api key")
var apiKey: UserAPIKey?
syncUser?.apiKeysAuth.createAPIKey(named: "my-api-key") { result in
switch result {
case .success(let userAPIKey):
apiKey = userAPIKey
case .failure:
XCTFail("Should create api key")
}
createAPIKeyEx.fulfill()
}
wait(for: [createAPIKeyEx], timeout: 4.0)
let fetchAPIKeyEx = expectation(description: "Fetch user api key")
syncUser?.apiKeysAuth.fetchAPIKey(apiKey!.objectId as! ObjectId, { result in
if case .failure = result {
XCTFail("Should fetch api key")
}
fetchAPIKeyEx.fulfill()
})
wait(for: [fetchAPIKeyEx], timeout: 4.0)
let fetchAPIKeysEx = expectation(description: "Fetch user api keys")
syncUser?.apiKeysAuth.fetchAPIKeys { result in
switch result {
case .success(let userAPIKeys):
XCTAssertEqual(userAPIKeys.count, 1)
case .failure:
XCTFail("Should fetch api key")
}
fetchAPIKeysEx.fulfill()
}
wait(for: [fetchAPIKeysEx], timeout: 4.0)
}
func testCallFunction() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: credentials) { result in
switch result {
case .success(let user):
XCTAssertNotNil(user)
case .failure:
XCTFail("Should link user")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
let callFunctionEx = expectation(description: "Call function")
app.currentUser?.functions.sum([1, 2, 3, 4, 5]) { bson, error in
guard let bson = bson else {
XCTFail(error!.localizedDescription)
return
}
guard case let .int32(sum) = bson else {
XCTFail(error!.localizedDescription)
return
}
XCTAssertNil(error)
XCTAssertEqual(sum, 15)
callFunctionEx.fulfill()
}
wait(for: [callFunctionEx], timeout: 4.0)
}
func testPushRegistration() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginExpectation = expectation(description: "Login user")
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: credentials) { result in
if case .failure = result {
XCTFail("Should link user")
}
loginExpectation.fulfill()
}
wait(for: [loginExpectation], timeout: 4.0)
let registerDeviceExpectation = expectation(description: "Register Device")
let client = app.pushClient(serviceName: "gcm")
client.registerDevice(token: "some-token", user: app.currentUser!) { error in
XCTAssertNil(error)
registerDeviceExpectation.fulfill()
}
wait(for: [registerDeviceExpectation], timeout: 4.0)
let dergisterDeviceExpectation = expectation(description: "Deregister Device")
client.deregisterDevice(user: app.currentUser!, completion: { error in
XCTAssertNil(error)
dergisterDeviceExpectation.fulfill()
})
wait(for: [dergisterDeviceExpectation], timeout: 4.0)
}
func testCustomUserData() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let registerUserEx = expectation(description: "Register user")
app.emailPasswordAuth.registerUser(email: email, password: password) { (error) in
XCTAssertNil(error)
registerUserEx.fulfill()
}
wait(for: [registerUserEx], timeout: 4.0)
let loginEx = expectation(description: "Login user")
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: credentials) { result in
switch result {
case .success(let user):
XCTAssertNotNil(user)
case .failure:
XCTFail("Should link user")
}
loginEx.fulfill()
}
wait(for: [loginEx], timeout: 4.0)
let userDataEx = expectation(description: "Update user data")
app.currentUser?.functions.updateUserData([["favourite_colour": "green", "apples": 10]]) { _, error in
XCTAssertNil(error)
userDataEx.fulfill()
}
wait(for: [userDataEx], timeout: 4.0)
let refreshDataEx = expectation(description: "Refresh user data")
app.currentUser?.refreshCustomData { customData, error in
XCTAssertNil(error)
XCTAssertNotNil(customData)
XCTAssertEqual(customData?["apples"] as! Int, 10)
XCTAssertEqual(customData?["favourite_colour"] as! String, "green")
refreshDataEx.fulfill()
}
wait(for: [refreshDataEx], timeout: 4.0)
XCTAssertEqual(app.currentUser?.customData["favourite_colour"], .string("green"))
XCTAssertEqual(app.currentUser?.customData["apples"], .int64(10))
}
}
// MARK: - Mongo Client
@objc(SwiftMongoClientTests)
class SwiftMongoClientTests: SwiftSyncTestCase {
override func tearDown() {
_ = setupMongoCollection()
super.tearDown()
}
func testMongoClient() {
let user = try! logInUser(for: Credentials.anonymous)
let mongoClient = user.mongoClient("mongodb1")
XCTAssertEqual(mongoClient.name, "mongodb1")
let database = mongoClient.database(named: "test_data")
XCTAssertEqual(database.name, "test_data")
let collection = database.collection(withName: "Dog")
XCTAssertEqual(collection.name, "Dog")
}
func removeAllFromCollection(_ collection: MongoCollection) {
let deleteEx = expectation(description: "Delete all from Mongo collection")
collection.deleteManyDocuments(filter: [:]) { result in
if case .failure = result {
XCTFail("Should delete")
}
deleteEx.fulfill()
}
wait(for: [deleteEx], timeout: 4.0)
}
func setupMongoCollection() -> MongoCollection {
let user = try! logInUser(for: basicCredentials())
let mongoClient = user.mongoClient("mongodb1")
let database = mongoClient.database(named: "test_data")
let collection = database.collection(withName: "Dog")
removeAllFromCollection(collection)
return collection
}
func testMongoOptions() {
let findOptions = FindOptions(1, nil, nil)
let findOptions1 = FindOptions(5, ["name": 1], ["_id": 1])
let findOptions2 = FindOptions(5, ["names": ["fido", "bob", "rex"]], ["_id": 1])
XCTAssertEqual(findOptions.limit, 1)
XCTAssertEqual(findOptions.projection, nil)
XCTAssertEqual(findOptions.sort, nil)
XCTAssertEqual(findOptions1.limit, 5)
XCTAssertEqual(findOptions1.projection, ["name": 1])
XCTAssertEqual(findOptions1.sort, ["_id": 1])
XCTAssertEqual(findOptions2.projection, ["names": ["fido", "bob", "rex"]])
let findModifyOptions = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
XCTAssertEqual(findModifyOptions.projection, ["name": 1])
XCTAssertEqual(findModifyOptions.sort, ["_id": 1])
XCTAssertTrue(findModifyOptions.upsert)
XCTAssertTrue(findModifyOptions.shouldReturnNewDocument)
}
func testMongoInsertResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "tibetan mastiff"]
let insertOneEx1 = expectation(description: "Insert one document")
collection.insertOne(document) { result in
if case .failure = result {
XCTFail("Should insert")
}
insertOneEx1.fulfill()
}
wait(for: [insertOneEx1], timeout: 4.0)
let insertManyEx1 = expectation(description: "Insert many documents")
collection.insertMany([document, document2]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 2)
case .failure:
XCTFail("Should insert")
}
insertManyEx1.fulfill()
}
wait(for: [insertManyEx1], timeout: 4.0)
let findEx1 = expectation(description: "Find documents")
collection.find(filter: [:]) { result in
switch result {
case .success(let documents):
XCTAssertEqual(documents.count, 3)
XCTAssertEqual(documents[0]["name"]??.stringValue, "fido")
XCTAssertEqual(documents[1]["name"]??.stringValue, "fido")
XCTAssertEqual(documents[2]["name"]??.stringValue, "rex")
case .failure:
XCTFail("Should find")
}
findEx1.fulfill()
}
wait(for: [findEx1], timeout: 4.0)
}
func testMongoFindResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "tibetan mastiff"]
let document3: Document = ["name": "rex", "breed": "tibetan mastiff", "coat": ["fawn", "brown", "white"]]
let findOptions = FindOptions(1, nil, nil)
let insertManyEx1 = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 3)
case .failure:
XCTFail("Should insert")
}
insertManyEx1.fulfill()
}
wait(for: [insertManyEx1], timeout: 4.0)
let findEx1 = expectation(description: "Find documents")
collection.find(filter: [:]) { result in
switch result {
case .success(let documents):
XCTAssertEqual(documents.count, 3)
XCTAssertEqual(documents[0]["name"]??.stringValue, "fido")
XCTAssertEqual(documents[1]["name"]??.stringValue, "rex")
XCTAssertEqual(documents[2]["name"]??.stringValue, "rex")
case .failure:
XCTFail("Should find")
}
findEx1.fulfill()
}
wait(for: [findEx1], timeout: 4.0)
let findEx2 = expectation(description: "Find documents")
collection.find(filter: [:], options: findOptions) { result in
switch result {
case .success(let document):
XCTAssertEqual(document.count, 1)
XCTAssertEqual(document[0]["name"]??.stringValue, "fido")
case .failure:
XCTFail("Should find")
}
findEx2.fulfill()
}
wait(for: [findEx2], timeout: 4.0)
let findEx3 = expectation(description: "Find documents")
collection.find(filter: document3, options: findOptions) { result in
switch result {
case .success(let documents):
XCTAssertEqual(documents.count, 1)
case .failure:
XCTFail("Should find")
}
findEx3.fulfill()
}
wait(for: [findEx3], timeout: 4.0)
let findOneEx1 = expectation(description: "Find one document")
collection.findOneDocument(filter: document) { result in
switch result {
case .success(let document):
XCTAssertNotNil(document)
case .failure:
XCTFail("Should find")
}
findOneEx1.fulfill()
}
wait(for: [findOneEx1], timeout: 4.0)
let findOneEx2 = expectation(description: "Find one document")
collection.findOneDocument(filter: document, options: findOptions) { result in
switch result {
case .success(let document):
XCTAssertNotNil(document)
case .failure:
XCTFail("Should find")
}
findOneEx2.fulfill()
}
wait(for: [findOneEx2], timeout: 4.0)
let findOneEx3 = expectation(description: "Find one document")
collection.findOneDocument(filter: ["name": "tim"]) { result in
switch result {
case .success(let document):
XCTAssertNil(document)
case .failure:
XCTFail("Should find")
}
findOneEx3.fulfill()
}
wait(for: [findOneEx3], timeout: 4.0)
}
func testMongoFindAndReplaceResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let findOneReplaceEx1 = expectation(description: "Find one document and replace")
collection.findOneAndReplace(filter: document, replacement: document2) { result in
switch result {
case .success(let document):
// no doc found, both should be nil
XCTAssertNil(document)
case .failure:
XCTFail("Should find")
}
findOneReplaceEx1.fulfill()
}
wait(for: [findOneReplaceEx1], timeout: 4.0)
let options1 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
let findOneReplaceEx2 = expectation(description: "Find one document and replace")
collection.findOneAndReplace(filter: document2, replacement: document3, options: options1) { result in
switch result {
case .success(let document):
XCTAssertEqual(document!["name"]??.stringValue, "john")
case .failure:
XCTFail("Should find")
}
findOneReplaceEx2.fulfill()
}
wait(for: [findOneReplaceEx2], timeout: 4.0)
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, false)
let findOneReplaceEx3 = expectation(description: "Find one document and replace")
collection.findOneAndReplace(filter: document, replacement: document2, options: options2) { result in
switch result {
case .success(let document):
// upsert but do not return document
XCTAssertNil(document)
case .failure:
XCTFail("Should find")
}
findOneReplaceEx3.fulfill()
}
wait(for: [findOneReplaceEx3], timeout: 4.0)
}
func testMongoFindAndUpdateResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let findOneUpdateEx1 = expectation(description: "Find one document and update")
collection.findOneAndUpdate(filter: document, update: document2) { result in
switch result {
case .success(let document):
// no doc found, both should be nil
XCTAssertNil(document)
case .failure:
XCTFail("Should find")
}
findOneUpdateEx1.fulfill()
}
wait(for: [findOneUpdateEx1], timeout: 4.0)
let options1 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
let findOneUpdateEx2 = expectation(description: "Find one document and update")
collection.findOneAndUpdate(filter: document2, update: document3, options: options1) { result in
switch result {
case .success(let document):
XCTAssertNotNil(document)
XCTAssertEqual(document!["name"]??.stringValue, "john")
case .failure:
XCTFail("Should find")
}
findOneUpdateEx2.fulfill()
}
wait(for: [findOneUpdateEx2], timeout: 4.0)
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
let findOneUpdateEx3 = expectation(description: "Find one document and update")
collection.findOneAndUpdate(filter: document, update: document2, options: options2) { result in
switch result {
case .success(let document):
XCTAssertNotNil(document)
XCTAssertEqual(document!["name"]??.stringValue, "rex")
case .failure:
XCTFail("Should find")
}
findOneUpdateEx3.fulfill()
}
wait(for: [findOneUpdateEx3], timeout: 4.0)
}
func testMongoFindAndDeleteResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 2)
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let findOneDeleteEx1 = expectation(description: "Find one document and delete")
collection.findOneAndDelete(filter: document) { result in
switch result {
case .success(let document):
// Document does not exist, but should not return an error because of that
XCTAssertNotNil(document)
case .failure:
XCTFail("Should find")
}
findOneDeleteEx1.fulfill()
}
wait(for: [findOneDeleteEx1], timeout: 4.0)
let options1 = FindOneAndModifyOptions(["name": 1], ["_id": 1], false, false)
let findOneDeleteEx2 = expectation(description: "Find one document and delete")
collection.findOneAndDelete(filter: document, options: options1) { result in
switch result {
case .success(let document):
XCTAssertNotNil(document)
XCTAssertEqual(document!["name"]??.stringValue, "fido")
findOneDeleteEx2.fulfill()
case .failure:
XCTFail("Should find")
}
}
wait(for: [findOneDeleteEx2], timeout: 4.0)
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1])
let findOneDeleteEx3 = expectation(description: "Find one document and delete")
collection.findOneAndDelete(filter: document, options: options2) { result in
switch result {
case .success(let document):
// Document does not exist, but should not return an error because of that
XCTAssertNil(document)
findOneDeleteEx3.fulfill()
case .failure:
XCTFail("Should find")
}
}
wait(for: [findOneDeleteEx3], timeout: 4.0)
let findEx = expectation(description: "Find documents")
collection.find(filter: [:]) { result in
switch result {
case .success(let documents):
XCTAssertEqual(documents.count, 0)
case .failure:
XCTFail("Should find")
}
findEx.fulfill()
}
wait(for: [findEx], timeout: 4.0)
}
func testMongoUpdateOneResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
let document5: Document = ["name": "bill", "breed": "great dane"]
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 4)
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let updateEx1 = expectation(description: "Update one document")
collection.updateOneDocument(filter: document, update: document2) { result in
switch result {
case .success(let updateResult):
XCTAssertEqual(updateResult.matchedCount, 1)
XCTAssertEqual(updateResult.modifiedCount, 1)
XCTAssertNil(updateResult.objectId)
case .failure:
XCTFail("Should update")
}
updateEx1.fulfill()
}
wait(for: [updateEx1], timeout: 4.0)
let updateEx2 = expectation(description: "Update one document")
collection.updateOneDocument(filter: document5, update: document2, upsert: true) { result in
switch result {
case .success(let updateResult):
XCTAssertEqual(updateResult.matchedCount, 0)
XCTAssertEqual(updateResult.modifiedCount, 0)
XCTAssertNotNil(updateResult.objectId)
case .failure:
XCTFail("Should update")
}
updateEx2.fulfill()
}
wait(for: [updateEx2], timeout: 4.0)
}
func testMongoUpdateManyResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
let document5: Document = ["name": "bill", "breed": "great dane"]
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 4)
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let updateEx1 = expectation(description: "Update one document")
collection.updateManyDocuments(filter: document, update: document2) { result in
switch result {
case .success(let updateResult):
XCTAssertEqual(updateResult.matchedCount, 1)
XCTAssertEqual(updateResult.modifiedCount, 1)
XCTAssertNil(updateResult.objectId)
case .failure:
XCTFail("Should update")
}
updateEx1.fulfill()
}
wait(for: [updateEx1], timeout: 4.0)
let updateEx2 = expectation(description: "Update one document")
collection.updateManyDocuments(filter: document5, update: document2, upsert: true) { result in
switch result {
case .success(let updateResult):
XCTAssertEqual(updateResult.matchedCount, 0)
XCTAssertEqual(updateResult.modifiedCount, 0)
XCTAssertNotNil(updateResult.objectId)
case .failure:
XCTFail("Should update")
}
updateEx2.fulfill()
}
wait(for: [updateEx2], timeout: 4.0)
}
func testMongoDeleteOneResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let deleteEx1 = expectation(description: "Delete 0 documents")
collection.deleteOneDocument(filter: document) { result in
switch result {
case .success(let count):
XCTAssertEqual(count, 0)
case .failure:
XCTFail("Should delete")
}
deleteEx1.fulfill()
}
wait(for: [deleteEx1], timeout: 4.0)
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 2)
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let deleteEx2 = expectation(description: "Delete one document")
collection.deleteOneDocument(filter: document) { result in
switch result {
case .success(let count):
XCTAssertEqual(count, 1)
case .failure:
XCTFail("Should delete")
}
deleteEx2.fulfill()
}
wait(for: [deleteEx2], timeout: 4.0)
}
func testMongoDeleteManyResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let deleteEx1 = expectation(description: "Delete 0 documents")
collection.deleteManyDocuments(filter: document) { result in
switch result {
case .success(let count):
XCTAssertEqual(count, 0)
case .failure:
XCTFail("Should delete")
}
deleteEx1.fulfill()
}
wait(for: [deleteEx1], timeout: 4.0)
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 2)
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let deleteEx2 = expectation(description: "Delete one document")
collection.deleteManyDocuments(filter: ["breed": "cane corso"]) { result in
switch result {
case .success(let count):
XCTAssertEqual(count, 2)
case .failure:
XCTFail("Should selete")
}
deleteEx2.fulfill()
}
wait(for: [deleteEx2], timeout: 4.0)
}
func testMongoCountAndAggregateResultCompletion() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let insertManyEx1 = expectation(description: "Insert many documents")
collection.insertMany([document]) { result in
switch result {
case .success(let objectIds):
XCTAssertEqual(objectIds.count, 1)
case .failure(let error):
XCTFail("Insert failed: \(error)")
}
insertManyEx1.fulfill()
}
wait(for: [insertManyEx1], timeout: 4.0)
collection.aggregate(pipeline: [["$match": ["name": "fido"]], ["$group": ["_id": "$name"]]]) { result in
switch result {
case .success(let documents):
XCTAssertNotNil(documents)
case .failure(let error):
XCTFail("Aggregate failed: \(error)")
}
}
let countEx1 = expectation(description: "Count documents")
collection.count(filter: document) { result in
switch result {
case .success(let count):
XCTAssertNotNil(count)
case .failure(let error):
XCTFail("Count failed: \(error)")
}
countEx1.fulfill()
}
wait(for: [countEx1], timeout: 4.0)
let countEx2 = expectation(description: "Count documents")
collection.count(filter: document, limit: 1) { result in
switch result {
case .success(let count):
XCTAssertEqual(count, 1)
case .failure(let error):
XCTFail("Count failed: \(error)")
}
countEx2.fulfill()
}
wait(for: [countEx2], timeout: 4.0)
}
func testWatch() {
performWatchTest(nil)
}
func testWatchAsync() {
let queue = DispatchQueue.init(label: "io.realm.watchQueue", attributes: .concurrent)
performWatchTest(queue)
}
func performWatchTest(_ queue: DispatchQueue?) {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
var watchEx = expectation(description: "Watch 3 document events")
let watchTestUtility = WatchTestUtility(targetEventCount: 3, expectation: &watchEx)
let changeStream: ChangeStream?
if let queue = queue {
changeStream = collection.watch(delegate: watchTestUtility, queue: queue)
} else {
changeStream = collection.watch(delegate: watchTestUtility)
}
DispatchQueue.global().async {
watchTestUtility.isOpenSemaphore.wait()
for _ in 0..<3 {
collection.insertOne(document) { result in
if case .failure = result {
XCTFail("Should insert")
}
}
watchTestUtility.semaphore.wait()
}
changeStream?.close()
}
wait(for: [watchEx], timeout: 60.0)
}
func testWatchWithMatchFilter() {
performWatchWithMatchFilterTest(nil)
}
func testWatchWithMatchFilterAsync() {
let queue = DispatchQueue.init(label: "io.realm.watchQueue", attributes: .concurrent)
performWatchWithMatchFilterTest(queue)
}
func performWatchWithMatchFilterTest(_ queue: DispatchQueue?) {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
var objectIds = [ObjectId]()
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objIds):
XCTAssertEqual(objIds.count, 4)
objectIds = objIds.map { $0.objectIdValue! }
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
var watchEx = expectation(description: "Watch 3 document events")
let watchTestUtility = WatchTestUtility(targetEventCount: 3, matchingObjectId: objectIds.first!, expectation: &watchEx)
let changeStream: ChangeStream?
if let queue = queue {
changeStream = collection.watch(matchFilter: ["fullDocument._id": AnyBSON.objectId(objectIds[0])],
delegate: watchTestUtility,
queue: queue)
} else {
changeStream = collection.watch(matchFilter: ["fullDocument._id": AnyBSON.objectId(objectIds[0])],
delegate: watchTestUtility)
}
DispatchQueue.global().async {
watchTestUtility.isOpenSemaphore.wait()
for i in 0..<3 {
let name: AnyBSON = .string("fido-\(i)")
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[0])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[1])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
watchTestUtility.semaphore.wait()
}
changeStream?.close()
}
wait(for: [watchEx], timeout: 60.0)
}
func testWatchWithFilterIds() {
performWatchWithFilterIdsTest(nil)
}
func testWatchWithFilterIdsAsync() {
let queue = DispatchQueue.init(label: "io.realm.watchQueue", attributes: .concurrent)
performWatchWithFilterIdsTest(queue)
}
func performWatchWithFilterIdsTest(_ queue: DispatchQueue?) {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
var objectIds = [ObjectId]()
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objIds):
XCTAssertEqual(objIds.count, 4)
objectIds = objIds.map { $0.objectIdValue! }
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
var watchEx = expectation(description: "Watch 3 document events")
let watchTestUtility = WatchTestUtility(targetEventCount: 3,
matchingObjectId: objectIds.first!,
expectation: &watchEx)
let changeStream: ChangeStream?
if let queue = queue {
changeStream = collection.watch(filterIds: [objectIds[0]], delegate: watchTestUtility, queue: queue)
} else {
changeStream = collection.watch(filterIds: [objectIds[0]], delegate: watchTestUtility)
}
DispatchQueue.global().async {
watchTestUtility.isOpenSemaphore.wait()
for i in 0..<3 {
let name: AnyBSON = .string("fido-\(i)")
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[0])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[1])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
watchTestUtility.semaphore.wait()
}
changeStream?.close()
}
wait(for: [watchEx], timeout: 60.0)
}
func testWatchMultipleFilterStreams() {
performMultipleWatchStreamsTest(nil)
}
func testWatchMultipleFilterStreamsAsync() {
let queue = DispatchQueue.init(label: "io.realm.watchQueue", attributes: .concurrent)
performMultipleWatchStreamsTest(queue)
}
func performMultipleWatchStreamsTest(_ queue: DispatchQueue?) {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
var objectIds = [ObjectId]()
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objIds):
XCTAssertEqual(objIds.count, 4)
objectIds = objIds.map { $0.objectIdValue! }
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
var watchEx = expectation(description: "Watch 5 document events")
watchEx.expectedFulfillmentCount = 2
let watchTestUtility1 = WatchTestUtility(targetEventCount: 3,
matchingObjectId: objectIds[0],
expectation: &watchEx)
let watchTestUtility2 = WatchTestUtility(targetEventCount: 3,
matchingObjectId: objectIds[1],
expectation: &watchEx)
let changeStream1: ChangeStream?
let changeStream2: ChangeStream?
if let queue = queue {
changeStream1 = collection.watch(filterIds: [objectIds[0]], delegate: watchTestUtility1, queue: queue)
changeStream2 = collection.watch(filterIds: [objectIds[1]], delegate: watchTestUtility2, queue: queue)
} else {
changeStream1 = collection.watch(filterIds: [objectIds[0]], delegate: watchTestUtility1)
changeStream2 = collection.watch(filterIds: [objectIds[1]], delegate: watchTestUtility2)
}
let teardownEx = expectation(description: "All changes complete")
DispatchQueue.global().async {
watchTestUtility1.isOpenSemaphore.wait()
watchTestUtility2.isOpenSemaphore.wait()
for i in 0..<3 {
let name: AnyBSON = .string("fido-\(i)")
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[0])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[1])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
watchTestUtility1.semaphore.wait()
watchTestUtility2.semaphore.wait()
}
changeStream1?.close()
changeStream2?.close()
teardownEx.fulfill()
}
wait(for: [watchEx, teardownEx], timeout: 60.0)
}
func testShouldNotDeleteOnMigrationWithSync() {
let user = try! logInUser(for: basicCredentials())
var configuration = user.configuration(testName: appId)
assertThrows(configuration.deleteRealmIfMigrationNeeded = true,
reason: "Cannot set 'deleteRealmIfMigrationNeeded' when sync is enabled ('syncConfig' is set).")
var localConfiguration = Realm.Configuration.defaultConfiguration
assertSucceeds {
localConfiguration.deleteRealmIfMigrationNeeded = true
}
}
}
class AnyRealmValueSyncTests: SwiftSyncTestCase {
/// The purpose of this test is to confirm that when an Object is set on a mixed Column and an old
/// version of an app does not have that Realm Object / Schema we can still access that object via
/// `AnyRealmValue.dynamicSchema`.
func testMissingSchema() {
do {
let user = try logInUser(for: basicCredentials())
if !isParent {
// Imagine this is v2 of an app with 3 classes
var config = user.configuration(partitionValue: #function)
config.objectTypes = [SwiftPerson.self, SwiftAnyRealmValueObject.self, SwiftMissingObject.self]
let realm = try openRealm(configuration: config)
try realm.write {
let so1 = SwiftPerson()
so1.firstName = "Rick"
so1.lastName = "Sanchez"
let so2 = SwiftPerson()
so2.firstName = "Squidward"
so2.lastName = "Tentacles"
let syncObj2 = SwiftMissingObject()
syncObj2.objectCol = so1
syncObj2.anyCol.value = .object(so1)
let syncObj = SwiftMissingObject()
syncObj.objectCol = so1
syncObj.anyCol.value = .object(syncObj2)
let obj = SwiftAnyRealmValueObject()
obj.anyCol.value = .object(syncObj)
obj.otherAnyCol.value = .object(so2)
realm.add(obj)
}
waitForUploads(for: realm)
return
}
executeChild()
// Imagine this is v1 of an app with just 2 classes, `SwiftMissingObject`
// did not exist when this version was shipped,
// but v2 managed to sync `SwiftMissingObject` to this Realm.
var config = user.configuration(partitionValue: #function)
config.objectTypes = [SwiftAnyRealmValueObject.self, SwiftPerson.self]
let realm = try openRealm(configuration: config)
let obj = realm.objects(SwiftAnyRealmValueObject.self).first
// SwiftMissingObject.anyCol -> SwiftMissingObject.anyCol -> SwiftPerson.firstName
let anyCol = ((obj!.anyCol.value.dynamicObject?.anyCol as? Object)?["anyCol"] as? Object)
XCTAssertEqual((anyCol?["firstName"] as? String), "Rick")
try! realm.write {
anyCol?["firstName"] = "Morty"
}
XCTAssertEqual((anyCol?["firstName"] as? String), "Morty")
let objectCol = (obj!.anyCol.value.dynamicObject?.objectCol as? Object)
XCTAssertEqual((objectCol?["firstName"] as? String), "Morty")
} catch {
XCTFail("Got an error: \(error) (process: \(isParent ? "parent" : "child"))")
}
}
}
// XCTest doesn't care about the @available on the class and will try to run
// the tests even on older versions. Putting this check inside `defaultTestSuite`
// results in a warning about it being redundant due to the enclosing check, so
// it needs to be out of line.
func hasCombine() -> Bool {
if #available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *) {
return true
}
return false
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher {
func expectValue(_ testCase: XCTestCase, _ expectation: XCTestExpectation, receiveValue: ((Self.Output) -> Void)? = nil) -> AnyCancellable {
return self.sink(receiveCompletion: { result in
if case .failure(let error) = result {
XCTFail("Unexpected failure: \(error)")
}
}, receiveValue: { value in
receiveValue?(value)
expectation.fulfill()
})
}
func await(_ testCase: XCTestCase, timeout: TimeInterval = 4.0, receiveValue: ((Self.Output) -> Void)? = nil) {
let expectation = testCase.expectation(description: "Async combine pipeline")
let cancellable = self.expectValue(testCase, expectation, receiveValue: receiveValue)
testCase.wait(for: [expectation], timeout: timeout)
cancellable.cancel()
}
func awaitFailure(_ testCase: XCTestCase, timeout: TimeInterval = 4.0) {
let expectation = testCase.expectation(description: "Async combine pipeline should fail")
let cancellable = self.sink(receiveCompletion: { result in
if case .failure = result {
expectation.fulfill()
}
}, receiveValue: { value in
XCTFail("Should have failed but got \(value)")
})
testCase.wait(for: [expectation], timeout: timeout)
cancellable.cancel()
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
@objc(CombineObjectServerTests)
class CombineObjectServerTests: SwiftSyncTestCase {
override class var defaultTestSuite: XCTestSuite {
if hasCombine() {
return super.defaultTestSuite
}
return XCTestSuite(name: "\(type(of: self))")
}
var subscriptions: Set<AnyCancellable> = []
override func tearDown() {
subscriptions.forEach { $0.cancel() }
subscriptions = []
super.tearDown()
}
func setupMongoCollection() -> MongoCollection {
let user = try! logInUser(for: basicCredentials())
let mongoClient = user.mongoClient("mongodb1")
let database = mongoClient.database(named: "test_data")
let collection = database.collection(withName: "Dog")
removeAllFromCollection(collection)
return collection
}
func removeAllFromCollection(_ collection: MongoCollection) {
collection.deleteManyDocuments(filter: [:]).await(self)
}
// swiftlint:disable multiple_closures_with_trailing_closure
func testWatchCombine() {
let sema = DispatchSemaphore(value: 0)
let sema2 = DispatchSemaphore(value: 0)
let openSema = DispatchSemaphore(value: 0)
let openSema2 = DispatchSemaphore(value: 0)
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let watchEx1 = expectation(description: "Watch 3 document events")
watchEx1.expectedFulfillmentCount = 3
let watchEx2 = expectation(description: "Watch 3 document events")
watchEx2.expectedFulfillmentCount = 3
collection.watch()
.onOpen {
openSema.signal()
}
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.global())
.sink(receiveCompletion: { _ in }) { _ in
watchEx1.fulfill()
XCTAssertFalse(Thread.isMainThread)
sema.signal()
}.store(in: &subscriptions)
collection.watch()
.onOpen {
openSema2.signal()
}
.subscribe(on: DispatchQueue.main)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { _ in }) { _ in
watchEx2.fulfill()
XCTAssertTrue(Thread.isMainThread)
sema2.signal()
}.store(in: &subscriptions)
DispatchQueue.global().async {
openSema.wait()
openSema2.wait()
for _ in 0..<3 {
collection.insertOne(document) { result in
if case .failure(let error) = result {
XCTFail("Failed to insert: \(error)")
}
}
sema.wait()
sema2.wait()
}
DispatchQueue.main.async {
self.subscriptions.forEach { $0.cancel() }
}
}
wait(for: [watchEx1, watchEx2], timeout: 60.0)
}
func testWatchCombineWithFilterIds() {
let sema1 = DispatchSemaphore(value: 0)
let sema2 = DispatchSemaphore(value: 0)
let openSema1 = DispatchSemaphore(value: 0)
let openSema2 = DispatchSemaphore(value: 0)
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
var objectIds = [ObjectId]()
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objIds):
XCTAssertEqual(objIds.count, 4)
objectIds = objIds.map { $0.objectIdValue! }
case .failure:
XCTFail("Should insert")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let watchEx1 = expectation(description: "Watch 3 document events")
watchEx1.expectedFulfillmentCount = 3
let watchEx2 = expectation(description: "Watch 3 document events")
watchEx2.expectedFulfillmentCount = 3
collection.watch(filterIds: [objectIds[0]])
.onOpen {
openSema1.signal()
}
.subscribe(on: DispatchQueue.main)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { _ in }) { changeEvent in
XCTAssertTrue(Thread.isMainThread)
guard let doc = changeEvent.documentValue else {
return
}
let objectId = doc["fullDocument"]??.documentValue!["_id"]??.objectIdValue!
if objectId == objectIds[0] {
watchEx1.fulfill()
sema1.signal()
}
}.store(in: &subscriptions)
collection.watch(filterIds: [objectIds[1]])
.onOpen {
openSema2.signal()
}
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.global())
.sink(receiveCompletion: { _ in }) { (changeEvent) in
XCTAssertFalse(Thread.isMainThread)
guard let doc = changeEvent.documentValue else {
return
}
let objectId = doc["fullDocument"]??.documentValue!["_id"]??.objectIdValue!
if objectId == objectIds[1] {
watchEx2.fulfill()
sema2.signal()
}
}.store(in: &subscriptions)
DispatchQueue.global().async {
openSema1.wait()
openSema2.wait()
for i in 0..<3 {
let name: AnyBSON = .string("fido-\(i)")
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[0])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure(let error) = result {
XCTFail("Failed to update: \(error)")
}
}
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[1])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure(let error) = result {
XCTFail("Failed to update: \(error)")
}
}
sema1.wait()
sema2.wait()
}
DispatchQueue.main.async {
self.subscriptions.forEach { $0.cancel() }
}
}
wait(for: [watchEx1, watchEx2], timeout: 60.0)
}
func testWatchCombineWithMatchFilter() {
let sema1 = DispatchSemaphore(value: 0)
let sema2 = DispatchSemaphore(value: 0)
let openSema1 = DispatchSemaphore(value: 0)
let openSema2 = DispatchSemaphore(value: 0)
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
var objectIds = [ObjectId]()
let insertManyEx = expectation(description: "Insert many documents")
collection.insertMany([document, document2, document3, document4]) { result in
switch result {
case .success(let objIds):
XCTAssertEqual(objIds.count, 4)
objectIds = objIds.map { $0.objectIdValue! }
case .failure(let error):
XCTFail("Failed to insert: \(error)")
}
insertManyEx.fulfill()
}
wait(for: [insertManyEx], timeout: 4.0)
let watchEx1 = expectation(description: "Watch 3 document events")
watchEx1.expectedFulfillmentCount = 3
let watchEx2 = expectation(description: "Watch 3 document events")
watchEx2.expectedFulfillmentCount = 3
collection.watch(matchFilter: ["fullDocument._id": AnyBSON.objectId(objectIds[0])])
.onOpen {
openSema1.signal()
}
.subscribe(on: DispatchQueue.main)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { _ in }) { changeEvent in
XCTAssertTrue(Thread.isMainThread)
guard let doc = changeEvent.documentValue else {
return
}
let objectId = doc["fullDocument"]??.documentValue!["_id"]??.objectIdValue!
if objectId == objectIds[0] {
watchEx1.fulfill()
sema1.signal()
}
}.store(in: &subscriptions)
collection.watch(matchFilter: ["fullDocument._id": AnyBSON.objectId(objectIds[1])])
.onOpen {
openSema2.signal()
}
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.global())
.sink(receiveCompletion: { _ in }) { changeEvent in
XCTAssertFalse(Thread.isMainThread)
guard let doc = changeEvent.documentValue else {
return
}
let objectId = doc["fullDocument"]??.documentValue!["_id"]??.objectIdValue!
if objectId == objectIds[1] {
watchEx2.fulfill()
sema2.signal()
}
}.store(in: &subscriptions)
DispatchQueue.global().async {
openSema1.wait()
openSema2.wait()
for i in 0..<3 {
let name: AnyBSON = .string("fido-\(i)")
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[0])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
collection.updateOneDocument(filter: ["_id": AnyBSON.objectId(objectIds[1])],
update: ["name": name, "breed": "king charles"]) { result in
if case .failure = result {
XCTFail("Should update")
}
}
sema1.wait()
sema2.wait()
}
DispatchQueue.main.async {
self.subscriptions.forEach { $0.cancel() }
}
}
wait(for: [watchEx1, watchEx2], timeout: 60.0)
}
// MARK: - Combine promises
func testEmailPasswordAuthenticationCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let auth = app.emailPasswordAuth
auth.registerUser(email: email, password: password).await(self)
auth.confirmUser("atoken", tokenId: "atokenid").awaitFailure(self)
auth.resendConfirmationEmail(email: "atoken").awaitFailure(self)
auth.retryCustomConfirmation(email: email).awaitFailure(self)
auth.sendResetPasswordEmail(email: "atoken").awaitFailure(self)
auth.resetPassword(to: "password", token: "atoken", tokenId: "tokenId").awaitFailure(self)
auth.callResetPasswordFunction(email: email, password: randomString(10), args: [[:]]).awaitFailure(self)
}
func testAppLoginCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
let loginEx = expectation(description: "Login user")
let appEx = expectation(description: "App changes triggered")
var triggered = 0
app.objectWillChange.sink { _ in
triggered += 1
if triggered == 2 {
appEx.fulfill()
}
}.store(in: &subscriptions)
app.emailPasswordAuth.registerUser(email: email, password: password)
.flatMap { self.app.login(credentials: .emailPassword(email: email, password: password)) }
.sink(receiveCompletion: { result in
if case let .failure(error) = result {
XCTFail("Should have completed login chain: \(error.localizedDescription)")
}
}, receiveValue: { user in
user.objectWillChange.sink { user in
XCTAssert(!user.isLoggedIn)
loginEx.fulfill()
}.store(in: &self.subscriptions)
XCTAssertEqual(user.id, self.app.currentUser?.id)
user.logOut { _ in } // logout user and make sure it is observed
})
.store(in: &subscriptions)
wait(for: [loginEx, appEx], timeout: 30.0)
XCTAssertEqual(self.app.allUsers.count, 1)
XCTAssertEqual(triggered, 2)
}
func testAsyncOpenCombine() {
if isParent {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
app.emailPasswordAuth.registerUser(email: email, password: password)
.flatMap { self.app.login(credentials: .emailPassword(email: email, password: password)) }
.flatMap { user in
Realm.asyncOpen(configuration: user.configuration(testName: #function))
}
.await(self, timeout: 30.0) { realm in
try! realm.write {
realm.add(SwiftHugeSyncObject.create())
realm.add(SwiftHugeSyncObject.create())
}
let progressEx = self.expectation(description: "Should upload")
let token = realm.syncSession!.addProgressNotification(for: .upload, mode: .forCurrentlyOutstandingWork) {
if $0.isTransferComplete {
progressEx.fulfill()
}
}
self.wait(for: [progressEx], timeout: 30.0)
token?.invalidate()
}
executeChild()
} else {
let chainEx = expectation(description: "Should chain realm login => realm async open")
let progressEx = expectation(description: "Should receive progress notification")
app.login(credentials: .anonymous)
.flatMap {
Realm.asyncOpen(configuration: $0.configuration(testName: #function)).onProgressNotification {
if $0.isTransferComplete {
progressEx.fulfill()
}
}
}
.expectValue(self, chainEx) { realm in
XCTAssertEqual(realm.objects(SwiftHugeSyncObject.self).count, 2)
}.store(in: &subscriptions)
wait(for: [chainEx, progressEx], timeout: 30.0)
}
}
func testAsyncOpenStandaloneCombine() throws {
try autoreleasepool {
let realm = try Realm()
try! realm.write {
(0..<10000).forEach { _ in realm.add(SwiftPerson(firstName: "Charlie", lastName: "Bucket")) }
}
}
Realm.asyncOpen().await(self) { realm in
XCTAssertEqual(realm.objects(SwiftPerson.self).count, 10000)
}
}
func testRefreshCustomDataCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
app.emailPasswordAuth.registerUser(email: email, password: password).await(self)
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: credentials)
.await(self) { user in
XCTAssertNotNil(user)
}
let userDataEx = expectation(description: "Update user data")
app.currentUser?.functions.updateUserData([["favourite_colour": "green", "apples": 10]]) { _, error in
XCTAssertNil(error)
userDataEx.fulfill()
}
wait(for: [userDataEx], timeout: 4.0)
app.currentUser?.refreshCustomData()
.await(self) { customData in
XCTAssertEqual(customData["apples"] as! Int, 10)
XCTAssertEqual(customData["favourite_colour"] as! String, "green")
}
XCTAssertEqual(app.currentUser?.customData["favourite_colour"], .string("green"))
XCTAssertEqual(app.currentUser?.customData["apples"], .int64(10))
}
func testMongoCollectionInsertCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "tibetan mastiff"]
collection.insertOne(document).await(self)
collection.insertMany([document, document2])
.await(self) { objectIds in
XCTAssertEqual(objectIds.count, 2)
}
collection.find(filter: [:])
.await(self) { findResult in
XCTAssertEqual(findResult.map({ $0["name"]??.stringValue }), ["fido", "fido", "rex"])
}
}
func testMongoCollectionFindCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "tibetan mastiff"]
let document3: Document = ["name": "rex", "breed": "tibetan mastiff", "coat": ["fawn", "brown", "white"]]
let findOptions = FindOptions(1, nil, nil)
collection.find(filter: [:], options: findOptions)
.await(self) { findResult in
XCTAssertEqual(findResult.count, 0)
}
collection.insertMany([document, document2, document3]).await(self)
collection.find(filter: [:])
.await(self) { findResult in
XCTAssertEqual(findResult.map({ $0["name"]??.stringValue }), ["fido", "rex", "rex"])
}
collection.find(filter: [:], options: findOptions)
.await(self) { findResult in
XCTAssertEqual(findResult.count, 1)
XCTAssertEqual(findResult[0]["name"]??.stringValue, "fido")
}
collection.find(filter: document3, options: findOptions)
.await(self) { findResult in
XCTAssertEqual(findResult.count, 1)
}
collection.findOneDocument(filter: document).await(self)
collection.findOneDocument(filter: document, options: findOptions).await(self)
}
func testMongoCollectionCountAndAggregateCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
collection.insertMany([document]).await(self)
collection.aggregate(pipeline: [["$match": ["name": "fido"]], ["$group": ["_id": "$name"]]])
.await(self)
collection.count(filter: document).await(self) { count in
XCTAssertEqual(count, 1)
}
collection.count(filter: document, limit: 1).await(self) { count in
XCTAssertEqual(count, 1)
}
}
func testMongoCollectionDeleteOneCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
collection.deleteOneDocument(filter: document).await(self) { count in
XCTAssertEqual(count, 0)
}
collection.insertMany([document, document2]).await(self)
collection.deleteOneDocument(filter: document).await(self) { count in
XCTAssertEqual(count, 1)
}
}
func testMongoCollectionDeleteManyCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
collection.deleteManyDocuments(filter: document).await(self) { count in
XCTAssertEqual(count, 0)
}
collection.insertMany([document, document2]).await(self)
collection.deleteManyDocuments(filter: ["breed": "cane corso"]).await(self) { count in
XCTAssertEqual(count, 2)
}
}
func testMongoCollectionUpdateOneCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
let document5: Document = ["name": "bill", "breed": "great dane"]
collection.insertMany([document, document2, document3, document4]).await(self)
collection.updateOneDocument(filter: document, update: document2).await(self) { updateResult in
XCTAssertEqual(updateResult.matchedCount, 1)
XCTAssertEqual(updateResult.modifiedCount, 1)
XCTAssertNil(updateResult.objectId)
}
collection.updateOneDocument(filter: document5, update: document2, upsert: true).await(self) { updateResult in
XCTAssertEqual(updateResult.matchedCount, 0)
XCTAssertEqual(updateResult.modifiedCount, 0)
XCTAssertNotNil(updateResult.objectId)
}
}
func testMongoCollectionUpdateManyCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
let document4: Document = ["name": "ted", "breed": "bullmastiff"]
let document5: Document = ["name": "bill", "breed": "great dane"]
collection.insertMany([document, document2, document3, document4]).await(self)
collection.updateManyDocuments(filter: document, update: document2).await(self) { updateResult in
XCTAssertEqual(updateResult.matchedCount, 1)
XCTAssertEqual(updateResult.modifiedCount, 1)
XCTAssertNil(updateResult.objectId)
}
collection.updateManyDocuments(filter: document5, update: document2, upsert: true).await(self) { updateResult in
XCTAssertEqual(updateResult.matchedCount, 0)
XCTAssertEqual(updateResult.modifiedCount, 0)
XCTAssertNotNil(updateResult.objectId)
}
}
func testMongoCollectionFindAndUpdateCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
collection.findOneAndUpdate(filter: document, update: document2).await(self)
let options1 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
collection.findOneAndUpdate(filter: document2, update: document3, options: options1).await(self) { updateResult in
guard let updateResult = updateResult else {
XCTFail("Should find")
return
}
XCTAssertEqual(updateResult["name"]??.stringValue, "john")
}
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
collection.findOneAndUpdate(filter: document, update: document2, options: options2).await(self) { updateResult in
guard let updateResult = updateResult else {
XCTFail("Should find")
return
}
XCTAssertEqual(updateResult["name"]??.stringValue, "rex")
}
}
func testMongoCollectionFindAndReplaceCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
let document2: Document = ["name": "rex", "breed": "cane corso"]
let document3: Document = ["name": "john", "breed": "cane corso"]
collection.findOneAndReplace(filter: document, replacement: document2).await(self) { updateResult in
XCTAssertNil(updateResult)
}
let options1 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, true)
collection.findOneAndReplace(filter: document2, replacement: document3, options: options1).await(self) { updateResult in
guard let updateResult = updateResult else {
XCTFail("Should find")
return
}
XCTAssertEqual(updateResult["name"]??.stringValue, "john")
}
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1], true, false)
collection.findOneAndReplace(filter: document, replacement: document2, options: options2).await(self) { updateResult in
XCTAssertNil(updateResult)
}
}
func testMongoCollectionFindAndDeleteCombine() {
let collection = setupMongoCollection()
let document: Document = ["name": "fido", "breed": "cane corso"]
collection.insertMany([document]).await(self)
collection.findOneAndDelete(filter: document).await(self) { updateResult in
XCTAssertNotNil(updateResult)
}
collection.findOneAndDelete(filter: document).await(self) { updateResult in
XCTAssertNil(updateResult)
}
collection.insertMany([document]).await(self)
let options1 = FindOneAndModifyOptions(projection: ["name": 1], sort: ["_id": 1], upsert: false, shouldReturnNewDocument: false)
collection.findOneAndDelete(filter: document, options: options1).await(self) { deleteResult in
XCTAssertNotNil(deleteResult)
}
collection.findOneAndDelete(filter: document, options: options1).await(self) { deleteResult in
XCTAssertNil(deleteResult)
}
collection.insertMany([document]).await(self)
let options2 = FindOneAndModifyOptions(["name": 1], ["_id": 1])
collection.findOneAndDelete(filter: document, options: options2).await(self) { deleteResult in
XCTAssertNotNil(deleteResult)
}
collection.findOneAndDelete(filter: document, options: options2).await(self) { deleteResult in
XCTAssertNil(deleteResult)
}
collection.insertMany([document]).await(self)
collection.find(filter: [:]).await(self) { updateResult in
XCTAssertEqual(updateResult.count, 1)
}
}
func testCallFunctionCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
app.emailPasswordAuth.registerUser(email: email, password: password).await(self)
let credentials = Credentials.emailPassword(email: email, password: password)
app.login(credentials: credentials).await(self) { user in
XCTAssertNotNil(user)
}
app.currentUser?.functions.sum([1, 2, 3, 4, 5]).await(self) { bson in
guard case let .int32(sum) = bson else {
XCTFail("Should be int32")
return
}
XCTAssertEqual(sum, 15)
}
app.currentUser?.functions.updateUserData([["favourite_colour": "green", "apples": 10]]).await(self) { bson in
guard case let .bool(upd) = bson else {
XCTFail("Should be bool")
return
}
XCTAssertTrue(upd)
}
}
func testAPIKeyAuthCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
app.emailPasswordAuth.registerUser(email: email, password: password).await(self)
var syncUser: User?
app.login(credentials: Credentials.emailPassword(email: email, password: password)).await(self) { user in
syncUser = user
}
var apiKey: UserAPIKey?
syncUser?.apiKeysAuth.createAPIKey(named: "my-api-key").await(self) { userApiKey in
apiKey = userApiKey
}
var objId: ObjectId? = try? ObjectId(string: apiKey!.objectId.stringValue)
syncUser?.apiKeysAuth.fetchAPIKey(objId!).await(self) { userApiKey in
apiKey = userApiKey
}
syncUser?.apiKeysAuth.fetchAPIKeys().await(self) { userApiKeys in
XCTAssertEqual(userApiKeys.count, 1)
}
objId = try? ObjectId(string: apiKey!.objectId.stringValue)
syncUser?.apiKeysAuth.disableAPIKey(objId!).await(self)
syncUser?.apiKeysAuth.enableAPIKey(objId!).await(self)
syncUser?.apiKeysAuth.deleteAPIKey(objId!).await(self)
}
func testPushRegistrationCombine() {
let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com"
let password = randomString(10)
app.emailPasswordAuth.registerUser(email: email, password: password).await(self)
app.login(credentials: Credentials.emailPassword(email: email, password: password)).await(self)
let client = app.pushClient(serviceName: "gcm")
client.registerDevice(token: "some-token", user: app.currentUser!).await(self)
client.deregisterDevice(user: app.currentUser!).await(self)
}
}
#endif // os(macOS)
| apache-2.0 | 48e316ad6cd9a0140cd17421993280e0 | 40.544612 | 148 | 0.574925 | 4.707797 | false | true | false | false |
Hexaville/HexavilleAuth | Sources/HexavilleAuth/HexaviileAuth.swift | 1 | 1557 | import Foundation
import HexavilleFramework
public enum HexavilleAuthError: Error {
case unsupportedPlaform
case codeIsMissingInResponseParameters
case responseError(HTTPURLResponse, Data)
}
extension HexavilleAuthError: CustomStringConvertible {
public var description: String {
switch self {
case .responseError(let response, let body):
var str = ""
str += "\(response)"
str += "\n"
str += "\n"
str += String(data: body, encoding: .utf8) ?? "Unknown Error"
return str
default:
return "\(self)"
}
}
}
public enum CredentialProviderType {
case oauth2(OAuth2AuthorizationProvidable)
case oauth1(OAuth1AuthorizationProvidable)
}
public struct HexavilleAuth {
var providers: [CredentialProviderType] = []
public init() {}
public mutating func add(_ provider: OAuth1AuthorizationProvidable) {
self.providers.append(.oauth1(provider))
}
public mutating func add(_ provider: OAuth2AuthorizationProvidable) {
self.providers.append(.oauth2(provider))
}
}
extension ApplicationContext {
public func isAuthenticated() -> Bool {
return loginUser != nil
}
public var loginUser: LoginUser? {
get {
return memory[HexavilleAuth.AuthenticationMiddleware.sessionKey] as? LoginUser
}
set {
return memory[HexavilleAuth.AuthenticationMiddleware.sessionKey] = newValue
}
}
}
| mit | 6a8d055683fc5eea926c63289d78da86 | 25.389831 | 90 | 0.633269 | 4.927215 | false | false | false | false |
urklc/UKPullToRefresh | UKPullToRefresh/UIScrollView+PullToRefresh.swift | 1 | 2570 | //
// Copyright (c) 2017, Ugur Kilic
//
// 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.
public var PullToRefreshHandle: UInt8 = 0
extension UIScrollView {
public var pullToRefreshView: UKPullToRefreshView! {
get {
return objc_getAssociatedObject(self, &PullToRefreshHandle) as? UKPullToRefreshView
}
set {
willChangeValue(forKey: "refreshView")
objc_setAssociatedObject(self, &PullToRefreshHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
didChangeValue(forKey: "refreshView")
}
}
public func setPullToRefreshViewHidden(_ hidden: Bool) {
pullToRefreshView?.isHidden = hidden
pullToRefreshView.scrollView = hidden ? nil : self
}
public func addPullToRefresh(to position: UKPullToRefreshView.Position, handler: @escaping () -> (Void)) {
let view = UKPullToRefreshView()
self.addSubview(view)
view.actionHandler = handler
view.position = position
pullToRefreshView = view
setPullToRefreshViewHidden(false)
}
public func addPullToRefresh(to position: UKPullToRefreshView.Position, type: UKPullToRefreshView.Type, handler: @escaping () -> (Void)) {
let view = type.init()
self.addSubview(view)
view.actionHandler = handler
view.position = position
view.scrollViewInitialInset = (contentInset.top, contentInset.bottom)
pullToRefreshView = view
setPullToRefreshViewHidden(false)
}
}
| mit | f08982c0b0a9816108ef276150c2951f | 38.538462 | 142 | 0.71284 | 4.913958 | false | false | false | false |
dk53/AutomaticStatusBarColor | AutomaticStatusBarColor/Classes/AutomaticStatusBarColor.swift | 1 | 3276 | //
// AppDelegate.swift
// AutomaticStatusBarColor
//
// Created by Victor Carmouze on 01/23/2017.
// Copyright (c) 2017 Victor Carmouze. All rights reserved.
//
public class AutomaticStatusBarColor {
init() {
UIViewController.classInit
}
public static let sharedInstance = AutomaticStatusBarColor()
fileprivate var disabledViewControllers = [UIViewController]()
fileprivate var customStatusBarViewControllers = [(controller: UIViewController, style: UIStatusBarStyle)]()
fileprivate var isEnabled = true
public func disable(forViewController viewController: UIViewController) {
disabledViewControllers.append(viewController)
}
public func force(statusBarStyle style: UIStatusBarStyle, forViewController viewController: UIViewController) {
customStatusBarViewControllers.append((viewController, style))
}
}
private let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
guard
let originalMethod = class_getInstanceMethod(forClass, originalSelector),
let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
else { return }
method_exchangeImplementations(originalMethod, swizzledMethod)
}
extension UIViewController {
static let classInit: Void = {
let originalSelector = #selector(viewWillAppear(_:))
let swizzledSelector = #selector(asb_viewWillAppear(animated:))
swizzling(UIViewController.self, originalSelector, swizzledSelector)
}()
@objc func asb_viewWillAppear(animated: Bool) {
asb_viewWillAppear(animated: animated)
updateStatusBarColor()
}
fileprivate func updateStatusBarColor() {
if !AutomaticStatusBarColor.sharedInstance.disabledViewControllers.contains(self) &&
AutomaticStatusBarColor.sharedInstance.isEnabled &&
view.frame.origin == CGPoint(x: 0, y: 0) {
let customStatusBarViewControllers = AutomaticStatusBarColor.sharedInstance.customStatusBarViewControllers
if let customTuple = (customStatusBarViewControllers.filter { $0.controller == self }).first {
UIApplication.shared.statusBarStyle = customTuple.style
} else {
UIApplication.shared.statusBarStyle = statusBarAutomaticStyle()
}
}
}
private func statusBarAutomaticStyle() -> UIStatusBarStyle {
return UIColor.averageColor(fromImage: statusBarImage()).isLight() ? .default : .lightContent
}
private func statusBarImage() -> UIImage? {
UIGraphicsBeginImageContext(UIApplication.shared.statusBarFrame.size)
if let ctx = UIGraphicsGetCurrentContext() {
view.layer.render(in: ctx)
}
return UIGraphicsGetImageFromCurrentImageContext()
}
}
extension UIViewController {
public func force(statusBarStyle style: UIStatusBarStyle) {
AutomaticStatusBarColor.sharedInstance.force(statusBarStyle: style, forViewController: self)
}
public func disableAutomaticStatusBarColor() {
AutomaticStatusBarColor.sharedInstance.disable(forViewController: self)
}
public func reloadAutomaticStatusBarColor() {
updateStatusBarColor()
}
}
| mit | d746f22e4aa907a19700676c233949cc | 32.773196 | 118 | 0.714591 | 5.533784 | false | false | false | false |
davidahouse/chute | chute/Common/CommandLine.swift | 1 | 8011 | //
// CommandLine.swift
// chute
//
// Created by David House on 9/10/17.
// Copyright © 2017 David House. All rights reserved.
//
// Chute Command Line Reference:
//
// chute
// -platform iOS or Android
// -project The Xcode project to use when creating the Chute report
// -branch The branch that resprents the captured test results
// -compareFolder The folder to compare the results with
// -saveFolder The folder to save the test input data into
// To post a summary and optional link to full report in a github pull request, the following are needed:
// -githubRepository The repository to use when posting a comment to github (format of <owner>/<repo>)
// -githubToken The token to use for posting a comment to github
// -pullRequestNumber The pull request number (optional)
// -githubPagesFolder The root folder in Github Pages branch for publishing to
//
// -publishRootURL The root http url where the published files will be found
// -githubHost The host name if using github enterprise
// -githubAPIURL The API URL if using github enterprise
// -derivedDataFolder Root folder for DerivedData
// -buildFolder Root folder for Android builds
// -logLevel Determines if additional logs will be written
// -buildLogFile The specific path to the build log where we can find warnings and compiler errors
// -swiftLintLog The path to the swift lint log file
// -inferReport The path to the infer report file
import Foundation
struct CommandLineArguments {
let platform: String?
let project: String?
let branch: String?
let compareFolder: String?
let githubRepository: String?
let githubToken: String?
let pullRequestNumber: String?
let githubPagesFolder: String?
let githubHost: String?
let githubAPIURL: String?
let slackWebhook: String?
let publishRootURL: String?
let derivedDataFolder: String?
let buildFolder: String?
let logLevel: String?
let buildLogFile: String?
let swiftLintLog: String?
let inferReport: String?
var hasRequiredParameters: Bool {
return project != nil && platform != nil
}
var hasParametersForGithubNotification: Bool {
return githubRepository != nil && githubToken != nil && pullRequestNumber != nil
}
var hasParametersForSlackNotification: Bool {
return slackWebhook != nil
}
var hasParametersForGithubPagesPublish: Bool {
return githubRepository != nil && githubToken != nil && githubPagesFolder != nil
}
init(arguments: [String] = CommandLine.arguments) {
var foundArguments: [String: String] = [:]
for (index, value) in arguments.enumerated() {
if value.hasPrefix("-") && index < (arguments.count - 1) && !arguments[index+1].hasPrefix("-") {
let parameter = String(value.suffix(value.count - 1))
foundArguments[parameter] = arguments[index+1]
}
}
platform = foundArguments["platform"]
project = foundArguments["project"]
branch = foundArguments["branch"] != nil ? foundArguments["branch"] : ProcessInfo.processInfo.environment["CHUTE_BRANCH"]
compareFolder = foundArguments["compareFolder"] != nil ? foundArguments["compareFolder"] : ProcessInfo.processInfo.environment["CHUTE_COMPARE_FOLDER"]
githubRepository = foundArguments["githubRepository"] != nil ? foundArguments["githubRepository"] : ProcessInfo.processInfo.environment["CHUTE_GITHUB_REPOSITORY"]
githubToken = foundArguments["githubToken"] != nil ? foundArguments["githubToken"] : ProcessInfo.processInfo.environment["CHUTE_GITHUB_TOKEN"]
pullRequestNumber = foundArguments["pullRequestNumber"] != nil ? foundArguments["pullRequestNumber"] : ProcessInfo.processInfo.environment["CHUTE_PULL_REQUEST_NUMBER"]
githubPagesFolder = foundArguments["githubPagesFolder"] != nil ? foundArguments["githubPagesFolder"] : ProcessInfo.processInfo.environment["CHUTE_GITHUB_PAGES_FOLDER"]
slackWebhook = foundArguments["slackWebhook"] != nil ? foundArguments["slackWebhook"] : ProcessInfo.processInfo.environment["CHUTE_SLACK_WEBHOOK"]
publishRootURL = foundArguments["publishRootURL"] != nil ? foundArguments["publishRootURL"] : ProcessInfo.processInfo.environment["CHUTE_PUBLISH_ROOT_URL"]
githubHost = foundArguments["githubHost"] != nil ? foundArguments["githubHost"] : ProcessInfo.processInfo.environment["CHUTE_GITHUB_HOST"]
githubAPIURL = foundArguments["githubAPIURL"] != nil ? foundArguments["githubAPIURL"] : ProcessInfo.processInfo.environment["CHUTE_GITHUB_APIURL"]
derivedDataFolder = foundArguments["derivedDataFolder"] != nil ? foundArguments["derivedDataFolder"] : ProcessInfo.processInfo.environment["CHUTE_DERIVED_DATA_FOLDER"]
buildFolder = foundArguments["buildFolder"] != nil ? foundArguments["buildFolder"] : ProcessInfo.processInfo.environment["CHUTE_BUILD_FOLDER"]
logLevel = foundArguments["logLevel"] != nil ? foundArguments["logLevel"] : ProcessInfo.processInfo.environment["CHUTE_LOG_LEVEL"]
buildLogFile = foundArguments["buildLogFile"] != nil ? foundArguments["buildLogFile"] :
ProcessInfo.processInfo.environment["CHUTE_BUILD_LOG_FILE"]
swiftLintLog = foundArguments["swiftLintLog"] != nil ? foundArguments["swiftLintLog"] :
ProcessInfo.processInfo.environment["CHUTE_SWIFT_LINT_LOG"]
inferReport = foundArguments["inferReport"] != nil ? foundArguments["inferReport"] : ProcessInfo.processInfo.environment["CHUTE_INFER_REPORT"]
}
func printInstructions() {
var instructions = "Usage: chute -platform <platform> -project <project>"
instructions += " [-branch <branch>]"
instructions += " [-compareFolder <compareFolder>]"
instructions += " [-githubRepository <githubRepository>]"
instructions += " [-githubToken <githubToken>]"
instructions += " [-pullRequestNumber <pullRequestNumber>]"
instructions += " [-githubPagesFolder <githubPagesFolder>]"
instructions += " [-slackWebhook <slackWebhook>]"
instructions += " [-publishRootURL <publishRootURL>]"
instructions += " [-githubHost <githubHost>]"
instructions += " [-githubAPIURL <githubAPIURL>]"
instructions += " [-derivedDataFolder <derivedDataFolder>]"
instructions += " [-buildFolder <buildFolder>]"
instructions += " [-logLevel <logLevel>]"
instructions += " [-buildLogFile <buildLogFile>]"
instructions += " [-swiftLintLog <swiftLintLog>]"
instructions += " [-inferReport <inferReport>"
print(instructions)
}
}
extension CommandLineArguments: Printable {
func printOut() {
print("Platform: \(platform ?? "")")
print("Project: \(project ?? "")")
print("Branch: \(branch ?? "")")
print("Compare Folder: \(compareFolder ?? "")")
print("Github Repository: \(githubRepository ?? "")")
print("Github Token: \(githubToken ?? "")")
print("PR Number: \(pullRequestNumber ?? "")")
print("Github Pages Folder: \(githubPagesFolder ?? "")")
print("Slack Webhook: \(slackWebhook ?? "")")
print("Publish Root URL: \(publishRootURL ?? "")")
print("Github Host: \(githubHost ?? "")")
print("Github API URL: \(githubAPIURL ?? "")")
print("Derived Data Folder: \(derivedDataFolder ?? "")")
print("Build Folder: \(buildFolder ?? "")")
print("Log Level: \(logLevel ?? "")")
print("Build Log File: \(buildLogFile ?? "")")
print("Swift Lint Log: \(swiftLintLog ?? "")")
print("Infer Report: \(inferReport ?? "")")
}
}
| mit | 87d7ab956b65fe67518ffdc557b0e33c | 49.377358 | 175 | 0.65593 | 4.717314 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/Views/CheckmarkListItem.swift | 1 | 3599 | //
// CheckmarkListItem.swift
// LoopKitUI
//
// Created by Rick Pasetto on 7/17/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public struct CheckmarkListItem: View {
var title: Text
var titleFont: Font
var description: Text
@Binding var isSelected: Bool
let isEnabled: Bool
public init(title: Text, titleFont: Font = .headline, description: Text, isSelected: Binding<Bool>, isEnabled: Bool = true) {
self.title = title
self.titleFont = titleFont
self.description = description
self._isSelected = isSelected
self.isEnabled = isEnabled
}
@ViewBuilder
public var body: some View {
if isEnabled {
Button(action: { self.isSelected = true }) {
content
}
} else {
content
}
}
private var content: some View {
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 4) {
title
.font(titleFont)
description
.font(.footnote)
.foregroundColor(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 12)
selectionIndicator
.accessibility(label: Text(isSelected ? "Selected" : "Unselected"))
}
.animation(nil)
}
@ViewBuilder
private var selectionIndicator: some View {
if isEnabled {
filledCheckmark
.frame(width: 26, height: 26)
} else {
plainCheckmark
.frame(width: 22, height: 22)
}
}
@ViewBuilder
private var filledCheckmark: some View {
if isSelected {
Image(systemName: "checkmark.circle.fill")
.resizable()
.background(Circle().stroke()) // Ensure size aligns with open circle
.foregroundColor(.accentColor)
} else {
Circle()
.stroke()
.foregroundColor(Color(.systemGray4))
}
}
@ViewBuilder
private var plainCheckmark: some View {
if isSelected {
Image(systemName: "checkmark")
.resizable()
.foregroundColor(.accentColor)
}
}
}
public struct DurationBasedCheckmarkListItem: View {
var title: Text
var titleFont: Font
var description: Text
@Binding var isSelected: Bool
let isEnabled: Bool
@Binding var duration: TimeInterval
var validDurationRange: ClosedRange<TimeInterval>
public init(title: Text, titleFont: Font = .headline, description: Text, isSelected: Binding<Bool>, isEnabled: Bool = true,
duration: Binding<TimeInterval>, validDurationRange: ClosedRange<TimeInterval>) {
self.title = title
self.titleFont = titleFont
self.description = description
self._isSelected = isSelected
self.isEnabled = isEnabled
self._duration = duration
self.validDurationRange = validDurationRange
}
public var body: some View {
VStack(spacing: 0) {
CheckmarkListItem(title: title, titleFont: titleFont, description: description, isSelected: $isSelected, isEnabled: isEnabled)
if isSelected {
DurationPicker(duration: $duration, validDurationRange: validDurationRange)
.frame(height: 216)
.transition(.fadeInFromTop)
}
}
}
}
| mit | 9ca74922ac88d4b71970456293191246 | 27.784 | 138 | 0.570317 | 5.14 | false | false | false | false |
e-how/kingTrader | kingTrader/Pods/CryptoSwift/CryptoSwift/HashProtocol.swift | 20 | 1164 | //
// HashProtocol.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 17/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
internal protocol HashProtocol {
var message: NSData { get }
/** Common part for hash calculation. Prepare header data. */
func prepare(len:Int) -> NSMutableData
}
extension HashProtocol {
func prepare(len:Int) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length
var counter = 0
while msgLength % len != (len - 8) {
counter++
msgLength++
}
let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
bufZeros.destroy()
bufZeros.dealloc(1)
return tmpMessage
}
} | apache-2.0 | 58faf9c6cb66b39fe3e502cb51c66707 | 25.431818 | 88 | 0.607573 | 4.611111 | false | false | false | false |
gottesmm/swift | test/SILGen/witness_tables.swift | 2 | 40395 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
// RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
// RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
// RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
// RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
import witness_tables_b
struct Arg {}
@objc class ObjCClass {}
infix operator <~> {}
protocol AssocReqt {
func requiredMethod()
}
protocol ArchetypeReqt {
func requiredMethod()
}
protocol AnyProtocol {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<A: ArchetypeReqt>(x x: A, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
protocol ClassProtocol : class {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<B: ArchetypeReqt>(x x: B, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
@objc protocol ObjCProtocol {
func method(x x: ObjCClass)
static func staticMethod(y y: ObjCClass)
}
class SomeAssoc {}
struct ConformingAssoc : AssocReqt {
func requiredMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables {
// TABLE-TESTABLE-LABEL: sil_witness_table [fragile] ConformingAssoc: AssocReqt module witness_tables {
// TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: @_T014witness_tables15ConformingAssocVAA0D4ReqtAaaDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-ALL-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtAaaDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtAaaDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
struct ConformingStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingStruct) {}
func generic<D: ArchetypeReqt>(x x: D, y: ConformingStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingStruct) {}
}
func <~>(x: ConformingStruct, y: ConformingStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW {{.*}}: ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
protocol AddressOnly {}
struct ConformingAddressOnlyStruct : AnyProtocol {
var p: AddressOnly // force address-only layout with a protocol-type field
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingAddressOnlyStruct) {}
func generic<E: ArchetypeReqt>(x x: E, y: ConformingAddressOnlyStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingAddressOnlyStruct) {}
}
func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
class ConformingClass : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClass) {}
func generic<F: ArchetypeReqt>(x x: F, y: ConformingClass) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClass) {}
}
func <~>(x: ConformingClass, y: ConformingClass) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingClass, @thick ConformingClass.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> ()
struct ConformsByExtension {}
extension ConformsByExtension : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformsByExtension) {}
func generic<G: ArchetypeReqt>(x x: G, y: ConformsByExtension) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformsByExtension) {}
}
func <~>(x: ConformsByExtension, y: ConformsByExtension) {}
// TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
extension OtherModuleStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: OtherModuleStruct) {}
func generic<H: ArchetypeReqt>(x x: H, y: OtherModuleStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: OtherModuleStruct) {}
}
func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {}
// TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolAddEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
protocol OtherProtocol {}
struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method<I, J>(x x: I, y: J) {}
func generic<K, L>(x x: K, y: L) {}
func assocTypesMethod<M, N>(x x: M, y: N) {}
static func staticMethod<O>(x x: O) {}
}
func <~> <P: OtherProtocol>(x: P, y: P) {}
// TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
class ConformingClassToClassProtocol : ClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClassToClassProtocol) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingClassToClassProtocol) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClassToClassProtocol) {}
}
func <~>(x: ConformingClassToClassProtocol,
y: ConformingClassToClassProtocol) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #ClassProtocol.method!1: @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.generic!1: @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.staticMethod!1: @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #ClassProtocol."<~>"!1: @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0AaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
class ConformingClassToObjCProtocol : ObjCProtocol {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
}
// TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol
struct ConformingGeneric<R: AssocReqt> : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = R
func method(x x: Arg, y: ConformingGeneric) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingGeneric) {}
func assocTypesMethod(x x: SomeAssoc, y: R) {}
static func staticMethod(x x: ConformingGeneric) {}
}
func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {}
// TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: R
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol AnotherProtocol {}
struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt>
: AnyProtocol, AnotherProtocol
{
typealias AssocType = SomeAssoc
typealias AssocWithReqt = S
func method<T, U>(x x: T, y: U) {}
func generic<V, W>(x x: V, y: W) {}
func assocTypesMethod<X, Y>(x x: X, y: Y) {}
static func staticMethod<Z>(x x: Z) {}
}
func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {}
// TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: S
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolAaA9AssocReqtRzlAaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol InheritedProtocol1 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedProtocol2 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedClassProtocol : class, AnyProtocol {
func inheritedMethod()
}
struct InheritedConformance : InheritedProtocol1 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: InheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: InheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: InheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: InheritedConformance, y: InheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_T014witness_tables20InheritedConformanceVAA0C9Protocol1AaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables20InheritedConformanceVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables20InheritedConformanceVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables20InheritedConformanceVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables20InheritedConformanceVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables20InheritedConformanceVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: RedundantInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: RedundantInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: RedundantInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_T014witness_tables29RedundantInheritedConformanceVAA0D9Protocol1AaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: DiamondInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: DiamondInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: DiamondInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol1AaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol2AaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
class ClassInheritedConformance : InheritedClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ClassInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: ClassInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ClassInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolAaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// -- Witnesses have the 'self' abstraction level of their protocol.
// AnyProtocol has no class bound, so its witnesses treat Self as opaque.
// InheritedClassProtocol has a class bound, so its witnesses treat Self as
// a reference value.
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolAaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@guaranteed ClassInheritedConformance) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> ()
struct GenericAssocType<T> : AssocReqt {
func requiredMethod() {}
}
protocol AssocTypeWithReqt {
associatedtype AssocType : AssocReqt
}
struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt {
typealias AssocType = CC
}
// TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: CC
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent
// TABLE-NEXT: }
struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt {
typealias AssocType = GenericAssocType<DD>
}
// TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: GenericAssocType<DD>
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): GenericAssocType<DD>: specialize <DD> (<T> GenericAssocType<T>: AssocReqt module witness_tables)
// TABLE-NEXT: }
protocol InheritedFromObjC : ObjCProtocol {
func inheritedMethod()
}
class ConformsInheritedFromObjC : InheritedFromObjC {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
func inheritedMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables {
// TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: @_T014witness_tables25ConformsInheritedFromObjCCAA0deF1CAaaDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
protocol ObjCAssoc {
associatedtype AssocType : ObjCProtocol
}
struct HasObjCAssoc : ObjCAssoc {
typealias AssocType = ConformsInheritedFromObjC
}
// TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables {
// TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC
// TABLE-NEXT: }
protocol Initializer {
init(arg: Arg)
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_T014witness_tables20HasInitializerStructVAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables20HasInitializerStructVAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct
struct HasInitializerStruct : Initializer {
init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_T014witness_tables19HasInitializerClassCAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables19HasInitializerClassCAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass
class HasInitializerClass : Initializer {
required init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_T014witness_tables18HasInitializerEnumOAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_T014witness_tables18HasInitializerEnumOAA0D0AaaDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum
enum HasInitializerEnum : Initializer {
case A
init(arg: Arg) { self = .A }
}
| apache-2.0 | cc26425f3f6cfad353f28e49115399e5 | 72.405455 | 324 | 0.770763 | 3.645747 | false | false | false | false |
DrGo/SwiftDoro | SwiftDoro/TimerViewController.swift | 2 | 2311 | //
// SecondViewController.swift
// SwiftDoro
//
// Created by TRM on 6/17/15.
// Copyright (c) 2015 MottApplications. All rights reserved.
//
import UIKit
class TimerViewController: UIViewController {
@IBOutlet weak var timerButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.registerForNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.updateTimerLabel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
self.unregisterForNotification()
}
@IBAction func timerButtonTapped(sender: UIButton) {
sender.enabled = false;
Timer.sharedInstance.startTimer()
}
func newRound() {
self.updateTimerLabel()
self.timerButton?.enabled = true;
}
func updateTimerLabel() {
let seconds = Timer.sharedInstance.seconds
self.timerLabel?.text = self.timerStringWithSeconds(seconds)
}
func timerStringWithSeconds(seconds: Int) -> String {
var timerString = String()
let minutes = seconds / 60
let secondsMinusMinutes = seconds - minutes * 60
if minutes >= 10 {
timerString = "\(minutes):"
} else {
timerString = "0\(minutes):"
}
if secondsMinusMinutes >= 10 {
timerString += "\(secondsMinusMinutes)"
} else {
timerString += "0\(secondsMinusMinutes)"
}
return timerString
}
//MARK: - Notifications Methods
func registerForNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTimerLabel", name: kSecondTickNotifcation, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "newRound", name: kNewRoundNotification, object: nil)
}
func unregisterForNotification() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | eab8bc732ac108ef63289e0776442e96 | 24.966292 | 135 | 0.61402 | 5.112832 | false | false | false | false |
JadenGeller/Matchbox | Matchbox/Matchbox/InputStream.swift | 1 | 2232 | //
// AnyParser.swift
// Parsley
//
// Created by Jaden Geller on 10/13/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import Parsley
import Spork
public class InputStream<Token>: BooleanType {
public let state: ParseState<Token>
public var error: ParseError?
public let delimiter: Parser<Token, ()>
public var boolValue: Bool {
return error == nil
}
func match<Result>(parser: Parser<Token, Result>) -> Result? {
do { return try dropLeft(delimiter, parser).parse(state) }
catch let x as ParseError { error = x } catch { }
return nil
}
convenience public init<Sequence: SequenceType where Sequence.Generator.Element == Token>(_ sequence: Sequence) {
self.init(sequence, delimiter: none())
}
convenience public init<Sequence: SequenceType where Sequence.Generator.Element == Token>(sequence: Sequence) {
self.init(sequence, delimiter: none())
}
convenience public init<Ignore, Sequence: SequenceType where Sequence.Generator.Element == Token>(_ sequence: Sequence, delimiter: Parser<Token, Ignore>) {
self.init(ParseState(bridgedFromGenerator: sequence.generate()), delimiter: delimiter)
}
convenience public init<Ignore, Sequence: SequenceType where Sequence.Generator: ForkableGeneratorType, Sequence.Generator.Element == Token>(_ sequence: Sequence, delimiter: Parser<Token, Ignore>) {
self.init(ParseState(forkableGenerator: sequence.generate()), delimiter: delimiter)
}
private init<Ignore>(_ state: ParseState<Token>, delimiter: Parser<Token, Ignore>) {
self.state = state
self.delimiter = delimiter.discard()
}
}
/// A stream type that can be used to parse text, ignoring whitespace by default
public class TextStream: InputStream<Character> {
public init<Ignore>(_ string: String, delimiter: Parser<Character, Ignore>) {
super.init(ParseState(forkableGenerator: string.characters.generate()), delimiter: delimiter)
}
convenience init(_ string: String, ignoreWhitespace: Bool = true) {
self.init(string, delimiter: ignoreWhitespace ? many(within(" \n")).discard() : none())
}
}
| mit | 3e6d5f2b1779cb608bf6023a44aa8447 | 36.813559 | 202 | 0.681757 | 4.426587 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Renderer/ShaderSource.swift | 1 | 11710 | //
// ShaderSource.swift
// CesiumKit
//
// Created by Ryan Walklin on 7/03/15.
// Copyright (c) 2015 Test Toast. All rights reserved.
//
import Foundation
private class DependencyNode: Equatable {
var name: String
var glslSource: String
var dependsOn = [DependencyNode]()
var requiredBy = [DependencyNode]()
var evaluated: Bool = false
init (
name: String,
glslSource: String,
dependsOn: [DependencyNode] = [DependencyNode](),
requiredBy: [DependencyNode] = [DependencyNode](),
evaluated: Bool = false)
{
self.name = name
self.glslSource = glslSource
self.dependsOn = dependsOn
self.requiredBy = requiredBy
self.evaluated = evaluated
}
}
private func == (left: DependencyNode, right: DependencyNode) -> Bool {
return left.name == right.name &&
left.glslSource == right.glslSource
}
/**
* An object containing various inputs that will be combined to form a final GLSL shader string.
*
* @param {Object} [options] Object with the following properties:
* @param {String[]} [options.sources] An array of strings to combine containing GLSL code for the shader.
* @param {String[]} [options.defines] An array of strings containing GLSL identifiers to <code>#define</code>.
* @param {String} [options.pickColorQualifier] The GLSL qualifier, <code>uniform</code> or <code>varying</code>, for the input <code>czm_pickColor</code>. When defined, a pick fragment shader is generated.
* @param {Boolean} [options.includeBuiltIns=true] If true, referenced built-in functions will be included with the combined shader. Set to false if this shader will become a source in another shader, to avoid duplicating functions.
*
* @exception {DeveloperError} options.pickColorQualifier must be 'uniform' or 'varying'.
*
* @example
* // 1. Prepend #defines to a shader
* var source = new Cesium.ShaderSource({
* defines : ['WHITE'],
* sources : ['void main() { \n#ifdef WHITE\n gl_FragColor = vec4(1.0); \n#else\n gl_FragColor = vec4(0.0); \n#endif\n }']
* });
*
* // 2. Modify a fragment shader for picking
* var source = new Cesium.ShaderSource({
* sources : ['void main() { gl_FragColor = vec4(1.0); }'],
* pickColorQualifier : 'uniform'
* });
*
* @private
*/
struct ShaderSource {
var sources: [String]
var defines: [String]
var pickColorQualifier: String?
let includeBuiltIns: Bool
fileprivate let _commentRegex = "/\\*\\*[\\s\\S]*?\\*/"
fileprivate let _versionRegex = "/#version\\s+(.*?)\n"
fileprivate let _lineRegex = "\\n"
fileprivate let _czmRegex = "\\bczm_[a-zA-Z0-9_]*"
init (sources: [String] = [String](), defines: [String] = [String](), pickColorQualifier: String? = nil, includeBuiltIns: Bool = true) {
assert(pickColorQualifier == nil || pickColorQualifier == "uniform" || pickColorQualifier == "varying", "options.pickColorQualifier must be 'uniform' or 'varying'.")
self.defines = defines
self.sources = sources
self.pickColorQualifier = pickColorQualifier
self.includeBuiltIns = includeBuiltIns
}
/**
* Create a single string containing the full, combined vertex shader with all dependencies and defines.
*
* @returns {String} The combined shader string.
*/
func createCombinedVertexShader () -> String {
return combineShader(false)
}
/**
* Create a single string containing the full, combined fragment shader with all dependencies and defines.
*
* @returns {String} The combined shader string.
*/
func createCombinedFragmentShader () -> String {
return combineShader(true)
}
func combineShader(_ isFragmentShader: Bool) -> String {
// Combine shader sources, generally for pseudo-polymorphism, e.g., czm_getMaterial.
var combinedSources = ""
for (i, source) in sources.enumerated() {
// #line needs to be on its own line.
combinedSources += "\n#line 0\n" + sources[i];
}
combinedSources = removeComments(combinedSources)
var version: String? = nil
// Extract existing shader version from sources
let versionRange = combinedSources[_versionRegex].range()
if versionRange.location != NSNotFound {
version = (combinedSources as NSString).substring(with: versionRange)
combinedSources.replace(version!, "\n")
}
// Replace main() for picked if desired.
if pickColorQualifier != nil {
// FIXME: pickColorQualifier
/*combinedSources = combinedSources.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, 'void czm_old_main()');
combinedSources += '\
\n' + pickColorQualifier + ' vec4 czm_pickColor;\n\
void main()\n\
{\n\
czm_old_main();\n\
if (gl_FragColor.a == 0.0) {\n\
discard;\n\
}\n\
gl_FragColor = czm_pickColor;\n\
}';*/
}
// combine into single string
var result = ""
// #version must be first
// defaults to #version 100 if not specified
if version != nil {
result = "#version " + version!
}
// Prepend #defines for uber-shaders
for define in defines {
if define.characters.count != 0 {
result += "#define " + define + "\n"
}
}
// append built-ins
if includeBuiltIns {
result += getBuiltinsAndAutomaticUniforms(combinedSources)
}
// reset line number
result += "\n#line 0\n"
// append actual source
result += combinedSources
return result
}
fileprivate func removeComments (_ source: String) -> String {
// strip doc comments so we don't accidentally try to determine a dependency for something found
// in a comment
var newSource = source
let commentBlocks = newSource[_commentRegex].matches()
if commentBlocks.count > 0 {
for comment in commentBlocks {
let numberOfLines = comment[_lineRegex].matches().count
// preserve the number of lines in the comment block so the line numbers will be correct when debugging shaders
var modifiedComment = ""
for lineNumber in 0..<numberOfLines {
modifiedComment += "//\n"
}
newSource = newSource.replace(comment, modifiedComment)
}
}
return newSource
}
fileprivate func getBuiltinsAndAutomaticUniforms(_ shaderSource: String) -> String {
// generate a dependency graph for builtin functions
var dependencyNodes = [DependencyNode]()
let root = getDependencyNode("main", glslSource: shaderSource, nodes: &dependencyNodes)
generateDependencies(root, dependencyNodes: &dependencyNodes)
sortDependencies(&dependencyNodes)
// Concatenate the source code for the function dependencies.
// Iterate in reverse so that dependent items are declared before they are used.
return Array(dependencyNodes.reversed())
.reduce("", { $0 + $1.glslSource + "\n" })
.replace(root.glslSource, "")
}
fileprivate func getDependencyNode(_ name: String, glslSource: String, nodes: inout [DependencyNode]) -> DependencyNode {
var dependencyNode: DependencyNode?
// check if already loaded
for node in nodes {
if node.name == name {
dependencyNode = node
}
}
if dependencyNode == nil {
// strip doc comments so we don't accidentally try to determine a dependency for something found
// in a comment
let newGLSLSource = removeComments(glslSource)
// create new node
dependencyNode = DependencyNode(name: name, glslSource: newGLSLSource)
nodes.append(dependencyNode!)
}
return dependencyNode!
}
fileprivate func generateDependencies(_ currentNode: DependencyNode, dependencyNodes: inout [DependencyNode]) {
if currentNode.evaluated {
return
}
currentNode.evaluated = true
// identify all dependencies that are referenced from this glsl source code
let czmMatches = deleteDuplicates(currentNode.glslSource[_czmRegex].matches())
for match in czmMatches {
if (match != currentNode.name) {
var elementSource: String? = nil
if let builtin = Builtins[match] {
elementSource = builtin
} else if let uniform = AutomaticUniforms[match] {
elementSource = uniform.declaration(match)
} else {
logPrint(.warning, "uniform \(match) not found")
}
if elementSource != nil {
let referencedNode = getDependencyNode(match, glslSource: elementSource!, nodes: &dependencyNodes)
currentNode.dependsOn.append(referencedNode)
referencedNode.requiredBy.append(currentNode)
// recursive call to find any dependencies of the new node
generateDependencies(referencedNode, dependencyNodes: &dependencyNodes)
}
}
}
}
fileprivate func sortDependencies(_ dependencyNodes: inout [DependencyNode]) {
var nodesWithoutIncomingEdges = [DependencyNode]()
var allNodes = [DependencyNode]()
while (dependencyNodes.count > 0) {
let node = dependencyNodes.removeLast()
allNodes.append(node)
if node.requiredBy.count == 0 {
nodesWithoutIncomingEdges.append(node)
}
}
while nodesWithoutIncomingEdges.count > 0 {
let currentNode = nodesWithoutIncomingEdges.remove(at: 0)
dependencyNodes.append(currentNode)
for i in 0..<currentNode.dependsOn.count {
// remove the edge from the graph
let referencedNode = currentNode.dependsOn[i]
let index = referencedNode.requiredBy.index(of: currentNode)
if (index != nil) {
referencedNode.requiredBy.remove(at: index!)
}
// if referenced node has no more incoming edges, add to list
if referencedNode.requiredBy.count == 0 {
nodesWithoutIncomingEdges.append(referencedNode)
}
}
}
// if there are any nodes left with incoming edges, then there was a circular dependency somewhere in the graph
var badNodes = [DependencyNode]()
for node in allNodes {
if node.requiredBy.count != 0 {
badNodes.append(node)
}
}
if badNodes.count != 0 {
var message = "A circular dependency was found in the following built-in functions/structs/constants: \n"
for node in badNodes {
message += node.name + "\n"
}
assertionFailure(message)
}
}
}
| apache-2.0 | e0096716f06b154d16db5e72e5e426e2 | 35.708464 | 232 | 0.583689 | 4.79918 | false | false | false | false |
CikeQiu/CKMnemonic | CKMnemonic/CKMnemonic/ViewController.swift | 1 | 1281 | //
// ViewController.swift
// CKMnemonic
//
// Created by 仇弘扬 on 2017/7/25.
// Copyright © 2017年 askcoin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
let language: CKMnemonicLanguageType = .chinese
// let mnemonic = try CKMnemonic.generateMnemonic(strength: 128, language: language)
let mnemonicC = try CKMnemonic.mnemonicString(from: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", language: language)
let mnemonicE = try CKMnemonic.mnemonicString(from: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", language: .english)
let seedC = try CKMnemonic.deterministicSeedString(from: mnemonicC, passphrase: "Test", language: language)
let seedE = try CKMnemonic.deterministicSeedString(from: mnemonicE, passphrase: "Test", language: .english)
// let seedNoSec = try CKMnemonic.deterministicSeedString(from: mnemonic, language: language)
// print(seedNoSec)
print(mnemonicC)
print(mnemonicE)
print(seedC)
print(seedE)
} catch {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 1a7a2abba0103da149a475327d9de043 | 30.02439 | 110 | 0.744497 | 3.228426 | false | false | false | false |
jasnig/DouYuTVMutate | DouYuTVMutate/DouYuTV/Main/Lib/PhotoBrowser/PhotoToolBar.swift | 1 | 6624 | //
// PhotoToolBar.swift
// ImageBrowser
//
// Created by jasnig on 16/5/9.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// /// @author ZeroJ, 16-05-24 23:05:11
///
//TODO: 还未使用 (it is not useful now)
struct ToolBarStyle {
enum ToolBarPosition {
case Up
case Down
}
/// 是否显示保存按钮
var showSaveBtn = true
/// 是否显示附加按钮
var showExtraBtn = true
/// toolBar位置
var toolbarPosition = ToolBarPosition.Down
}
class PhotoToolBar: UIView {
typealias BtnAction = (btn: UIButton) -> Void
var saveBtnOnClick: BtnAction?
var extraBtnOnClick: BtnAction?
var indexText: String = " " {
didSet {
indexLabel.text = indexText
}
}
var toolBarStyle: ToolBarStyle!
/// 保存图片按钮
private lazy var saveBtn: UIButton = {
let saveBtn = UIButton()
saveBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
saveBtn.backgroundColor = UIColor.clearColor()
saveBtn.setImage(UIImage(named: "feed_video_icon_download_white"), forState: .Normal)
saveBtn.addTarget(self, action: #selector(self.saveBtnOnClick(_:)), forControlEvents: .TouchUpInside)
// saveBtn.hidden = self.toolBarStyle.showSaveBtn
return saveBtn
}()
/// 附加的按钮
private lazy var extraBtn: UIButton = {
let extraBtn = UIButton()
extraBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
extraBtn.backgroundColor = UIColor.clearColor()
extraBtn.setImage(UIImage(named: "more"), forState: .Normal)
extraBtn.addTarget(self, action: #selector(self.extraBtnOnClick(_:)), forControlEvents: .TouchUpInside)
// extraBtn.hidden = self.toolBarStyle.showExtraBtn
return extraBtn
}()
/// 显示页码
private lazy var indexLabel:UILabel = {
let indexLabel = UILabel()
indexLabel.textColor = UIColor.whiteColor()
indexLabel.backgroundColor = UIColor.clearColor()
indexLabel.textAlignment = NSTextAlignment.Center
indexLabel.font = UIFont.boldSystemFontOfSize(20.0)
return indexLabel
}()
init(frame: CGRect, toolBarStyle: ToolBarStyle) {
super.init(frame: frame)
self.toolBarStyle = toolBarStyle
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit() {
addSubview(saveBtn)
addSubview(indexLabel)
addSubview(extraBtn)
}
func saveBtnOnClick(btn: UIButton) {
saveBtnOnClick?(btn:btn)
}
func extraBtnOnClick(btn: UIButton) {
extraBtnOnClick?(btn: btn)
}
override func layoutSubviews() {
super.layoutSubviews()
let margin: CGFloat = 30.0
let btnW: CGFloat = 60.0
let saveBtnX = NSLayoutConstraint(item: saveBtn, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: margin)
let saveBtnY = NSLayoutConstraint(item: saveBtn, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)
let saveBtnW = NSLayoutConstraint(item: saveBtn, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: btnW)
let saveBtnH = NSLayoutConstraint(item: saveBtn, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1.0, constant: 0.0)
saveBtn.translatesAutoresizingMaskIntoConstraints = false
addConstraints([saveBtnX, saveBtnY, saveBtnW, saveBtnH])
let extraBtnX = NSLayoutConstraint(item: extraBtn, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: -margin)
let extraBtnY = NSLayoutConstraint(item: extraBtn, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)
let extraBtnW = NSLayoutConstraint(item: extraBtn, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: btnW)
let extraBtnH = NSLayoutConstraint(item: extraBtn, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1.0, constant: 0.0)
extraBtn.translatesAutoresizingMaskIntoConstraints = false
addConstraints([extraBtnX, extraBtnY, extraBtnW, extraBtnH])
let indexLabelLeft = NSLayoutConstraint(item: indexLabel, attribute: .Leading, relatedBy: .Equal, toItem: saveBtn, attribute: .Trailing, multiplier: 1.0, constant: 0.0)
let indexLabelY = NSLayoutConstraint(item: indexLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)
let indexLabelRight = NSLayoutConstraint(item: indexLabel, attribute: .Trailing, relatedBy: .Equal, toItem: extraBtn, attribute: .Leading, multiplier: 1.0, constant: 0.0)
let indexLabelH = NSLayoutConstraint(item: indexLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1.0, constant: 0.0)
indexLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraints([indexLabelLeft, indexLabelY, indexLabelRight, indexLabelH])
}
}
| mit | 9728389699a709053ab1068285774b4f | 41.764706 | 178 | 0.683173 | 4.359094 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV2/Models/RuntimeResponseGeneric.swift | 1 | 6202 | /**
* (C) Copyright IBM Corp. 2018, 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import IBMSwiftSDKCore
/**
RuntimeResponseGeneric.
*/
public enum RuntimeResponseGeneric: Codable, Equatable {
case audio(RuntimeResponseGenericRuntimeResponseTypeAudio)
case channelTransfer(RuntimeResponseGenericRuntimeResponseTypeChannelTransfer)
case connectToAgent(RuntimeResponseGenericRuntimeResponseTypeConnectToAgent)
case iframe(RuntimeResponseGenericRuntimeResponseTypeIframe)
case image(RuntimeResponseGenericRuntimeResponseTypeImage)
case option(RuntimeResponseGenericRuntimeResponseTypeOption)
case suggestion(RuntimeResponseGenericRuntimeResponseTypeSuggestion)
case pause(RuntimeResponseGenericRuntimeResponseTypePause)
case search(RuntimeResponseGenericRuntimeResponseTypeSearch)
case text(RuntimeResponseGenericRuntimeResponseTypeText)
case userDefined(RuntimeResponseGenericRuntimeResponseTypeUserDefined)
case video(RuntimeResponseGenericRuntimeResponseTypeVideo)
private struct GenericRuntimeResponseGeneric: Codable, Equatable {
var responseType: String
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let genericInstance = try? container.decode(GenericRuntimeResponseGeneric.self) {
switch genericInstance.responseType {
case "audio":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeAudio.self) {
self = .audio(val)
return
}
case "channel_transfer":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.self) {
self = .channelTransfer(val)
return
}
case "connect_to_agent":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.self) {
self = .connectToAgent(val)
return
}
case "iframe":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeIframe.self) {
self = .iframe(val)
return
}
case "image":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeImage.self) {
self = .image(val)
return
}
case "option":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeOption.self) {
self = .option(val)
return
}
case "suggestion":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeSuggestion.self) {
self = .suggestion(val)
return
}
case "pause":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypePause.self) {
self = .pause(val)
return
}
case "search":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeSearch.self) {
self = .search(val)
return
}
case "text":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeText.self) {
self = .text(val)
return
}
case "user_defined":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeUserDefined.self) {
self = .userDefined(val)
return
}
case "video":
if let val = try? container.decode(RuntimeResponseGenericRuntimeResponseTypeVideo.self) {
self = .video(val)
return
}
default:
// falling through to throw decoding error
break
}
}
throw DecodingError.typeMismatch(RuntimeResponseGeneric.self,
DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Decoding failed for all associated types"))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .audio(let audio):
try container.encode(audio)
case .channelTransfer(let channel_transfer):
try container.encode(channel_transfer)
case .connectToAgent(let connect_to_agent):
try container.encode(connect_to_agent)
case .iframe(let iframe):
try container.encode(iframe)
case .image(let image):
try container.encode(image)
case .option(let option):
try container.encode(option)
case .suggestion(let suggestion):
try container.encode(suggestion)
case .pause(let pause):
try container.encode(pause)
case .search(let search):
try container.encode(search)
case .text(let text):
try container.encode(text)
case .userDefined(let user_defined):
try container.encode(user_defined)
case .video(let video):
try container.encode(video)
}
}
}
| apache-2.0 | 398854291465b970ce755f4e3bdfead8 | 40.072848 | 157 | 0.611093 | 5.346552 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/ClosureSpacingRule.swift | 1 | 8901 | import Foundation
import SourceKittenFramework
extension NSRange {
private func equals(_ other: NSRange) -> Bool {
return NSEqualRanges(self, other)
}
private func isStrictSubset(of other: NSRange) -> Bool {
if equals(other) { return false }
return NSUnionRange(self, other).equals(other)
}
fileprivate func isStrictSubset(in others: [NSRange]) -> Bool {
return others.contains(where: isStrictSubset)
}
}
public struct ClosureSpacingRule: CorrectableRule, ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "closure_spacing",
name: "Closure Spacing",
description: "Closure expressions should have a single space inside each brace.",
kind: .style,
nonTriggeringExamples: [
"[].map ({ $0.description })",
"[].filter { $0.contains(location) }",
"extension UITableViewCell: ReusableView { }",
"extension UITableViewCell: ReusableView {}"
],
triggeringExamples: [
"[].filter(↓{$0.contains(location)})",
"[].map(↓{$0})",
"(↓{each in return result.contains(where: ↓{e in return e}) }).count",
"filter ↓{ sorted ↓{ $0 < $1}}"
],
corrections: [
"[].filter(↓{$0.contains(location)})":
"[].filter({ $0.contains(location) })",
"[].map(↓{$0})":
"[].map({ $0 })",
// Nested braces `{ {} }` do not get corrected on the first pass.
"filter ↓{sorted { $0 < $1}}":
"filter { sorted { $0 < $1} }",
// The user has to run tool again to fix remaining nested violations.
"filter { sorted ↓{ $0 < $1} }":
"filter { sorted { $0 < $1 } }",
"(↓{each in return result.contains(where: {e in return 0})}).count":
"({ each in return result.contains(where: {e in return 0}) }).count",
// second pass example
"({ each in return result.contains(where: ↓{e in return 0}) }).count":
"({ each in return result.contains(where: { e in return 0 }) }).count"
]
)
// this helps cut down the time to search through a file by
// skipping lines that do not have at least one `{` and one `}` brace
private func lineContainsBraces(in range: NSRange, content: NSString) -> NSRange? {
let start = content.range(of: "{", options: [.literal], range: range)
guard start.length != 0 else { return nil }
let end = content.range(of: "}", options: [.literal, .backwards], range: range)
guard end.length != 0 else { return nil }
guard start.location < end.location else { return nil }
return NSRange(location: start.location, length: end.location - start.location + 1)
}
// returns ranges of braces `{` or `}` in the same line
private func validBraces(in file: File) -> [NSRange] {
let nsstring = file.contents.bridge()
let bracePattern = regex("\\{|\\}")
let linesTokens = file.syntaxTokensByLines
let kindsToExclude = SyntaxKind.commentAndStringKinds.map { $0.rawValue }
// find all lines and occurences of open { and closed } braces
var linesWithBraces = [[NSRange]]()
for eachLine in file.lines {
guard let nsrange = lineContainsBraces(in: eachLine.range, content: nsstring) else {
continue
}
let braces = bracePattern.matches(in: file.contents, options: [],
range: nsrange).map { $0.range }
// filter out braces in comments and strings
let tokens = linesTokens[eachLine.index].filter { kindsToExclude.contains($0.type) }
let tokenRanges = tokens.compactMap {
file.contents.bridge().byteRangeToNSRange(start: $0.offset, length: $0.length)
}
linesWithBraces.append(braces.filter({ !$0.intersects(tokenRanges) }))
}
return linesWithBraces.flatMap { $0 }
}
// find ranges where violation exist. Returns ranges sorted by location.
private func findViolations(file: File) -> [NSRange] {
// match open braces to corresponding closing braces
func matchBraces(validBraceLocations: [NSRange]) -> [NSRange] {
if validBraceLocations.isEmpty { return [] }
var validBraces = validBraceLocations
var ranges = [NSRange]()
var bracesAsString = validBraces.map({
file.contents.substring(from: $0.location, length: $0.length)
}).joined()
while let foundRange = bracesAsString.range(of: "{}") {
let startIndex = bracesAsString.distance(from: bracesAsString.startIndex,
to: foundRange.lowerBound)
let location = validBraces[startIndex].location
let length = validBraces[startIndex + 1 ].location + 1 - location
ranges.append(NSRange(location: location, length: length))
bracesAsString.replaceSubrange(foundRange, with: "")
validBraces.removeSubrange(startIndex...startIndex + 1)
}
return ranges
}
// matching ranges of `{...}`
return matchBraces(validBraceLocations: validBraces(in: file))
.filter {
// removes enclosing brances to just content
let content = file.contents.substring(from: $0.location + 1, length: $0.length - 2)
if content.isEmpty || content == " " {
// case when {} is not a closure
return false
}
let cleaned = content.trimmingCharacters(in: .whitespaces)
return content != " " + cleaned + " "
}
.sorted {
$0.location < $1.location
}
}
public func validate(file: File) -> [StyleViolation] {
return findViolations(file: file).compactMap {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
// this will try to avoid nested ranges `{{}{}}` in single line
private func removeNested(_ ranges: [NSRange]) -> [NSRange] {
return ranges.filter { current in
return !current.isStrictSubset(in: ranges)
}
}
public func correct(file: File) -> [Correction] {
var matches = removeNested(findViolations(file: file)).filter {
!file.ruleEnabled(violatingRanges: [$0], for: self).isEmpty
}
guard !matches.isEmpty else { return [] }
// `matches` should be sorted by location from `findViolations`.
let start = NSRange(location: 0, length: 0)
let end = NSRange(location: file.contents.utf16.count, length: 0)
matches.insert(start, at: 0)
matches.append(end)
var fixedSections = [String]()
var matchIndex = 0
while matchIndex < matches.count - 1 {
defer { matchIndex += 1 }
// inverses the ranges to select non rule violation content
let current = matches[matchIndex].location + matches[matchIndex].length
let nextMatch = matches[matchIndex + 1]
let next = nextMatch.location
let length = next - current
let nonViolationContent = file.contents.substring(from: current, length: length)
if !nonViolationContent.isEmpty {
fixedSections.append(nonViolationContent)
}
// selects violation ranges and fixes them before adding back in
if nextMatch.length > 1 {
let violation = file.contents.substring(from: nextMatch.location + 1,
length: nextMatch.length - 2)
let cleaned = "{ " + violation.trimmingCharacters(in: .whitespaces) + " }"
fixedSections.append(cleaned)
}
// Catch all. Break at the end of loop.
if next == end.location { break }
}
// removes the start and end inserted above
if matches.count > 2 {
matches.remove(at: matches.count - 1)
matches.remove(at: 0)
}
// write changes to actual file
file.write(fixedSections.joined())
return matches.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0.location))
}
}
}
| mit | b83b7bbc7a071c9a43cb695f91f54e62 | 42.514706 | 99 | 0.568886 | 4.704293 | false | false | false | false |
JadenGeller/CS-81-Project | Sources/Statement.swift | 1 | 993 | //
// Statement.swift
// Language
//
// Created by Jaden Geller on 3/15/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
import Parsley
public enum Statement {
case binding(Identifier, Expression)
}
extension Statement: Equatable { }
public func ==(lhs: Statement, rhs: Statement) -> Bool {
switch (lhs, rhs) {
case (.binding(let lIdentifier, let lExpression), .binding(let rIdentifier, let rExpression)):
return lIdentifier == rIdentifier && lExpression == rExpression
}
}
extension Statement: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self {
case .binding(let identifier, let expression):
return "let \(identifier) = \(expression)"
}
}
public var debugDescription: String {
switch self {
case .binding(let identifier, let expression):
return "Statement.binding(\(identifier), \(expression))"
}
}
}
| mit | 1c2f4d26f29ee381076830012b22e7fa | 25.810811 | 98 | 0.650202 | 4.44843 | false | false | false | false |
Wolkabout/WolkSense-Hexiwear- | iOS/Hexiwear/ForgotPasswordViewController.swift | 1 | 3616 | //
// Hexiwear application is used to pair with Hexiwear BLE devices
// and send sensor readings to WolkSense sensor data cloud
//
// Copyright (C) 2016 WolkAbout Technology s.r.o.
//
// Hexiwear 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.
//
// Hexiwear 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/>.
//
//
// ForgotPasswordViewController.swift
//
import UIKit
protocol ForgotPasswordDelegate {
func didFinishResettingPassword()
}
class ForgotPasswordViewController: SingleTextViewController {
var forgotPasswordDelegate: ForgotPasswordDelegate?
@IBOutlet weak var emailText: UITextField!
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
skipButton.title = "Done"
actionButton.title = "Reset"
emailText.delegate = self
emailText.text = ""
title = "Reset password"
errorLabel.isHidden = true
}
override func toggleActivateButtonEnabled() {
if let em = emailText.text, isValidEmailAddress(em) {
actionButton.isEnabled = true
}
else {
actionButton.isEnabled = false
}
}
override func actionButtonAction() {
dataStore.resetPasswordForUserEmail(emailText.text!,
onFailure: handleResetFail(reason:),
onSuccess: {
showSimpleAlertWithTitle(applicationTitle, message: "Check your email for new password.", viewController: self, OKhandler: { _ in self.forgotPasswordDelegate?.didFinishResettingPassword()
})
}
)
}
func handleResetFail(reason: Reason) {
switch reason {
case .noSuccessStatusCode(let statusCode, _):
guard statusCode != BAD_REQUEST && statusCode != NOT_AUTHORIZED else {
DispatchQueue.main.async {
showSimpleAlertWithTitle(applicationTitle, message: "There is no account registered with provided email.", viewController: self)
self.view.setNeedsDisplay()
}
return
}
fallthrough
default:
DispatchQueue.main.async {
showSimpleAlertWithTitle(applicationTitle, message: "There was a problem resetting your password. Please try again or contact our support.", viewController: self)
self.view.setNeedsDisplay()
}
}
}
override func skipButtonAction() {
forgotPasswordDelegate?.didFinishResettingPassword()
}
@IBAction func emailChanged(_ sender: UITextField) {
toggleActivateButtonEnabled()
errorLabel.isHidden = true
self.view.setNeedsDisplay()
}
}
extension ForgotPasswordViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| gpl-3.0 | fb985053aa9d2a2070a06bbf7e9f27d3 | 34.106796 | 235 | 0.628595 | 5.357037 | false | false | false | false |
JamieScanlon/AugmentKit | AugmentKit/AKCore/Primatives/AKWorldLocation.swift | 1 | 9819 | //
// AKWorldLocation.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 simd
import CoreLocation
// MARK: - AKWorldLocation
/**
AKWorldLocation is a protocol that ties together a position in the AR world with a locaiton in the real world. When the `ARKit` session starts up, it crates an arbitrary coordinate system where the origin is where the device was located at the time of initialization. Every device and every AR session, therefore, has it's own local coordinate system. In order to reason about how the coordinate system relates to actual locations in the real world, AugmentKit uses location services to map a point in the `ARKit` coordinate system to a latitude and longitude in the real world and stores this as a `AKWorldLocation` instance. Once a reliable `AKWorldLocation` is found, other `AKWorldLocation` objects can be derived by calculating their relative distance from the one reliable reference AKWorldLocation object.
*/
public protocol AKWorldLocation {
/**
A latitude in the the real world
*/
var latitude: Double { get set }
/**
A longitude in the the real world
*/
var longitude: Double { get set }
/**
An elevation in the the real world
*/
var elevation: Double { get set }
/**
A transform, in the coodinate space of the AR eorld, which corresponds to the `latitude`, `longitude`, and `elevation`
*/
var transform: matrix_float4x4 { get set }
}
// MARK: - WorldLocation
/**
A standard implementaion of AKWorldLocation that provides common initializers that make it easy to derive latitude, longitude, and elevation relative to a reference locatio
*/
public struct WorldLocation: AKWorldLocation {
/**
A latitude in the the real world
*/
public var latitude: Double = 0
/**
A longitude in the the real world
*/
public var longitude: Double = 0
/**
An elevation in the the real world
*/
public var elevation: Double = 0
/**
A transform, in the coodinate space of the AR world, which corresponds to the `latitude`, `longitude`, and `elevation`
*/
public var transform: matrix_float4x4 = matrix_identity_float4x4
/**
Initialize a new structure with a `transform`, a `latitude`, `longitude`, and `elevation`
- Parameters:
- transform: A transform, in the coodinate space of the AR world, which corresponds to the `latitude`, `longitude`, and `elevation`
- latitude: A latitude in the the real world
- longitude: A longitude in the the real world
- elevation: An elevation in the the real world
*/
public init(transform: matrix_float4x4 = matrix_identity_float4x4, latitude: Double = 0, longitude: Double = 0, elevation: Double = 0) {
self.transform = transform
self.latitude = latitude
self.longitude = longitude
self.elevation = elevation
}
/**
Initialize a new structure with a `transform` and a `referenceLocation`.
This uses the `transform`, `latitude`, `longitude`, and `elevation` of the `referenceLocation` to calculate the new `AKWorldLocation`.
The meters/ºlatitude and meters/ºlongitude change with lat/lng. The `referenceLocation` is used to determine these values so the further the destination is from the reference location, the less accurate the resulting calculation is. It's usually fine unless you need very accuate calculations when the locations are tens or hundreds of km away.
- Parameters:
- transform: A transform of the new location in the coodinate space of the AR world
- referenceLocation: Another `AKWorldLocation` which contains reliable `transform`, `latitude`, `longitude`, and `elevation` properties.
*/
public init(transform: matrix_float4x4, referenceLocation: AKWorldLocation) {
self.transform = transform
let metersPerDegreeLatitude = AKLocationUtility.metersPerDegreeLatitude(at: referenceLocation.latitude)
let metersPerDegreeLongitude = AKLocationUtility.metersPerDegreeLongitude(at: referenceLocation.latitude)
let Δz = transform.columns.3.z - referenceLocation.transform.columns.3.z
let Δx = transform.columns.3.x - referenceLocation.transform.columns.3.x
let Δy = transform.columns.3.y - referenceLocation.transform.columns.3.y
self.latitude = referenceLocation.latitude + Double(Δz) / metersPerDegreeLatitude
self.longitude = referenceLocation.longitude + Double(Δx) / metersPerDegreeLongitude
self.elevation = referenceLocation.elevation + Double(Δy)
}
/**
Initializes a new structure with a `latitude`, `longitude`, and `elevation` and a `referenceLocation`.
This uses the `transform`, `latitude`, `longitude`, and `elevation` of the `referenceLocation` to calculate the new `AKWorldLocation`.
- Parameters:
- latitude: A latitude of the new location in the the real world
- longitude: A longitude of the new location in the the real world
- elevation: An elevation of the new location in the the real world
- referenceLocation: Another `AKWorldLocation` which contains reliable `transform`, `latitude`, `longitude`, and `elevation` properties.
*/
public init(latitude: Double, longitude: Double, elevation: Double = 0, referenceLocation: AKWorldLocation) {
self.latitude = latitude
self.longitude = longitude
self.elevation = elevation
let Δy = elevation - referenceLocation.elevation
let latSign: Double = {
if latitude < referenceLocation.latitude {
return 1
} else {
return -1
}
}()
let lngSign: Double = {
if longitude < referenceLocation.longitude {
return -1
} else {
return 1
}
}()
let clLocation1 = CLLocation(latitude: referenceLocation.latitude, longitude: referenceLocation.longitude)
let ΔzLocation = CLLocation(latitude: latitude, longitude: referenceLocation.longitude)
let ΔxLocation = CLLocation(latitude: referenceLocation.latitude, longitude: longitude)
let Δz = latSign * clLocation1.distance(from: ΔzLocation)
let Δx = lngSign * clLocation1.distance(from: ΔxLocation)
self.transform = referenceLocation.transform.translate(x: Float(Δx), y: Float(Δy), z: Float(Δz))
}
}
// MARK: - WorldLocation
/**
An implementation of `AKWorldLocation` that sets the y (vertical) position of an existing locaiton equal to the estimated ground of the world. This is useful when placing objects in the AR world that rest on the ground.
In order to to get the y value of the estimated ground, a reference to and `AKWorld` object is required.
*/
public struct GroundFixedWorldLocation: AKWorldLocation {
/**
Latitude
*/
public var latitude: Double = 0
/**
Longitude
*/
public var longitude: Double = 0
/**
Elevation
*/
public var elevation: Double = 0
/**
A weak reference to the `AKWorld`
*/
public weak var world: AKWorld?
/**
A transform in the coodinate space of the AR world. The provided value gets mutated so that the y value corresponds to the y value of the estimated ground layer as provided by the `world`
*/
public var transform: matrix_float4x4 {
get {
var convertedTransform = originalTransform
guard let worldGroundTransform = world?.estimatedGroundLayer.worldLocation.transform else {
return convertedTransform
}
convertedTransform.columns.3.y = worldGroundTransform.columns.3.y
return convertedTransform
}
set {
originalTransform = newValue
}
}
/**
Initializes a new structure with a `AKWorldLocation` and a reference to a `AKWorld` object
- Parameters:
- worldLocation: An existing `AKWorldLocation`
- world: A reference the the `AKWorld`
*/
public init(worldLocation: AKWorldLocation, world: AKWorld) {
self.originalTransform = worldLocation.transform
self.world = world
self.latitude = worldLocation.latitude
self.longitude = worldLocation.longitude
self.elevation = world.estimatedGroundLayer.worldLocation.elevation
}
// MARK: - Private
fileprivate var originalTransform: matrix_float4x4
}
| mit | 0614d51dd13e96b429f37231d8a5c62c | 41.986842 | 813 | 0.683706 | 4.623113 | false | false | false | false |
rpcarson/mtg-sdk-swift | MTGSDKSwift/MagicalCardManager.swift | 1 | 6280 | //
// MagicalCardManager.swift
// MTGSDKSwift
//
// Created by Reed Carson on 3/1/17.
// Copyright © 2017 Reed Carson. All rights reserved.
//
import UIKit
final public class Magic {
public init() {}
public typealias CardImageCompletion = (UIImage?, NetworkError?) -> Void
public typealias CardCompletion = ([Card]?, NetworkError?) -> Void
public typealias SetCompletion = ([CardSet]?, NetworkError?) -> Void
public static var enableLogging: Bool = false
public var fetchPageSize: String = "12"
public var fetchPageTotal: String = "1"
private let mtgAPIService = MTGAPIService()
private var urlManager: URLManager {
let urlMan = URLManager()
urlMan.pageTotal = fetchPageTotal
urlMan.pageSize = fetchPageSize
return urlMan
}
private let parser = Parser()
/**
Fetch JSON returns the raw json data rather than an Array of Card or CardSet. It will return json for sets or cards depending on what you feed it
- parameter parameters: either [CardSearchParameter] or [SetSearchParameter]
- parameter completion: ([String:Any]?, NetworkError?) -> Void
*/
public func fetchJSON(_ parameters: [SearchParameter], completion: @escaping JSONCompletionWithError) {
var networkError: NetworkError? {
didSet {
completion(nil, networkError)
}
}
guard let url = urlManager.buildURL(parameters: parameters) else {
networkError = NetworkError.miscError("fetchJSON url build failed")
return
}
mtgAPIService.mtgAPIQuery(url: url) {
json, error in
if let error = error {
networkError = NetworkError.requestError(error)
return
}
completion(json, nil)
}
}
/**
Retreives a UIImage based on the imageURL of the Card passed in
- parameter card: Card
- parameter completion: (UIImage?, NetworkError?) -> Void
*/
public func fetchImageForCard(_ card: Card, completion: @escaping CardImageCompletion) {
var networkError: NetworkError? {
didSet {
completion(nil, networkError)
}
}
guard let imgurl = card.imageUrl else {
networkError = NetworkError.fetchCardImageError("fetchImageForCard card imageURL was nil")
return
}
guard let url = URL(string: imgurl) else {
networkError = NetworkError.fetchCardImageError("fetchImageForCard url build failed")
return
}
do {
let data = try Data(contentsOf: url)
if let img = UIImage(data: data) {
completion(img, nil)
} else {
networkError = NetworkError.fetchCardImageError("could not create uiimage from data")
}
} catch {
networkError = NetworkError.fetchCardImageError("data from contents of url failed")
}
}
/**
Reteives an array of CardSet which matches the parameters given
- parameter parameters: [SetSearchParameter]
- parameter completion: ([CardSet]?, NetworkError?) -> Void
*/
public func fetchSets(_ parameters: [SetSearchParameter], completion: @escaping SetCompletion) {
var networkError: NetworkError? {
didSet {
completion(nil, networkError)
}
}
if let url = urlManager.buildURL(parameters: parameters) {
mtgAPIService.mtgAPIQuery(url: url) {
json, error in
if error != nil {
networkError = error
return
}
let sets = self.parser.parseSets(json: json!)
completion(sets, nil)
}
} else {
networkError = NetworkError.miscError("fetchSets url build failed")
}
}
/**
Reteives an array of Cards which match the parameters given
- parameter parameters: [CardSearchParameter]
- parameter completion: ([Card]?, NetworkError?) -> Void
*/
public func fetchCards(_ parameters: [CardSearchParameter], completion: @escaping CardCompletion) {
var networkError: NetworkError? {
didSet {
completion(nil, networkError)
}
}
if let url = urlManager.buildURL(parameters: parameters) {
mtgAPIService.mtgAPIQuery(url: url) {
json, error in
if error != nil {
networkError = error
return
}
let cards = self.parser.parseCards(json: json!)
completion(cards, nil)
}
} else {
networkError = NetworkError.miscError("fetchCards url build failed")
}
}
/**
This function simulates opening a booster pack for the given set, producing an array of [Card]
- parameter setCode: String: the set code of the desired set
- parameter completion: ([Card]?, NetworkError?) -> Void
*/
public func generateBoosterForSet(_ setCode: String, completion: @escaping CardCompletion) {
var networkError: NetworkError? {
didSet {
completion(nil, networkError)
}
}
let endpoint = "https://api.magicthegathering.io/v1/sets/"
let fullURLString = endpoint + setCode + "/booster"
guard let url = URL(string: fullURLString) else {
networkError = NetworkError.miscError("generateBooster - build url fail")
return
}
mtgAPIService.mtgAPIQuery(url: url) {
json, error in
if let error = error {
networkError = error
return
}
let cards = self.parser.parseCards(json: json!)
completion(cards, nil)
}
}
}
| mit | 8599b831443820bc413a18d02f5e804a | 29.333333 | 150 | 0.552795 | 5.280908 | false | false | false | false |
tavon321/FoodApp | FoodApp/Services.swift | 1 | 3134 | //
// Services.swift
// TODO
//
// Created by Luis F Ruiz Arroyave on 11/3/16.
// Copyright © 2016 UdeM. All rights reserved.
//
import Foundation
import Alamofire
typealias CompletionHandler = (success:Bool, response:[String: AnyObject]) -> ()
struct Services {
static func tasks(completionHandler:CompletionHandler) {
let urlString = kBaseUrl + kAppIDKenvey + ktasks
Alamofire.request(.GET, urlString, headers: headers).validate()
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
completionHandler(success:true, response: ["response": value])
}
case .Failure(let error):
completionHandler(success:false, response: ["error": error])
}
}
}
static func save(task:[String: AnyObject], completionHandler:CompletionHandler) {
let urlString = kBaseUrl + kAppIDKenvey + ktasks
Alamofire.request(.POST, urlString, parameters: task, headers: headers).validate()
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
completionHandler(success:true, response: ["response": value])
}
case .Failure(let error):
completionHandler(success:false, response: ["error": error])
}
}
}
static func update(task:[String: AnyObject], completionHandler:CompletionHandler) {
let urlString = kBaseUrl + kAppIDKenvey + ktasks + "\(task["_id"])"
Alamofire.request(.PUT, urlString, parameters: task, headers: headers).validate()
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
completionHandler(success:true, response: ["response": value])
}
case .Failure(let error):
completionHandler(success:false, response: ["error": error])
}
}
}
static func delete(task:[String: AnyObject], completionHandler:CompletionHandler) {
let urlString = kBaseUrl + kAppIDKenvey + ktasks + "\((task["_id"])!)"
Alamofire.request(.DELETE, urlString, parameters: task, headers: headers).validate()
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
completionHandler(success:true, response: ["response": value])
}
case .Failure(let error):
completionHandler(success:false, response: ["error": error])
}
}
}
}
| mit | 9fe2f86970e7763170942b49d2925bce | 34.202247 | 92 | 0.523779 | 5.535336 | false | false | false | false |
rlisle/Patriot-iOS | Patriot/InteractiveTransition.swift | 1 | 1404 | //
// Interactor.swift
// Patriot
//
// Created by Ron Lisle on 5/29/17.
// Copyright © 2017 Ron Lisle. All rights reserved.
//
import UIKit
class InteractiveTransition: UIPercentDrivenInteractiveTransition
{
var interactionInProgress = false // was hasStarted
var shouldCompleteTransition = false // was shouldfinish
private weak var viewController: UIViewController!
func wireToViewController(viewController: UIViewController!)
{
self.viewController = viewController
}
func handleGesture(gestureRecognizer: UIScreenEdgePanGestureRecognizer)
{
let translation = gestureRecognizer.translation(in: gestureRecognizer.view!.superview!)
var progress = (translation.x / 300)
progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))
switch gestureRecognizer.state {
case .began: // handled in VC
interactionInProgress = true
viewController.dismiss(animated: true, completion: nil)
case .changed:
shouldCompleteTransition = progress > 0.5
update(progress)
case .cancelled:
interactionInProgress = false
cancel()
case .ended:
interactionInProgress = false
if !shouldCompleteTransition {
cancel()
} else {
finish()
}
default:
print("Unsupported")
}
}
}
| bsd-3-clause | 1d2e8d215c66b30c6ec85e27c9d6eed9 | 24.053571 | 95 | 0.646472 | 5.215613 | false | false | false | false |
egouletlang/ios-BaseUtilityClasses | BaseUtilityClasses/Extension/CGColor_EXT.swift | 1 | 1461 | //
// CGColor_EXT.swift
// Bankroll
//
// Created by Etienne Goulet-Lang on 5/25/16.
// Copyright © 2016 Etienne Goulet-Lang. All rights reserved.
//
import Foundation
import CoreGraphics
public extension CGColor {
public func toRGB() -> UIColorRGB {
let components = self.components
let red = Int((components?[0])! * 255)
let green = Int((components?[1])! * 255)
let blue = Int((components?[2])! * 255)
return Int64((red<<16) | (green<<8) | (blue))
}
public func toColorComponents() -> [CGFloat] {
let components = self.components
return [
CGFloat(components![0]),
CGFloat(components![1]),
CGFloat(components![2]),
CGFloat(components![3])
]
}
public func toRGBString(_ prefixWithHash: Bool = true) -> String {
let components = self.components
var r = NSString(format: "%X", UInt((components?[0])! * 255))
var g = NSString(format: "%X", UInt((components?[1])! * 255))
var b = NSString(format: "%X", UInt((components?[2])! * 255))
if r.length == 1 {r = NSString(string: "0" + (r as String)) }
if g.length == 1 {g = NSString(string: "0" + (g as String)) }
if b.length == 1 {b = NSString(string: "0" + (b as String)) }
return (prefixWithHash ? "#" : "") + (r as String) + (g as String) + (b as String)
}
}
| mit | de8ff69bde878d1160363db76f64cd4c | 30.73913 | 90 | 0.539041 | 3.802083 | false | false | false | false |
tensorflow/swift-models | Examples/GPT2-Inference/UI/macOS/main.swift | 1 | 5262 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AppKit
import Dispatch
import Foundation
import TextModels
internal class NSLabel: NSTextField {
public override init(frame: NSRect) {
super.init(frame: frame)
self.drawsBackground = false
self.isBezeled = false
self.isEditable = false
self.isSelectable = false
}
public required init?(coder: NSCoder) {
fatalError("init?(coder:) not implemented")
}
}
internal extension NSLabel {
convenience init(frame: NSRect, title: String) {
self.init(frame: frame)
self.stringValue = title
}
}
internal extension NSButton {
convenience init(frame: NSRect, title: String) {
self.init(frame: frame)
self.title = title
}
var text: String {
get { return self.stringValue }
set { self.stringValue = newValue }
}
}
internal extension NSTextField {
var text: String {
get { return self.stringValue }
set { self.stringValue = newValue }
}
}
internal extension NSTextView {
var text: String {
get { return self.string }
set { self.string = newValue }
}
}
internal extension NSSlider {
var value: Double {
get { return self.doubleValue }
set { self.doubleValue = newValue }
}
}
func onMain(_ body: @escaping () -> ()) {
if Thread.isMainThread {
body()
} else {
DispatchQueue.main.async { body() }
}
}
func onBackground(_ body: @escaping () -> ()) {
DispatchQueue.global(qos: .background).async { body() }
}
class SwiftApplicationDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow =
NSWindow(contentRect: NSRect(x: 0, y: 0, width: 648, height: 432),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
defer: false)
lazy var input: NSTextField =
NSTextField(frame: NSRect(x: 24, y: 392, width: 512, height: 20))
lazy var button: NSButton =
NSButton(frame: NSRect(x: 544, y: 386, width: 72, height: 32),
title: "Generate")
lazy var output: NSTextView =
NSTextView(frame: NSRect(x: 24, y: 128, width: 512, height: 256))
lazy var slider: NSSlider =
NSSlider(frame: NSRect(x: 24, y: 100, width: 512, height: 32))
lazy var label: NSLabel =
NSLabel(frame: NSRect(x: 24, y: 60, width: 512, height: 20),
title: "Loading GPT-2 ...")
var gpt: GPT2?
func applicationDidFinishLaunching(_ notification: Notification) {
self.slider.minValue = 0.0
self.slider.maxValue = 1.0
self.slider.value = 0.5
self.window.contentView?.addSubview(self.input)
self.window.contentView?.addSubview(self.button)
let view: NSScrollView = NSScrollView(frame: self.output.frame)
view.hasVerticalScroller = true
view.hasHorizontalScroller = true
view.documentView = self.output
self.output.textContainer?.widthTracksTextView = false
self.window.contentView?.addSubview(view)
// self.window.contentView?.addSubview(self.output)
self.window.contentView?.addSubview(self.slider)
self.window.contentView?.addSubview(self.label)
let ComicSansMS: NSFont = NSFont(name: "Comic Sans MS", size: 10)!
self.input.font = ComicSansMS
self.input.stringValue = "Introducing Swift for TensorFlow on macOS"
self.label.font = ComicSansMS
self.output.font = ComicSansMS
self.output.isEditable = false
self.button.target = self
self.button.action = #selector(generate)
onBackground {
do {
self.gpt = try GPT2()
onMain { self.label.text = "GPT-2 ready!" }
} catch {
onMain { self.label.text = "GPT-2 Construction Failure" }
}
}
self.window.makeKeyAndOrderFront(nil)
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication)
-> Bool {
return true
}
}
extension SwiftApplicationDelegate {
@objc
func generate() {
guard let gpt = self.gpt else { return }
output.text = input.text
if !input.text.isEmpty {
gpt.seed = gpt.embedding(for: input.text)
}
gpt.temperature = Float(self.slider.value)
onBackground {
for _ in 0 ..< 256 {
do {
let word: String = try gpt.generate()
onMain {
self.output.text = self.output.text + word
let range: NSRange =
NSRange(location: self.output.text.count - 1, length: 1)
self.output.scrollRangeToVisible(range)
}
} catch {
continue
}
}
}
}
}
let delegate: SwiftApplicationDelegate = SwiftApplicationDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
| apache-2.0 | 6c0469bcb2fdb9d0e1965027af87e359 | 26.549738 | 79 | 0.662296 | 4.007616 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/Sequence.swift | 1 | 22751 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Encapsulates iteration state and interface for iteration over a
/// sequence.
///
/// - Note: While it is safe to copy an iterator, advancing one
/// copy may invalidate the others.
///
/// Any code that uses multiple iterators (or `for`...`in` loops)
/// over a single sequence should have static knowledge that the
/// specific sequence is multi-pass, either because its concrete
/// type is known or because it is constrained to `CollectionType`.
/// Also, the iterators must be obtained by distinct calls to the
/// sequence's `makeIterator()` method, rather than by copying.
public protocol IteratorProtocol {
/// The type of element traversed by `self`.
associatedtype Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`. Specific implementations of this protocol
/// are encouraged to respond to violations of this requirement by
/// calling `preconditionFailure("...")`.
@warn_unused_result
mutating func next() -> Element?
}
/// A type that can be iterated with a `for`...`in` loop.
///
/// `Sequence` makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. To
/// ensure non-destructive iteration, constrain your sequence to
/// `Collection`.
///
/// As a consequence, it is not possible to run multiple `for` loops
/// on a sequence to "resume" iteration:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // Not guaranteed to continue from the next element.
/// }
///
/// `Sequence` makes no requirement about the behavior in that
/// case. It is not correct to assume that a sequence will either be
/// "consumable" and will resume iteration, or that a sequence is a
/// collection and will restart iteration from the first element.
/// A conforming sequence that is not a collection is allowed to
/// produce an arbitrary sequence of elements from the second iterator.
public protocol Sequence {
//@available(*, unavailable, renamed="Iterator")
//typealias Generator = ()
/// A type that provides the *sequence*'s iteration interface and
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator : IteratorProtocol
// FIXME: should be constrained to Sequence
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
/// A type that represents a subsequence of some of the elements.
associatedtype SubSequence
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@warn_unused_result
func makeIterator() -> Iterator
/// Returns a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
var underestimatedCount: Int { get }
/// Returns an `Array` containing the results of mapping `transform`
/// over `self`.
///
/// - Complexity: O(N).
@warn_unused_result
func map<T>(
@noescape transform: (Iterator.Element) throws -> T
) rethrows -> [T]
/// Returns an `Array` containing the elements of `self`,
/// in order, that satisfy the predicate `includeElement`.
@warn_unused_result
func filter(
@noescape includeElement: (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element]
/// Call `body` on each element in `self` in the same order as a
/// *for-in loop.*
///
/// sequence.forEach {
/// // body code
/// }
///
/// is similar to:
///
/// for element in sequence {
/// // body code
/// }
///
/// - Note: You cannot use the `break` or `continue` statement to exit the
/// current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
/// exit from the current call to `body`, not any outer scope, and won't
/// skip subsequent calls.
///
/// - Complexity: O(`self.count`)
func forEach(@noescape body: (Iterator.Element) throws -> Void) rethrows
/// Returns a subsequence containing all but the first `n` elements.
///
/// - Precondition: `n >= 0`
/// - Complexity: O(`n`)
@warn_unused_result
func dropFirst(n: Int) -> SubSequence
/// Returns a subsequence containing all but the last `n` elements.
///
/// - Precondition: `self` is a finite sequence.
/// - Precondition: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
func dropLast(n: Int) -> SubSequence
/// Returns a subsequence, up to `maxLength` in length, containing the
/// initial elements.
///
/// If `maxLength` exceeds `self.count`, the result contains all
/// the elements of `self`.
///
/// - Precondition: `maxLength >= 0`
@warn_unused_result
func prefix(maxLength: Int) -> SubSequence
/// Returns a slice, up to `maxLength` in length, containing the
/// final elements of `s`.
///
/// If `maxLength` exceeds `s.count`, the result contains all
/// the elements of `s`.
///
/// - Precondition: `self` is a finite sequence.
/// - Precondition: `maxLength >= 0`
@warn_unused_result
func suffix(maxLength: Int) -> SubSequence
/// Returns the maximal `SubSequence`s of `self`, in order, that
/// don't contain elements satisfying the predicate `isSeparator`.
///
/// - Parameter maxSplits: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplits + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing *all* the elements of `self` following the
/// last split point.
/// The default value is `Int.max`.
///
/// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// satisfying `isSeparator`.
/// The default value is `true`.
///
/// - Precondition: `maxSplits >= 0`
@warn_unused_result
func split(
maxSplits maxSplits: Int, omittingEmptySubsequences: Bool,
@noescape isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence]
@warn_unused_result
func _customContainsEquatableElement(
element: Iterator.Element
) -> Bool?
/// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and
/// return its result. Otherwise, return `nil`.
func _preprocessingPass<R>(@noescape preprocess: () -> R) -> R?
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Iterator.Element>
/// Copy a Sequence into an array, returning one past the last
/// element initialized.
func _copyContents(initializing ptr: UnsafeMutablePointer<Iterator.Element>)
-> UnsafeMutablePointer<Iterator.Element>
}
/// A default makeIterator() function for `IteratorProtocol` instances that
/// are declared to conform to `Sequence`
extension Sequence
where Self.Iterator == Self, Self : IteratorProtocol {
public func makeIterator() -> Self {
return self
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` iterator before possibly returning the first available element.
///
/// The underlying iterator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already dropped from the underlying sequence.
internal class _DropFirstSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
internal var _iterator: Base
internal let _limit: Int
internal var _dropped: Int
internal init(_iterator: Base, limit: Int, dropped: Int = 0) {
self._iterator = _iterator
self._limit = limit
self._dropped = dropped
}
internal func makeIterator() -> _DropFirstSequence<Base> {
return self
}
internal func next() -> Base.Element? {
while _dropped < _limit {
if _iterator.next() == nil {
_dropped = _limit
return nil
}
_dropped += 1
}
return _iterator.next()
}
internal func dropFirst(n: Int) -> AnySequence<Base.Element> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
return AnySequence(
_DropFirstSequence(
_iterator: _iterator, limit: _limit + n, dropped: _dropped))
}
}
/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` iterator.
///
/// The underlying iterator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already taken from the underlying sequence.
internal class _PrefixSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
internal let _maxLength: Int
internal var _iterator: Base
internal var _taken: Int
internal init(_iterator: Base, maxLength: Int, taken: Int = 0) {
self._iterator = _iterator
self._maxLength = maxLength
self._taken = taken
}
internal func makeIterator() -> _PrefixSequence<Base> {
return self
}
internal func next() -> Base.Element? {
if _taken >= _maxLength { return nil }
_taken += 1
if let next = _iterator.next() {
return next
}
_taken = _maxLength
return nil
}
internal func prefix(maxLength: Int) -> AnySequence<Base.Element> {
return AnySequence(
_PrefixSequence(
_iterator: _iterator,
maxLength: Swift.min(maxLength, self._maxLength),
taken: _taken))
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Sequence
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an `Array` containing the results of mapping `transform`
/// over `self`.
///
/// - Complexity: O(N).
@warn_unused_result
public func map<T>(
@noescape transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)
var iterator = self.makeIterator()
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
/// Returns an `Array` containing the elements of `self`,
/// in order, that satisfy the predicate `includeElement`.
@warn_unused_result
public func filter(
@noescape includeElement: (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element] {
var result = ContiguousArray<Iterator.Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try includeElement(element) {
result.append(element)
}
}
return Array(result)
}
@warn_unused_result
public func suffix(maxLength: Int) -> AnySequence<Iterator.Element> {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
if maxLength == 0 { return AnySequence([]) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into an `Array`
// and return it. This saves memory for sequences particularly longer
// than `maxLength`.
var ringBuffer: [Iterator.Element] = []
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = i.successor() % maxLength
}
}
if i != ringBuffer.startIndex {
return AnySequence(
[ringBuffer[i..<ringBuffer.endIndex], ringBuffer[0..<i]].flatten())
}
return AnySequence(ringBuffer)
}
/// Returns the maximal `SubSequence`s of `self`, in order, that
/// don't contain elements satisfying the predicate `isSeparator`.
///
/// - Parameter maxSplits: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplits + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing *all* the elements of `self` following the
/// last split point.
/// The default value is `Int.max`.
///
/// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// satisfying `isSeparator`.
/// The default value is `true`.
///
/// - Precondition: `maxSplits >= 0`
@warn_unused_result
public func split(
maxSplits maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@noescape isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [AnySequence<Iterator.Element>] {
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [AnySequence<Iterator.Element>] = []
var subSequence: [Iterator.Element] = []
func appendSubsequence() -> Bool {
if subSequence.isEmpty && omittingEmptySubsequences {
return false
}
result.append(AnySequence(subSequence))
subSequence = []
return true
}
if maxSplits == 0 {
// We aren't really splitting the sequence. Convert `self` into an
// `Array` using a fast entry point.
subSequence = Array(self)
appendSubsequence()
return result
}
var hitEnd = false
var iterator = self.makeIterator()
while true {
guard let element = iterator.next() else {
hitEnd = true
break
}
if try isSeparator(element) {
if !appendSubsequence() {
continue
}
if result.count == maxSplits {
break
}
} else {
subSequence.append(element)
}
}
if !hitEnd {
while let element = iterator.next() {
subSequence.append(element)
}
}
appendSubsequence()
return result
}
/// Returns a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
public var underestimatedCount: Int {
return 0
}
public func _preprocessingPass<R>(@noescape preprocess: () -> R) -> R? {
return nil
}
@warn_unused_result
public func _customContainsEquatableElement(
element: Iterator.Element
) -> Bool? {
return nil
}
/// Call `body` on each element in `self` in the same order as a
/// *for-in loop.*
///
/// sequence.forEach {
/// // body code
/// }
///
/// is similar to:
///
/// for element in sequence {
/// // body code
/// }
///
/// - Note: You cannot use the `break` or `continue` statement to exit the
/// current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
/// exit from the current call to `body`, not any outer scope, and won't
/// skip subsequent calls.
///
/// - Complexity: O(`self.count`)
public func forEach(
@noescape body: (Iterator.Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}
extension Sequence where Iterator.Element : Equatable {
/// Returns the maximal `SubSequence`s of `self`, in order, around a
/// `separator` element.
///
/// - Parameter maxSplits: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplits + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing *all* the elements of `self` following the
/// last split point.
/// The default value is `Int.max`.
///
/// - Parameter omittingEmptySubsequences: If `false`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// equal to `separator`.
/// The default value is `true`.
///
/// - Precondition: `maxSplits >= 0`
@warn_unused_result
public func split(
separator separator: Iterator.Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [AnySequence<Iterator.Element>] {
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
isSeparator: { $0 == separator })
}
}
extension Sequence where
SubSequence : Sequence,
SubSequence.Iterator.Element == Iterator.Element,
SubSequence.SubSequence == SubSequence {
/// Returns a subsequence containing all but the first `n` elements.
///
/// - Precondition: `n >= 0`
/// - Complexity: O(`n`)
@warn_unused_result
public func dropFirst(n: Int) -> AnySequence<Iterator.Element> {
precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n))
}
/// Returns a subsequence containing all but the last `n` elements.
///
/// - Precondition: `self` is a finite collection.
/// - Precondition: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
public func dropLast(n: Int) -> AnySequence<Iterator.Element> {
precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= n. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `n` * sizeof(Iterator.Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result: [Iterator.Element] = []
var ringBuffer: [Iterator.Element] = []
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < n {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = i.successor() % n
}
}
return AnySequence(result)
}
@warn_unused_result
public func prefix(maxLength: Int) -> AnySequence<Iterator.Element> {
precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence")
if maxLength == 0 {
return AnySequence(EmptyCollection<Iterator.Element>())
}
return AnySequence(
_PrefixSequence(_iterator: makeIterator(), maxLength: maxLength))
}
}
extension Sequence {
/// Returns a subsequence containing all but the first element.
///
/// - Complexity: O(1)
@warn_unused_result
public func dropFirst() -> SubSequence { return dropFirst(1) }
/// Returns a subsequence containing all but the last element.
///
/// - Precondition: `self` is a finite sequence.
/// - Precondition: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
public func dropLast() -> SubSequence { return dropLast(1) }
}
extension Sequence {
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element> {
var p = UnsafeMutablePointer<Iterator.Element>(ptr)
for x in IteratorSequence(self.makeIterator()) {
p.initialize(with: x)
p += 1
}
return p
}
}
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass a IteratorProtocol through IteratorSequence to give it "Sequence-ness"
/// A sequence built around an iterator of type `Base`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
public struct IteratorSequence<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
/// Construct an instance whose iterator is a copy of `base`.
public init(_ base: Base) {
_base = base
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Base.Element? {
return _base.next()
}
internal var _base: Base
}
@available(*, unavailable, renamed="IteratorProtocol")
public typealias GeneratorType = IteratorProtocol
@available(*, unavailable, renamed="Sequence")
public typealias SequenceType = Sequence
extension Sequence {
@available(*, unavailable, renamed="makeIterator()")
func generate() -> Iterator {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="it became a property 'underestimatedCount'")
func underestimateCount() -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="call 'split(_:omittingEmptySubsequences:isSeparator:)' and invert the 'allowEmptySlices' argument")
func split(maxSplit: Int, allowEmptySlices: Bool,
@noescape isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
fatalError("unavailable function can't be called")
}
}
extension Sequence where Iterator.Element : Equatable {
@available(*, unavailable, message="call 'split(separator:omittingEmptySubsequences:isSeparator:)' and invert the 'allowEmptySlices' argument")
public func split(
separator: Iterator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [AnySequence<Iterator.Element>] {
fatalError("unavailable function can't be called")
}
}
@available(*, unavailable, renamed="IteratorSequence")
public struct GeneratorSequence<Base : IteratorProtocol> {}
| apache-2.0 | 5fbe98d8b2e75c22c1abd96f606ceb9f | 31.972464 | 145 | 0.652411 | 4.33931 | false | false | false | false |
RockyAo/Dictionary | Dictionary/Classes/Home/View/HistoryTableViewCell.swift | 1 | 1699 | //
// HistoryTableViewCell.swift
// Dictionary
//
// Created by Rocky on 2017/5/29.
// Copyright © 2017年 Rocky. All rights reserved.
//
import UIKit
import RxSwift
import Action
class HistoryTableViewCell: UITableViewCell {
let disposeBag = DisposeBag()
@IBOutlet weak var translationLabel: UILabel!
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var collectionButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionButton.rx.tap.asDriver()
.map{ [unowned self] in
return !self.collectionButton.isSelected
}
.drive(collectionButton.rx.isSelected)
.addDisposableTo(disposeBag)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(with item: WordModel,action:Action<WordModel,WordModel>) {
wordLabel.text = item.query
var transString = ""
for item in item.basicTranslation?.explains ?? []{
transString.append(item)
transString.append(" ")
}
translationLabel.text = transString
collectionButton.isSelected = item.selected
var returnData = item
collectionButton.rx.bind(to: action) { [weak self] _ in
returnData.selected = (self?.collectionButton.isSelected)!
return returnData
}
}
}
| agpl-3.0 | 1ba5cf88bb5b49623095de9aeba6a5a5 | 23.941176 | 77 | 0.579009 | 5.155015 | false | false | false | false |
linchaosheng/CSSwiftWB | SwiftCSWB/SwiftCSWB/Class/Home/M/WBUser.swift | 1 | 2820 | //
// WBUser.swift
// SwiftCSWB
//
// Created by LCS on 16/5/4.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
class WBUser: NSObject {
var id : NSNumber?
var screen_name : String?
var profile_image_url : String?
// -1 未认证 0 认证用户 2.3.5 认证企业 220 达人
var verified_type = 0;
// 会员
var mbrank = 0;
var mbtype = 0;
/*
"allow_all_act_msg" = 1;
"allow_all_comment" = 1;
"avatar_hd" = "http://tva3.sinaimg.cn/crop.1.0.1239.1239.1024/99f9e77bjw8f3d39n6gnrj20yi0yfgo7.jpg";
"avatar_large" = "http://tp4.sinaimg.cn/2583291771/180/5756843714/0";
"bi_followers_count" = 255;
"block_app" = 1;
"block_word" = 0;
city = 1000;
class = 1;
"cover_image" = "http://ww3.sinaimg.cn/crop.0.0.920.300/99f9e77bgw1f2jokra5i2j20pk08cglf.jpg";
"cover_image_phone" = "http://ww1.sinaimg.cn/crop.0.0.640.640.640/6d4a0c7cjw1f344owlzy4j20e80e8jt9.jpg";
"created_at" = "Fri Jan 20 17:32:05 +0800 2012";
"credit_score" = 80;
description = "\U6027\U60c5\U51b7\U6de1 \U7231\U7761\U89c9";
domain = "";
"favourites_count" = 355;
"follow_me" = 0;
"followers_count" = 861247;
following = 1;
"friends_count" = 267;
gender = f;
"geo_enabled" = 0;
id = 2583291771;
idstr = 2583291771;
lang = "zh-cn";
location = "\U5176\U4ed6";
mbrank = 6;
mbtype = 12;
name = "\U5357\U7a51";
"online_status" = 0;
"pagefriends_count" = 0;
"profile_image_url" = "http://tp4.sinaimg.cn/2583291771/50/5756843714/0";
"profile_url" = 321887373;
province = 100;
ptype = 0;
remark = "";
"screen_name" = "\U5357\U7a51";
star = 0;
"statuses_count" = 1179;
urank = 34;
url = "";
"user_ability" = 8;
verified = 1;
"verified_contact_email" = "";
"verified_contact_mobile" = "";
"verified_contact_name" = "";
"verified_level" = 3;
"verified_reason" = "\U77e5\U540d\U60c5\U611f\U535a\U4e3b";
"verified_reason_modified" = "";
"verified_reason_url" = "";
"verified_source" = "";
"verified_source_url" = "";
"verified_state" = 0;
"verified_trade" = 1150;
"verified_type" = 0;
weihao = 321887373;
*/
init(dict : [String : AnyObject]){
super.init()
setValuesForKeysWithDictionary(dict)
}
// 对象中的属性和字典不完全匹配的时候要实现该方法,忽略找不到的key
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let keys : [String] = ["id", "screen_name", "profile_image_url", "verified_type", "mbrank", "mbtype"]
let dict = dictionaryWithValuesForKeys(keys)
return ("\(dict)")
}
}
| apache-2.0 | 32cac16502a046d4856ccb2f99db2abe | 26.545455 | 109 | 0.584892 | 2.788344 | false | false | false | false |
ihomway/RayWenderlichCourses | iOS Concurrency with GCD and Operations/iOS Concurrency with GCD and Operations.playground/Sources/Graphics/GradientGenerator.swift | 1 | 2183 | /*
* Copyright (c) 2016 Razeware LLC
*
* 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
func topAndBottomGradient(size: CGSize, clearLocations: [CGFloat] = [0.35, 0.65], innerIntensity: CGFloat = 0.5) -> UIImage {
let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)
let colors = [
.white,
UIColor(white: innerIntensity, alpha: 1.0),
.black,
UIColor(white: innerIntensity, alpha: 1.0),
.white
].map { $0.cgColor }
let colorLocations : [CGFloat] = [0, clearLocations[0], (clearLocations[0] + clearLocations[1]) / 2.0, clearLocations[1], 1]
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceGray(), colors: colors as CFArray, locations: colorLocations)
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: 0, y: size.height)
context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions())
let cgImage = context!.makeImage()
return UIImage(cgImage: cgImage!)
}
| mit | be135b6dcfdeaa40255261fa527c6e19 | 43.55102 | 206 | 0.735685 | 4.238835 | false | false | false | false |
ffried/FFCoreData | Sources/FFCoreData/ManagedObjectContext Observer/MOCObjectsObserver.swift | 1 | 4852 | //
// MOCObjectsObserver.swift
// FFCoreData
//
// Created by Florian Friedrich on 24.1.15.
// Copyright 2015 Florian Friedrich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import struct Foundation.URL
import class CoreData.NSManagedObjectID
import class CoreData.NSManagedObject
import class CoreData.NSManagedObjectContext
#if canImport(os)
import func os.os_log
#else
import func FFFoundation.os_log
#endif
public struct MOCObjectsFilter: MOCObserverFilter {
var objectIDs: Array<NSManagedObjectID> {
didSet {
precondition(!objectIDs.contains(where: \.isTemporaryID),
"FFCoreData: ERROR: Temporary NSManagedObjectIDs set on MOCObjectsObserver! Be sure to only use non-temporary IDs for MOCObservers!")
}
}
private var objectIDURIs: Array<URL> {
objectIDs.map { $0.uriRepresentation() }
}
public init(objectIDs: Array<NSManagedObjectID>) {
self.objectIDs = objectIDs
}
public func include(managedObject: NSManagedObject) -> Bool {
managedObject.obtainPermanentID()
return objectIDURIs.contains(managedObject.objectID.uriRepresentation())
}
}
extension NSManagedObject {
fileprivate final func obtainPermanentID() {
guard !objectID.isTemporaryID else { return }
do {
try managedObjectContext?.obtainPermanentIDs(for: [self])
} catch {
os_log("Could not obtain permanent object id: %@", log: .ffCoreData, type: .error, String(describing: error))
}
}
private var mocObservationMode: MOCObservationMode {
managedObjectContext.map { .singleContext($0) } ?? .allContexts
}
private var mocObjectsFilter: MOCObjectsFilter {
obtainPermanentID()
return MOCObjectsFilter(objectIDs: [objectID])
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public var changes: MOCChanges<MOCObjectsFilter> {
MOCChanges(mode: mocObservationMode, filter: mocObjectsFilter)
}
public func createMOCObjectObserver(fireInitially: Bool = false,
handler: @escaping MOCBlockObserver<MOCObjectsFilter>.Handler) -> MOCBlockObserver<MOCObjectsFilter> {
MOCBlockObserver(mode: mocObservationMode, filter: mocObjectsFilter, fireInitially: fireInitially, handler: handler)
}
#if canImport(Combine)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func publishChanges() -> MOCChangePublisher<MOCObjectsFilter> {
MOCChangePublisher(mode: mocObservationMode, filter: mocObjectsFilter)
}
#endif
}
fileprivate extension MOCObservationMode {
init(contexts: Array<NSManagedObjectContext>) {
if contexts.isEmpty {
self = .allContexts
} else if contexts.count == 1 {
self = .singleContext(contexts[0])
} else {
self = .multipleContexts(contexts)
}
}
}
extension Sequence where Element: NSManagedObject {
private func mocObservationModeAndObjectsFilter() -> (mode: MOCObservationMode, filter: MOCObjectsFilter) {
var contexts = Array<NSManagedObjectContext>()
contexts.reserveCapacity(underestimatedCount)
var objectIDs = Array<NSManagedObjectID>()
objectIDs.reserveCapacity(underestimatedCount)
for obj in self {
obj.obtainPermanentID()
objectIDs.append(obj.objectID)
if let moc = obj.managedObjectContext, !contexts.contains(moc) {
contexts.append(moc)
}
}
return (MOCObservationMode(contexts: contexts), MOCObjectsFilter(objectIDs: objectIDs))
}
public func createMOCObjectsObserver(fireInitially: Bool = false, handler: @escaping MOCBlockObserver<MOCObjectsFilter>.Handler) -> MOCBlockObserver<MOCObjectsFilter> {
let (mode, filter) = mocObservationModeAndObjectsFilter()
return MOCBlockObserver(mode: mode, filter: filter, fireInitially: fireInitially, handler: handler)
}
#if canImport(Combine)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func publishChanges() -> MOCChangePublisher<MOCObjectsFilter> {
let (mode, filter) = mocObservationModeAndObjectsFilter()
return MOCChangePublisher(mode: mode, filter: filter)
}
#endif
}
| apache-2.0 | a6aef40d839d8274f432819270ac29dc | 36.323077 | 172 | 0.691055 | 4.534579 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Tags View/TopicsCollectionView.swift | 2 | 1861 | import Foundation
/// A drop in collection view that will configure the collection view to display the topics chip group:
/// - Overrides the layout to be `ReaderInterestsCollectionViewFlowLayout`
/// - Creates the ReaderTopicCollectionViewCoordinator
/// - Uses the dynamic height collection view class to automatically change its size to the content
///
/// When implementing you can also use the `topicDelegate` to know when the group is expanded/collapsed, or if a topic chip was selected
class TopicsCollectionView: DynamicHeightCollectionView {
var coordinator: ReaderTopicCollectionViewCoordinator?
weak var topicDelegate: ReaderTopicCollectionViewCoordinatorDelegate?
var topics: [String] = [] {
didSet {
coordinator?.topics = topics
}
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
collectionViewLayout = ReaderInterestsCollectionViewFlowLayout()
coordinator = ReaderTopicCollectionViewCoordinator(collectionView: self, topics: topics)
coordinator?.delegate = self
}
func collapse() {
coordinator?.changeState(.collapsed)
}
}
extension TopicsCollectionView: ReaderTopicCollectionViewCoordinatorDelegate {
func coordinator(_ coordinator: ReaderTopicCollectionViewCoordinator, didSelectTopic topic: String) {
topicDelegate?.coordinator(coordinator, didSelectTopic: topic)
}
func coordinator(_ coordinator: ReaderTopicCollectionViewCoordinator, didChangeState: ReaderTopicCollectionViewState) {
topicDelegate?.coordinator(coordinator, didChangeState: didChangeState)
}
}
| gpl-2.0 | b59f13bf18435b2fdda1d454eb0f575f | 36.22 | 136 | 0.740999 | 5.726154 | false | false | false | false |
pawanpoudel/SwiftNews | SwiftNews/ExternalDependencies/Server/ArticleBuilders/GoogleNewsArticleBuilder.swift | 1 | 2274 | class GoogleNewsArticleBuilder : AbstractArticleBuilder {
// MARK: - Creating articles
override func createArticleFromRssEntry(rssEntry: RssEntry) -> Article {
let article = Article()
article.uniqueId = rssEntry.guid
return article
}
// MARK: - Extracting title
private func extractRealTitleFromTitle(title: String) -> String {
if let separatorRange = title.rangeOfString(" - ") {
return title.substringToIndex(separatorRange.startIndex)
}
return title
}
// MARK: - Extracting publisher
private func extractPublisherFromTitle(title: String) -> String? {
if let separatorRange = title.rangeOfString(" - ") {
return title.substringFromIndex(separatorRange.startIndex)
}
return nil
}
// MARK: - Extracting source url
private func sourceUrlFromRssLink(rssLink: String) -> String? {
if let urlComponents = NSURLComponents(string: rssLink),
queryItems = urlComponents.queryItems
{
return extractUrlFromQueryItems(queryItems)
}
return nil
}
private func extractUrlFromQueryItems(queryItems: [AnyObject]) -> String? {
for queryItem in queryItems as! [NSURLQueryItem] {
if queryItem.name == "url" {
return queryItem.value!
}
}
return nil
}
// MARK: - Extracting image url
private func imageUrlFromSummary(summary: String) -> String? {
let document = GDataXMLDocument(HTMLString: summary, error: nil)
let imageNodes = document.nodesForXPath("//img", error: nil)
for imageNode in imageNodes as! [GDataXMLNode] {
return buildImageUrlFromImageNode(imageNode)
}
return nil
}
private func buildImageUrlFromImageNode(imageNode: GDataXMLNode) -> String? {
if let xmlElement = imageNode as? GDataXMLElement,
imageSourceAttribute = xmlElement.attributeForName("src")
{
return "http:".stringByAppendingString(imageSourceAttribute.stringValue())
}
return nil
}
}
| mit | d5360b6b6b733d3ca2d220a2713fdc0c | 28.921053 | 86 | 0.600264 | 5.239631 | false | false | false | false |
Sadmansamee/quran-ios | Quran/GappedAudioPlayerInteractor.swift | 1 | 705 | //
// GappedAudioPlayerInteractor.swift
// Quran
//
// Created by Mohamed Afifi on 5/14/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
class GappedAudioPlayerInteractor: DefaultAudioPlayerInteractor {
weak var delegate: AudioPlayerInteractorDelegate? = nil
let downloader: AudioFilesDownloader
let lastAyahFinder: LastAyahFinder
let player: AudioPlayer
var downloadCancelled: Bool = false
init(downloader: AudioFilesDownloader, lastAyahFinder: LastAyahFinder, player: AudioPlayer) {
self.downloader = downloader
self.lastAyahFinder = lastAyahFinder
self.player = player
self.player.delegate = self
}
}
| mit | 0f1c52585d8d4539474310a92b2bd499 | 23.275862 | 97 | 0.727273 | 4.756757 | false | false | false | false |
CocoaHeadsConference/CHConferenceApp | NSBrazilConf/Views/Home/Feed/MapFeedView.swift | 1 | 1695 | //
// MapFeedView.swift
// NSBrazilConf
//
// Created by Mauricio Cardozo on 10/7/19.
// Copyright © 2019 Cocoaheadsbr. All rights reserved.
//
import SwiftUI
import MapKit
struct MapFeedView: View, FeedViewProtocol {
init?(feedItem: FeedItem) {
guard let item = feedItem as? MapFeedItem else { return nil }
self.feedItem = item
}
var feedItem: MapFeedItem
var body: some View {
Button(action: self.openMap) {
CardView{
VStack(alignment: HorizontalAlignment.leading) {
MapView(location: self.feedItem.location, annotationTitle: self.feedItem.title, span: self.feedItem.span)
VStack(alignment: .leading, spacing: 4) {
Text("\(self.feedItem.title) \(self.feedItem.subtitle)")
.font(.headline)
}
.padding(.leading, 16)
.padding(.bottom, 8)
}
}
}.frame(maxWidth: .infinity, minHeight: 286)
}
func openMap() {
let placemark = MKPlacemark(coordinate: self.feedItem.location)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = self.feedItem.title
mapItem.openInMaps(launchOptions: nil)
}
}
struct MapFeedView_Previews: PreviewProvider {
static var previews: some View {
MapFeedView(feedItem: MapFeedItem(location: CLLocationCoordinate2D(),
span: MKCoordinateSpan(),
title: "CUBO",
subtitle: "Itaú")
).previewDevice(.iPhone11)
}
}
| mit | af40dbb57b744d2bd26f27a06604020f | 31.557692 | 125 | 0.552865 | 4.72905 | false | false | false | false |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorSDK.swift | 1 | 32367 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import JDStatusBarNotification
import PushKit
import SafariServices
import DZNWebViewController
import ReachabilitySwift
@objc open class ActorSDK: NSObject, PKPushRegistryDelegate {
//
// Shared instance
//
fileprivate static let shared = ActorSDK()
public static func sharedActor() -> ActorSDK {
return shared
}
//
// Root Objects
//
//联系人列表
open var contactsList:ARBindedDisplayList!
//#切换根目录通知
public let switchRootController = Notification.Name(rawValue:"rootViewController")
/// Main Messenger object
open var messenger : ACCocoaMessenger!
// Actor Style
public let style = ActorStyle()
/// SDK Delegate
open var delegate: ActorSDKDelegate = ActorSDKDelegateDefault()
/// SDK Analytics
open var analyticsDelegate: ActorSDKAnalytics?
//
// Configuration
//
//webservice地址
open var webserviceIP = "http://61.175.100.14:8004/WebServiceSSO.asmx"
open var param_K = "eagleSoftWebService"
open var ERR_HTTP_REQUEST = "MOA连接出错,请稍后再试,或者联系管理员"
//serviceIP
open var serviceIP = "http://61.175.100.14:8012/ActorServices-Maven/services/ActorService"
/// Server Endpoints
open var endpoints = [
"tcp://61.175.100.14:9070" //"tcp://61.175.100.14:9070" 正式地址 tcp://220.189.207.18:9070 测试地址
] {
didSet {
trustedKeys = []
}
}
/// Trusted Server Keys
open var trustedKeys = [
"508D39F2BBDAB7776172478939362CD5127871B60151E9B86CD6D61AD1A75849".lowercased()
]
/// API ID
open var apiId = 2
/// API Key
open var apiKey = "2ccdc3699149eac0a13926c77ca84e504afd68b4f399602e06d68002ace965a3"
/// Push registration mode
open var autoPushMode = AAAutoPush.afterLogin
/// Push token registration id. Required for sending push tokens
open var apiPushId: Int? = 25
/// Strategy about authentication
open var authStrategy = AAAuthStrategy.usernameOnly
/// Enable phone book import
open var enablePhoneBookImport = true
/// Invitation URL for apps
open var inviteUrl: String = "https://actor.im/dl"
/// Invitation URL for apps
open var invitePrefix: String? = "https://actor.im/join/"
/// Invitation URL for apps
open var invitePrefixShort: String? = "actor.im/join/"
/// Privacy Policy URL
open var privacyPolicyUrl: String? = nil
/// Privacy Policy Text
open var privacyPolicyText: String? = nil
/// Terms of Service URL
open var termsOfServiceUrl: String? = nil
/// Terms of Service Text
open var termsOfServiceText: String? = nil
/// App name
open var appName: String = "Actor"
/// Use background on welcome screen
open var useBackgroundOnWelcomeScreen: Bool? = false
/// Support email
open var supportEmail: String? = nil
/// Support email
open var supportActivationEmail: String? = nil
/// Support account
open var supportAccount: String? = nil
/// Support home page
open var supportHomepage: String? = "http://www.eaglesoft.cn"
/// Support account
open var supportTwitter: String? = "actorapp"
/// Invite url scheme
open var inviteUrlScheme: String? = nil
/// Web Invite Domain host
open var inviteUrlHost: String? = nil
/// Enable voice calls feature
open var enableCalls: Bool = false
/// Enable video calls feature
open var enableVideoCalls: Bool = false
/// Enable custom sound on Groups and Chats
open var enableChatGroupSound: Bool = false
/// Enable experimental features
open var enableExperimentalFeatures: Bool = false
/// Auto Join Groups
open var autoJoinGroups = [String]()
/// Should perform auto join only after first message or contact
open var autoJoinOnReady = true
//
// User Onlines
//
/// Is User online
fileprivate(set) open var isUserOnline = false
/// Disable this if you want manually handle online states
open var automaticOnlineHandling = true
//
// Local Settings
//
// Local Shared Settings
fileprivate static var udStorage = UDPreferencesStorage()
open var isPhotoAutoDownloadGroup: Bool = udStorage.getBoolWithKey("local.photo_download.group", withDefault: true) {
willSet(v) {
ActorSDK.udStorage.putBool(withKey: "local.photo_download.group", withValue: v)
}
}
open var isPhotoAutoDownloadPrivate: Bool = udStorage.getBoolWithKey("local.photo_download.private", withDefault: true) {
willSet(v) {
ActorSDK.udStorage.putBool(withKey: "local.photo_download.private", withValue: v)
}
}
open var isAudioAutoDownloadGroup: Bool = udStorage.getBoolWithKey("local.audio_download.group", withDefault: true) {
willSet(v) {
ActorSDK.udStorage.putBool(withKey: "local.audio_download.group", withValue: v)
}
}
open var isAudioAutoDownloadPrivate: Bool = udStorage.getBoolWithKey("local.audio_download.private", withDefault: true) {
willSet(v) {
ActorSDK.udStorage.putBool(withKey: "local.audio_download.private", withValue: v)
}
}
open var isGIFAutoplayEnabled: Bool = udStorage.getBoolWithKey("local.autoplay_gif", withDefault: true) {
willSet(v) {
ActorSDK.udStorage.putBool(withKey: "local.autoplay_gif", withValue: v)
}
}
//
// Internal State
//
/// Is Actor Started
fileprivate(set) open var isStarted = false
fileprivate var binder = AABinder()
fileprivate var syncTask: UIBackgroundTaskIdentifier?
fileprivate var completionHandler: ((UIBackgroundFetchResult) -> Void)?
// View Binding info
fileprivate(set) open var bindedToWindow: UIWindow!
// Reachability
fileprivate var reachability: Reachability!
public override init() {
// Auto Loading Application name
if let name = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleNameKey)) as? String {
self.appName = name
}
}
open func createActor() {
if isStarted {
return
}
isStarted = true
AAActorRuntime.configureRuntime()
let builder = ACConfigurationBuilder()!
// Api Connections
let deviceKey = UUID().uuidString
let deviceName = UIDevice.current.name
let appTitle = "Actor iOS"
for url in endpoints {
builder.addEndpoint(url)
}
for key in trustedKeys {
builder.addTrustedKey(key)
}
builder.setApiConfiguration(ACApiConfiguration(appTitle: appTitle, withAppId: jint(apiId), withAppKey: apiKey, withDeviceTitle: deviceName, withDeviceId: deviceKey))
// Providers
builder.setPhoneBookProvider(PhoneBookProvider())
builder.setNotificationProvider(iOSNotificationProvider())
builder.setCallsProvider(iOSCallsProvider())
// Stats
builder.setPlatformType(ACPlatformType.ios())
builder.setDeviceCategory(ACDeviceCategory.mobile())
// Locale
for lang in Locale.preferredLanguages {
builder.addPreferredLanguage(lang)
}
// TimeZone
let timeZone = TimeZone.current.identifier
builder.setTimeZone(timeZone)
// AutoJoin
for s in autoJoinGroups {
builder.addAutoJoinGroup(withToken: s)
}
if autoJoinOnReady {
builder.setAutoJoinType(ACAutoJoinType.after_INIT())
} else {
builder.setAutoJoinType(ACAutoJoinType.immediately())
}
// Logs
// builder.setEnableFilesLogging(true)
// Application name
builder.setCustomAppName(appName)
// Config
builder.setPhoneBookImportEnabled(jboolean(enablePhoneBookImport))
builder.setVoiceCallsEnabled(jboolean(enableCalls))
builder.setVideoCallsEnabled(jboolean(enableCalls))
builder.setIsEnabledGroupedChatList(false)
// builder.setEnableFilesLogging(true)
// Creating messenger
messenger = ACCocoaMessenger(configuration: builder.build())
// Configure bubbles
AABubbles.layouters = delegate.actorConfigureBubbleLayouters(AABubbles.builtInLayouters)
checkAppState()
// Bind Messenger LifeCycle
binder.bind(messenger.getGlobalState().isSyncing, closure: { (value: JavaLangBoolean?) -> () in
if value!.booleanValue() {
if self.syncTask == nil {
self.syncTask = UIApplication.shared.beginBackgroundTask(withName: "Background Sync", expirationHandler: { () -> Void in
// print("飞鸟测试----Background Sync")
})
}
} else {
if self.syncTask != nil {
UIApplication.shared.endBackgroundTask(self.syncTask!)
self.syncTask = nil
}
if self.completionHandler != nil {
self.completionHandler!(UIBackgroundFetchResult.newData)
self.completionHandler = nil
}
}
})
// Bind badge counter
binder.bind(Actor.getGlobalState().globalCounter, closure: { (value: JavaLangInteger?) -> () in
if let v = value {
UIApplication.shared.applicationIconBadgeNumber = Int(v.intValue)
} else {
UIApplication.shared.applicationIconBadgeNumber = 0
}
})
// Push registration
if autoPushMode == .fromStart {
requestPush()
}
// Subscribe to network changes
reachability = Reachability()!
if reachability != nil {
reachability.whenReachable = { reachability in
self.messenger.forceNetworkCheck()
// print("飞鸟测试----forceNetworkCheck")
}
do {
try reachability.startNotifier()
// print("飞鸟测试----startNotifier")
} catch {
print("Unable to start Reachability")
}
} else {
print("Unable to create Reachability")
}
}
func didLoggedIn() {
// Push registration
if autoPushMode == .afterLogin {
requestPush()
}
var controller: UIViewController! = delegate.actorControllerAfterLogIn()
if controller == nil {
controller = delegate.actorControllerForStart()
}
if controller == nil {
let tab = AARootTabViewController()
tab.viewControllers = self.getMainNavigations()
if let index = self.delegate.actorRootInitialControllerIndex() {
tab.selectedIndex = index
} else {
tab.selectedIndex = 1
}
if (AADevice.isiPad) {
let splitController = AARootSplitViewController()
splitController.viewControllers = [tab, AANoSelectionViewController()]
controller = splitController
} else {
controller = tab
}
}
bindedToWindow.rootViewController = controller!
}
//
// Push support
//
/// Token need to be with stripped everything except numbers and letters
func pushRegisterToken(_ token: String) {
if !isStarted {
fatalError("Messenger not started")
}
if apiPushId != nil {
messenger.registerApplePush(withApnsId: jint(apiPushId!), withToken: token)
}
}
func pushRegisterKitToken(_ token: String) {
if !isStarted {
fatalError("Messenger not started")
}
if apiPushId != nil {
messenger.registerApplePushKit(withApnsId: jint(apiPushId!), withToken: token)
}
}
fileprivate func requestPush() {
let types: UIUserNotificationType = [.alert, .badge, .sound]
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: types, categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
fileprivate func requestPushKit() {
let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
voipRegistry.delegate = self
voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
}
@objc open func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) {
if (type == PKPushType.voIP) {
let tokenString = "\(credentials.token)".replace(" ", dest: "").replace("<", dest: "").replace(">", dest: "")
pushRegisterKitToken(tokenString)
}
}
@objc open func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenForType type: PKPushType) {
if (type == PKPushType.voIP) {
}
}
@objc open func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
if (type == PKPushType.voIP) {
let aps = payload.dictionaryPayload["aps"] as! [NSString: AnyObject]
if let callId = aps["callId"] as? String {
if let attempt = aps["attemptIndex"] as? String {
Actor.checkCall(jlong(callId)!, withAttempt: jint(attempt)!)
} else {
Actor.checkCall(jlong(callId)!, withAttempt: 0)
}
} else if let seq = aps["seq"] as? String {
Actor.onPushReceived(withSeq: jint(seq)!, withAuthId: 0)
}
}
}
/// Get main navigations with check in delegate for customize from SDK
fileprivate func getMainNavigations() -> [AANavigationController] {
let allControllers = self.delegate.actorRootControllers()
if let all = allControllers {
var mainNavigations = [AANavigationController]()
for controller in all {
mainNavigations.append(AANavigationController(rootViewController: controller))
}
return mainNavigations
} else {
var mainNavigations = [AANavigationController]()
////////////////////////////////////
// Recent dialogs
////////////////////////////////////
if let recentDialogs = self.delegate.actorControllerForDialogs() {
mainNavigations.append(AANavigationController(rootViewController: recentDialogs))
} else {
mainNavigations.append(AANavigationController(rootViewController: AARecentViewController()))
}
////////////////////////////////////
// Contacts
////////////////////////////////////
if let contactsController = self.delegate.actorControllerForContacts() {
mainNavigations.append(AANavigationController(rootViewController: contactsController))
} else {
mainNavigations.append(AANavigationController(rootViewController: ContactsController()))
}
////////////////////////////////////
// Work
////////////////////////////////////
// mainNavigations.append(AANavigationController(rootViewController:WorkController()))
////////////////////////////////////
// Settings
////////////////////////////////////
if let settingsController = self.delegate.actorControllerForSettings() {
mainNavigations.append(AANavigationController(rootViewController: settingsController))
} else {
mainNavigations.append(AANavigationController(rootViewController: AASettingsViewController()))
}
return mainNavigations
}
}
//
// Presenting Messenger
//
open func presentMessengerInWindow(_ window: UIWindow) {
if !isStarted {
fatalError("Messenger not started")
}
self.bindedToWindow = window
if messenger.isLoggedIn() {
if autoPushMode == .afterLogin {
requestPush()
}
var controller: UIViewController! = delegate.actorControllerForStart()
if controller == nil {
let tab = AARootTabViewController()
tab.viewControllers = self.getMainNavigations()
if let index = self.delegate.actorRootInitialControllerIndex() {
tab.selectedIndex = index
} else {
tab.selectedIndex = 1
}
if (AADevice.isiPad) {
let splitController = AARootSplitViewController()
splitController.viewControllers = [tab, AANoSelectionViewController()]
controller = splitController
} else {
controller = tab
}
}
window.rootViewController = controller!
} else {
let controller: UIViewController! = delegate.actorControllerForAuthStart()
if controller == nil {
window.rootViewController = LoginViewController()
} else {
window.rootViewController = controller
}
}
// Bind Status Bar connecting
if !style.statusBarConnectingHidden {
JDStatusBarNotification.setDefaultStyle { (style) -> JDStatusBarStyle? in
style?.progressBarPosition = .navBar
style?.barColor = self.style.statusBarConnectingBgColor
style?.textColor = self.style.statusBarConnectingTextColor
return style
}
dispatchOnUi { () -> Void in
self.binder.bind(self.messenger.getGlobalState().isSyncing, valueModel2: self.messenger.getGlobalState().isConnecting) {
(isSyncing: JavaLangBoolean?, isConnecting: JavaLangBoolean?) -> () in
if isSyncing!.booleanValue() || isConnecting!.booleanValue() {
if isConnecting!.booleanValue() {
// JDStatusBarNotification.show(withStatus: AALocalized("StatusConnecting"))
} else {
// JDStatusBarNotification.show(withStatus: AALocalized("StatusSyncing"))
}
} else {
// JDStatusBarNotification.dismiss()
}
}
}
}
}
open func presentMessengerInNewWindow()
{
// let window = UIWindow(frame: UIScreen.main.bounds)
let window:UIWindow = ((UIApplication.shared.delegate?.window)!)!
presentMessengerInWindow(window)
// window.makeKeyAndVisible()
}
//
// Data Processing
//
/// Handling URL Opening in application
func openUrl(_ url: String) {
if let u = URL(string: url) {
// Handle phone call
if (u.scheme?.lowercased() == "telprompt") {
UIApplication.shared.openURL(u)
return
}
// Handle web invite url
if (u.scheme?.lowercased() == "http" || u.scheme?.lowercased() == "https") && inviteUrlHost != nil {
if u.host == inviteUrlHost {
let token = u.lastPathComponent
joinGroup(token)
return
}
}
// Handle custom scheme invite url
if (u.scheme?.lowercased() == inviteUrlScheme?.lowercased()) {
if (u.host == "invite") {
let token = u.query?.components(separatedBy: "=")[1]
if token != nil {
joinGroup(token!)
return
}
}
if let bindedController = bindedToWindow?.rootViewController {
let alert = UIAlertController(title: nil, message: AALocalized("ErrorUnableToJoin"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: AALocalized("AlertOk"), style: .cancel, handler: nil))
bindedController.present(alert, animated: true, completion: nil)
}
return
}
if (url.isValidUrl()){
if let bindedController = bindedToWindow?.rootViewController {
// Dismiss Old Presented Controller to show new one
if let presented = bindedController.presentedViewController {
presented.dismiss(animated: true, completion: nil)
}
// Building Controller for Web preview
let controller: UIViewController
if #available(iOS 9.0, *) {
controller = SFSafariViewController(url: u)
} else {
controller = AANavigationController(rootViewController: DZNWebViewController(url: u))
}
if AADevice.isiPad {
controller.modalPresentationStyle = .fullScreen
}
// Presenting controller
bindedController.present(controller, animated: true, completion: nil)
} else {
// Just Fallback. Might never happend
UIApplication.shared.openURL(u)
}
}
}
}
/// Handling joining group by token
func joinGroup(_ token: String) {
if let bindedController = bindedToWindow?.rootViewController {
let alert = UIAlertController(title: nil, message: AALocalized("GroupJoinMessage"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: AALocalized("AlertNo"), style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: AALocalized("GroupJoinAction"), style: .default){ (action) -> Void in
AAExecutions.execute(Actor.joinGroupViaLinkCommand(withToken: token), type: .safe, ignore: [], successBlock: { (val) -> Void in
// TODO: Fix for iPad
let groupId = val as! JavaLangInteger
let tabBarController = bindedController as! UITabBarController
let index = tabBarController.selectedIndex
let navController = tabBarController.viewControllers![index] as! UINavigationController
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.group(with: groupId.int32Value)) {
navController.pushViewController(customController, animated: true)
} else {
navController.pushViewController(ConversationViewController(peer: ACPeer.group(with: groupId.int32Value)), animated: true)
}
}, failureBlock: nil)
})
bindedController.present(alert, animated: true, completion: nil)
}
}
/// Tracking page visible
func trackPageVisible(_ page: ACPage) {
analyticsDelegate?.analyticsPageVisible(page)
}
/// Tracking page hidden
func trackPageHidden(_ page: ACPage) {
analyticsDelegate?.analyticsPageHidden(page)
}
/// Tracking event
func trackEvent(_ event: ACEvent) {
analyticsDelegate?.analyticsEvent(event)
}
//
// File System
//
open func fullFilePathForDescriptor(_ descriptor: String) -> String {
return CocoaFiles.pathFromDescriptor(descriptor)
}
//
// Manual Online handling
//
open func didBecameOnline() {
if automaticOnlineHandling {
fatalError("Manual Online handling not enabled!")
}
if !isStarted {
fatalError("Messenger not started")
}
if !isUserOnline {
isUserOnline = true
messenger.onAppVisible()
}
}
open func didBecameOffline() {
if automaticOnlineHandling {
fatalError("Manual Online handling not enabled!")
}
if !isStarted {
fatalError("Messenger not started")
}
if isUserOnline {
isUserOnline = false
messenger.onAppHidden()
}
}
//
// Automatic Online handling
//
func checkAppState() {
if UIApplication.shared.applicationState == .active {
if !isUserOnline {
isUserOnline = true
// Mark app as visible
messenger.onAppVisible()
// Notify Audio Manager about app visiblity change
AAAudioManager.sharedAudio().appVisible()
// Notify analytics about visibilibty change
// Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(true))
// Hack for resync phone book
// Actor.onPhoneBookChanged()
}
} else {
if isUserOnline {
isUserOnline = false
// Notify Audio Manager about app visiblity change
AAAudioManager.sharedAudio().appHidden()
// Mark app as hidden
messenger.onAppHidden()
// Notify analytics about visibilibty change
// Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(false))
}
}
}
open func applicationDidFinishLaunching(_ application: UIApplication) {
if !automaticOnlineHandling || !isStarted {
return
}
checkAppState()
}
open func applicationDidBecomeActive(_ application: UIApplication) {
if !automaticOnlineHandling || !isStarted {
return
}
checkAppState()
}
open func applicationWillEnterForeground(_ application: UIApplication) {
if !automaticOnlineHandling || !isStarted {
return
}
checkAppState()
}
open func applicationDidEnterBackground(_ application: UIApplication) {
if !automaticOnlineHandling || !isStarted {
return
}
checkAppState()
// Keep application running for 40 secs
if messenger.isLoggedIn() {
var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
completitionTask = application.beginBackgroundTask(withName: "Completition", expirationHandler: { () -> Void in
application.endBackgroundTask(completitionTask)
completitionTask = UIBackgroundTaskInvalid
})
// Wait for 40 secs before app shutdown
// DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).asyncAfter(deadline: DispatchTime.now() + Double(Int64(40.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in
// application.endBackgroundTask(completitionTask)
// completitionTask = UIBackgroundTaskInvalid
// }
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).asyncAfter(deadline: DispatchTime.now() + Double(Int64(40.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in
application.endBackgroundTask(completitionTask)
completitionTask = UIBackgroundTaskInvalid
}
}
}
open func applicationWillResignActive(_ application: UIApplication) {
if !automaticOnlineHandling || !isStarted {
return
}
//
// This event is fired when user press power button and lock screeen.
// In iOS power button also cancel ongoint call.
//
// messenger.probablyEndCall()
checkAppState()
}
//
// Handling remote notifications
//
open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if !messenger.isLoggedIn() {
completionHandler(UIBackgroundFetchResult.noData)
return
}
self.completionHandler = completionHandler
}
open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Nothing?
}
open func application(_ application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
requestPushKit()
}
//
// Handling background fetch events
//
open func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if !messenger.isLoggedIn() {
completionHandler(UIBackgroundFetchResult.noData)
return
}
self.completionHandler = completionHandler
}
//
// Handling invite url
//
func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
dispatchOnUi { () -> Void in
self.openUrl(url.absoluteString)
}
return true
}
open func application(_ app: UIApplication, openURL url: URL) -> Bool {
dispatchOnUi { () -> Void in
let URLString:String = url.absoluteString
if URLString.contains("MOAV6path=") && URLString.contains("MOAV6title=")
{
let recentVC = AARecentViewController()
let tempStr = URLString.components(separatedBy: "MOAV6path=").last
let filePath = tempStr?.components(separatedBy: "MOAV6title=").first
let fileTitle = tempStr?.components(separatedBy: "MOAV6title=").last
recentVC.filePath = filePath!
recentVC.fileTitle = fileTitle!
self.bindedToWindow.rootViewController?.navigateDetail(recentVC)
}
else {
self.openUrl(url.absoluteString)
}
}
return true
}
open func application(_ application: UIApplication, handleOpenURL url: URL) -> Bool {
dispatchOnUi { () -> Void in
self.openUrl(url.absoluteString)
}
return true
}
}
public enum AAAutoPush {
case none
case fromStart
case afterLogin
}
public enum AAAuthStrategy {
case phoneOnly
case emailOnly
case phoneEmail
case usernameOnly
}
| agpl-3.0 | a868360290dd7b59af342c2ce93bffe5 | 33.104651 | 212 | 0.566407 | 5.52922 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/Noise/SimplexNoise.swift | 1 | 14640 | //
// SimplexNoise.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/* Copyright (c) 2007-2012 Eliot Eshelman
*
* 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/>.
*
*/
public func SimplexNoise(_ octaves: Int, _ persistence: Double, _ scale: Double, _ x: Double, _ y: Double) -> Double {
var total = 0.0
var frequency = scale
var amplitude = 1.0
var maxAmplitude = 0.0
for _ in 0..<octaves {
total += raw_noise(x * frequency, y * frequency) * amplitude
frequency *= 2
maxAmplitude += amplitude
amplitude *= persistence
}
return 0.5 * total / maxAmplitude + 0.5
}
public func SimplexNoise(_ octaves: Int, _ persistence: Double, _ scale: Double, _ x: Double, _ y: Double, _ z: Double) -> Double {
var total = 0.0
var frequency = scale
var amplitude = 1.0
var maxAmplitude = 0.0
for _ in 0..<octaves {
total += raw_noise(x * frequency, y * frequency, z * frequency) * amplitude
frequency *= 2
maxAmplitude += amplitude
amplitude *= persistence
}
return 0.5 * total / maxAmplitude + 0.5
}
public func SimplexNoise(_ octaves: Int, _ persistence: Double, _ scale: Double, _ x: Double, _ y: Double, _ z: Double, _ w: Double) -> Double {
var total = 0.0
var frequency = scale
var amplitude = 1.0
var maxAmplitude = 0.0
for _ in 0..<octaves {
total += raw_noise(x * frequency, y * frequency, z * frequency, w * frequency) * amplitude
frequency *= 2
maxAmplitude += amplitude
amplitude *= persistence
}
return 0.5 * total / maxAmplitude + 0.5
}
private let perm: [Int] = [
151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,
8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,
35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,
134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,
55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89,
18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,
250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,
189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,
172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,
228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,
107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,
8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,
35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,
134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,
55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89,
18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,
250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,
189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,
172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,
228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,
107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
]
private let grad3: [[Int]] = [
[1,1,0], [-1,1,0], [1,-1,0], [-1,-1,0],
[1,0,1], [-1,0,1], [1,0,-1], [-1,0,-1],
[0,1,1], [0,-1,1], [0,1,-1], [0,-1,-1]
]
private let grad4: [[Int]] = [
[0,1,1,1], [0,1,1,-1], [0,1,-1,1], [0,1,-1,-1],
[0,-1,1,1], [0,-1,1,-1], [0,-1,-1,1], [0,-1,-1,-1],
[1,0,1,1], [1,0,1,-1], [1,0,-1,1], [1,0,-1,-1],
[-1,0,1,1], [-1,0,1,-1], [-1,0,-1,1], [-1,0,-1,-1],
[1,1,0,1], [1,1,0,-1], [1,-1,0,1], [1,-1,0,-1],
[-1,1,0,1], [-1,1,0,-1], [-1,-1,0,1], [-1,-1,0,-1],
[1,1,1,0], [1,1,-1,0], [1,-1,1,0], [1,-1,-1,0],
[-1,1,1,0], [-1,1,-1,0], [-1,-1,1,0], [-1,-1,-1,0]
]
private let simplex: [[Int]] = [
[0,1,2,3],[0,1,3,2],[0,0,0,0],[0,2,3,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,3,0],
[0,2,1,3],[0,0,0,0],[0,3,1,2],[0,3,2,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,3,2,0],
[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[1,2,0,3],[0,0,0,0],[1,3,0,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,3,0,1],[2,3,1,0],
[1,0,2,3],[1,0,3,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,3,1],[0,0,0,0],[2,1,3,0],
[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[2,0,1,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,0,1,2],[3,0,2,1],[0,0,0,0],[3,1,2,0],
[2,1,0,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,1,0,2],[0,0,0,0],[3,2,0,1],[3,2,1,0]
]
private func fastfloor(_ x: Double) -> Int {
return x > 0 ? Int(x) : Int(x - 1)
}
private func dot(_ g: [Int], _ x: Double) -> Double {
return Double(g[0]) * x
}
private func dot(_ g: [Int], _ x: Double, _ y: Double) -> Double {
return Double(g[0]) * x + Double(g[1]) * y
}
private func dot(_ g: [Int], _ x: Double, _ y: Double, _ z: Double) -> Double {
return Double(g[0]) * x + Double(g[1]) * y + Double(g[2]) * z
}
private func dot(_ g: [Int], _ x: Double, _ y: Double, _ z: Double, _ w: Double) -> Double {
return Double(g[0]) * x + Double(g[1]) * y + Double(g[2]) * z + Double(g[3]) * w
}
private func raw_noise(_ x: Double, _ y: Double) -> Double {
let n0, n1, n2: Double
let F2 = 0.5 * (sqrt(3.0) - 1.0)
let s = (x + y) * F2
let i = fastfloor(x + s)
let j = fastfloor(y + s)
let G2 = (3.0 - sqrt(3.0)) / 6.0
let t = Double(i + j) * G2
let X0 = Double(i) - t
let Y0 = Double(j) - t
let x0 = x - X0
let y0 = y - Y0
let i1, j1: Int
if x0>y0 {
i1 = 1
j1 = 0
} else {
i1 = 0
j1 = 1
}
let x1 = x0 - Double(i1) + G2
let y1 = y0 - Double(j1) + G2
let x2 = x0 - 1.0 + 2.0 * G2
let y2 = y0 - 1.0 + 2.0 * G2
let ii = i & 255
let jj = j & 255
let gi0 = perm[ii + perm[jj]] % 12
let gi1 = perm[ii + i1 + perm[jj + j1]] % 12
let gi2 = perm[ii + 1 + perm[jj + 1]] % 12
var t0 = 0.5 - x0 * x0 - y0 * y0
if t0 < 0 {
n0 = 0.0
} else {
t0 *= t0
n0 = t0 * t0 * dot(grad3[gi0], x0, y0)
}
var t1 = 0.5 - x1 * x1 - y1 * y1
if t1 < 0 {
n1 = 0.0
} else {
t1 *= t1
n1 = t1 * t1 * dot(grad3[gi1], x1, y1)
}
var t2 = 0.5 - x2 * x2 - y2 * y2
if t2 < 0 {
n2 = 0.0
} else {
t2 *= t2
n2 = t2 * t2 * dot(grad3[gi2], x2, y2)
}
return 70.0 * (n0 + n1 + n2)
}
private func raw_noise(_ x: Double, _ y: Double, _ z: Double) -> Double {
let n0, n1, n2, n3: Double
let F3 = 1.0 / 3.0
let s = (x + y + z) * F3
let i = fastfloor(x + s)
let j = fastfloor(y + s)
let k = fastfloor(z + s)
let G3 = 1.0 / 6.0
let t = Double(i + j + k) * G3
let X0 = Double(i) - t
let Y0 = Double(j) - t
let Z0 = Double(k) - t
let x0 = x - X0
let y0 = y - Y0
let z0 = z - Z0
let i1, j1, k1: Int
let i2, j2, k2: Int
if x0 >= y0 {
if y0 >= z0 {
(i1, j1, k1) = (1, 0, 0)
(i2, j2, k2) = (1, 1, 0)
} else if x0 >= z0 {
(i1, j1, k1) = (1, 0, 0)
(i2, j2, k2) = (1, 0, 1)
} else {
(i1, j1, k1) = (0, 0, 1)
(i2, j2, k2) = (1, 0, 1)
}
} else {
if y0 < z0 {
(i1, j1, k1) = (0, 0, 1)
(i2, j2, k2) = (0, 1, 1)
} else if x0 < z0 {
(i1, j1, k1) = (0, 1, 0)
(i2, j2, k2) = (0, 1, 1)
} else {
(i1, j1, k1) = (0, 1, 0)
(i2, j2, k2) = (1, 1, 0)
}
}
let x1 = x0 - Double(i1) + G3
let y1 = y0 - Double(j1) + G3
let z1 = z0 - Double(k1) + G3
let x2 = x0 - Double(i2) + 2.0 * G3
let y2 = y0 - Double(j2) + 2.0 * G3
let z2 = z0 - Double(k2) + 2.0 * G3
let x3 = x0 - 1.0 + 3.0 * G3
let y3 = y0 - 1.0 + 3.0 * G3
let z3 = z0 - 1.0 + 3.0 * G3
let ii = i & 255
let jj = j & 255
let kk = k & 255
let gi0 = perm[ii + perm[jj + perm[kk]]] % 12
let gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] % 12
let gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] % 12
let gi3 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] % 12
var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0
if t0 < 0 {
n0 = 0.0
} else {
t0 *= t0
n0 = t0 * t0 * dot(grad3[gi0], x0, y0, z0)
}
var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1
if t1 < 0 {
n1 = 0.0
} else {
t1 *= t1
n1 = t1 * t1 * dot(grad3[gi1], x1, y1, z1)
}
var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2
if t2 < 0 {
n2 = 0.0
} else {
t2 *= t2
n2 = t2 * t2 * dot(grad3[gi2], x2, y2, z2)
}
var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3
if t3 < 0 {
n3 = 0.0
} else {
t3 *= t3
n3 = t3 * t3 * dot(grad3[gi3], x3, y3, z3)
}
return 32.0 * (n0 + n1 + n2 + n3)
}
private func raw_noise(_ x: Double, _ y: Double, _ z: Double, _ w: Double) -> Double {
let F4 = (sqrt(5.0) - 1.0) / 4.0
let G4 = (5.0 - sqrt(5.0)) / 20.0
let n0, n1, n2, n3, n4: Double
let s = (x + y + z + w) * F4
let i = fastfloor(x + s)
let j = fastfloor(y + s)
let k = fastfloor(z + s)
let l = fastfloor(w + s)
let t = Double(i + j + k + l) * G4
let X0 = Double(i) - t
let Y0 = Double(j) - t
let Z0 = Double(k) - t
let W0 = Double(l) - t
let x0 = x - X0
let y0 = y - Y0
let z0 = z - Z0
let w0 = w - W0
let c1 = x0 > y0 ? 32 : 0
let c2 = x0 > z0 ? 16 : 0
let c3 = y0 > z0 ? 8 : 0
let c4 = x0 > w0 ? 4 : 0
let c5 = y0 > w0 ? 2 : 0
let c6 = z0 > w0 ? 1 : 0
let c = c1 + c2 + c3 + c4 + c5 + c6
let i1, j1, k1, l1: Int
let i2, j2, k2, l2: Int
let i3, j3, k3, l3: Int
i1 = simplex[c][0] >= 3 ? 1 : 0
j1 = simplex[c][1] >= 3 ? 1 : 0
k1 = simplex[c][2] >= 3 ? 1 : 0
l1 = simplex[c][3] >= 3 ? 1 : 0
i2 = simplex[c][0] >= 2 ? 1 : 0
j2 = simplex[c][1] >= 2 ? 1 : 0
k2 = simplex[c][2] >= 2 ? 1 : 0
l2 = simplex[c][3] >= 2 ? 1 : 0
i3 = simplex[c][0] >= 1 ? 1 : 0
j3 = simplex[c][1] >= 1 ? 1 : 0
k3 = simplex[c][2] >= 1 ? 1 : 0
l3 = simplex[c][3] >= 1 ? 1 : 0
let x1 = x0 - Double(i1) + G4
let y1 = y0 - Double(j1) + G4
let z1 = z0 - Double(k1) + G4
let w1 = w0 - Double(l1) + G4
let x2 = x0 - Double(i2) + 2.0 * G4
let y2 = y0 - Double(j2) + 2.0 * G4
let z2 = z0 - Double(k2) + 2.0 * G4
let w2 = w0 - Double(l2) + 2.0 * G4
let x3 = x0 - Double(i3) + 3.0 * G4
let y3 = y0 - Double(j3) + 3.0 * G4
let z3 = z0 - Double(k3) + 3.0 * G4
let w3 = w0 - Double(l3) + 3.0 * G4
let x4 = x0 - 1.0 + 4.0 * G4
let y4 = y0 - 1.0 + 4.0 * G4
let z4 = z0 - 1.0 + 4.0 * G4
let w4 = w0 - 1.0 + 4.0 * G4
let ii = i & 255
let jj = j & 255
let kk = k & 255
let ll = l & 255
let gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32
let gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32
let gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32
let gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32
let gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32
var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0
if t0 < 0 {
n0 = 0.0
} else {
t0 *= t0
n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0)
}
var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1
if t1 < 0 {
n1 = 0.0
} else {
t1 *= t1
n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1)
}
var t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2
if t2 < 0 {
n2 = 0.0
} else {
t2 *= t2
n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2)
}
var t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3
if t3 < 0 {
n3 = 0.0
} else {
t3 *= t3
n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3)
}
var t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4
if t4 < 0 {
n4 = 0.0
} else {
t4 *= t4
n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4)
}
return 27.0 * (n0 + n1 + n2 + n3 + n4)
}
| mit | b713d77c147fb8607bb97e946562124c | 31.317881 | 144 | 0.498224 | 2.310241 | false | false | false | false |
jpchmura/JPCDataSourceController | Source/Cells.swift | 1 | 6672 | //
// Cells.swift
// JPCDataSourceController
//
// Created by Jon Chmura on 4/20/15.
// Copyright (c) 2015 Jon Chmura. All rights reserved.
//
//
// Source: https://github.com/jpchmura/JPCDataSourceController
//
// License: MIT ( http://opensource.org/licenses/MIT )
//
import UIKit
public class SubtitleTableViewCell: UITableViewCell {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
public var titleLabel: UILabel = UILabel()
public var subtitleLabel: UILabel = UILabel()
public override var textLabel: UILabel? {
get {
return titleLabel
}
}
public override var detailTextLabel: UILabel? {
get {
return subtitleLabel
}
}
private func setup() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
titleLabel.numberOfLines = 2
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
subtitleLabel.numberOfLines = 0
let views = ["title": titleLabel, "subtitle": subtitleLabel]
self.contentView.addSubview(titleLabel)
self.contentView.addSubview(subtitleLabel)
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[title]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[subtitle]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[title]-[subtitle]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
}
}
public class Value1TableViewCell: UITableViewCell {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value1, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
public class Value2TableViewCell: UITableViewCell {
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value2, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
/**
* A UITableViewCell implementing the EmbeddedCollectionView protocol. It may be vended from a CellFactory for embedded collection views. The default layout is UICollectionViewFlowLayout. You may change this in your factory or extend this cell and override the collectionView property to instianciate with your own layout.
* The embedded collection view layout has it cover the entire cell content view edge to edge.
*/
public class TableViewEmbeddedCell: UITableViewCell, EmbeddedCollectionView {
private var _constraints = [NSLayoutConstraint]()
public var collectionView: UICollectionView? = nil {
didSet {
if collectionView !== oldValue {
oldValue?.removeFromSuperview()
contentView.removeConstraints(_constraints)
_constraints.removeAll()
if let collectionView = collectionView {
collectionView.removeFromSuperview()
self.contentView.addSubview(collectionView)
let views = ["view" : collectionView]
collectionView.translatesAutoresizingMaskIntoConstraints = false
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: [], metrics: nil, views: views)
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: [], metrics: nil, views: views)
contentView.addConstraints(_constraints)
}
}
}
}
/// If true, when asked for intrinsicContentSize this cell will return the contentSize.height of the collection view.
/// This will support self sizing cells for embedded collection views. Default value is true.
public var useContentHeightForIntrinsicSize: Bool = true
public override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
if let collectionView = collectionView where self.useContentHeightForIntrinsicSize {
size.height = collectionView.contentSize.height
}
return size
}
}
/**
* A UICollectionViewCell implementing the EmbeddedCollectionView protocol. It may be vended from a CellFactory for embedded collection views. The default layout is UICollectionViewFlowLayout. You may change this in your factory or extend this cell and override the collectionView property to instianciate with your own layout.
* The embedded collection view layout has it cover the entire cell content view edge to edge.
*/
public class CollectionViewEmbeddedCell: UICollectionViewCell, EmbeddedCollectionView {
private var _constraints = [NSLayoutConstraint]()
public var collectionView: UICollectionView? = nil {
didSet {
if collectionView !== oldValue {
oldValue?.removeFromSuperview()
contentView.removeConstraints(_constraints)
_constraints.removeAll()
if let collectionView = collectionView {
collectionView.removeFromSuperview()
self.contentView.addSubview(collectionView)
let views = ["view" : collectionView]
collectionView.translatesAutoresizingMaskIntoConstraints = false
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: [], metrics: nil, views: views)
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: [], metrics: nil, views: views)
contentView.addConstraints(_constraints)
}
}
}
}
}
| mit | 31304b6a616d3cb030b2ebdf09164c7d | 38.952096 | 330 | 0.652128 | 6.0271 | false | false | false | false |
kevinvanderlugt/Exercism-Solutions | swift/gigasecond/Gigasecond.swift | 1 | 684 | //
// Gigasecond.swift
// exercism-test-runner
//
// Created by Kevin VanderLugt on 3/19/15.
// Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved.
//
import Foundation
struct Gigasecond {
static func from(birthday: String) -> NSDate {
let gigasecond = pow(10.0, 9.0)
var dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
if let birthdate = dateFormatter.dateFromString(birthday) {
return birthdate.dateByAddingTimeInterval(gigasecond)
}
return NSDate.distantFuture() as NSDate
}
} | mit | c4bb4957386bc830bee1afac0830788f | 27.541667 | 67 | 0.654971 | 4.023529 | false | false | false | false |
djflsdl08/BasicIOS | FaceIt/FaceIt/EmotionsViewController.swift | 1 | 1328 | //
// EmotionsViewController.swift
// FaceIt
//
// Created by 김예진 on 2017. 10. 11..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class EmotionsViewController: UIViewController {
private let emotionalFaces : Dictionary <String,FacialExpression> = [
"angry" : FacialExpression(eyes : .Closed, eyeBrows : .Furrowed, mouth : .Frown),
"mischievious" : FacialExpression(eyes : .Open, eyeBrows : .Furrowed, mouth : .Grin),
"worried" : FacialExpression(eyes : .Open, eyeBrows : .Relaxed, mouth : .Smirk),
"happy" : FacialExpression(eyes : .Open, eyeBrows : .Normal, mouth : .Smile)
]
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destinationVC = segue.destination
if let navcon = destinationVC as? UINavigationController {
destinationVC = navcon.visibleViewController ?? destinationVC
}
if let faceVC = destinationVC as? FaceViewController {
if let identifier = segue.identifier {
faceVC.expression = emotionalFaces[identifier]!
if let sendingButton = sender as? UIButton {
faceVC.navigationItem.title = sendingButton.currentTitle
}
}
}
}
}
| mit | 40500a8cf24c1c79161839b7a87018d7 | 33.710526 | 93 | 0.617892 | 4.296417 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Carthage/Checkouts/QuickLayout/Example/QuickLayout/Samples/TableView/ContactTableViewCell.swift | 6 | 2553 | //
// ContactTableViewCell.swift
// QuickLayout_Example
//
// Created by Daniel Huri on 11/21/17.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import QuickLayout
class ContactTableViewCell: UITableViewCell {
// MARK: UI Props
private let thumbView = ThumbView()
private let emailLabel = UILabel()
private let fullNameLabel = UILabel()
private let userNameLabel = UILabel()
var contact: Contact! {
didSet {
userNameLabel.text = contact.userName
emailLabel.text = contact.email
let name = "\(contact.firstName) \(contact.lastName)"
fullNameLabel.text = name
thumbView.name = name
}
}
// MARK: Setup
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setupThumbView()
setupUserNameLabel()
setupFullNameLabel()
setupEmailLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupThumbView() {
contentView.addSubview(thumbView)
thumbView.layoutToSuperview(.top, offset: 16, priority: .must)
thumbView.layoutToSuperview(.left, offset: 16)
thumbView.set(.width, .height, of: 45)
}
private func setupUserNameLabel() {
contentView.addSubview(userNameLabel)
userNameLabel.font = MainFont.medium.with(size: 14)
userNameLabel.layout(.left, to: .right, of: thumbView, offset: 10)
userNameLabel.layout(to: .top, of: thumbView)
userNameLabel.layoutToSuperview(.right, offset: -16)
}
private func setupFullNameLabel() {
contentView.addSubview(fullNameLabel)
fullNameLabel.font = MainFont.light.with(size: 14)
fullNameLabel.layout(to: .left, of: userNameLabel)
fullNameLabel.layout(to: .right, of: userNameLabel)
fullNameLabel.layout(.top, to: .bottom, of: userNameLabel, offset: 5)
}
private func setupEmailLabel() {
contentView.addSubview(emailLabel)
emailLabel.font = MainFont.light.with(size: 12)
emailLabel.layout(to: .left, of: userNameLabel)
emailLabel.layout(to: .right, of: userNameLabel)
emailLabel.layout(.top, to: .bottom, of: fullNameLabel, offset: 5)
emailLabel.layoutToSuperview(.bottom, offset: -16, priority: .must)
}
}
| apache-2.0 | ef6cbe13e792813d734faa655e82d89a | 32.592105 | 79 | 0.645907 | 4.463287 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/TriggersViewController.swift | 1 | 4015 | //
// TriggersViewController.swift
// Outlander
//
// Created by Joseph McBride on 6/9/15.
// Copyright (c) 2015 Joe McBride. All rights reserved.
//
import Cocoa
public class TriggersViewController: NSViewController, SettingsView, NSTableViewDataSource {
@IBOutlet weak var tableView: NSTableView!
private var _context:GameContext?
private var _appSettingsLoader:AppSettingsLoader?
public var selectedItem:Trigger? {
willSet {
self.willChangeValueForKey("selectedItem")
}
didSet {
self.didChangeValueForKey("selectedItem")
}
}
public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool {
if key == "selectedItem" {
return true
} else {
return super.automaticallyNotifiesObserversForKey(key)
}
}
public override func viewDidLoad() {
super.viewDidLoad()
self.tableView.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false)
}
public override func controlTextDidChange(obj: NSNotification) {
if let item = self.selectedItem {
let textField = obj.object as! NSTextField
if(textField.tag == 1) {
item.trigger = textField.stringValue
}
else if(textField.tag == 2) {
item.action = textField.stringValue
} else {
item.actionClass = textField.stringValue
}
self.tableView.reloadData()
}
}
public func save() {
_appSettingsLoader!.saveTriggers()
}
public func setContext(context:GameContext) {
_context = context
_appSettingsLoader = AppSettingsLoader(context: _context)
}
@IBAction func addRemoveAction(sender: NSSegmentedControl) {
if sender.selectedSegment == 0 {
let trigger = Trigger("", "", "")
_context!.triggers.addObject(trigger)
let idx = NSIndexSet(index: _context!.triggers.count() - 1)
self.tableView.reloadData()
self.tableView.selectRowIndexes(idx, byExtendingSelection: false)
self.tableView.scrollRowToVisible(idx.firstIndex)
} else {
if self.tableView.selectedRow < 0 || self.tableView.selectedRow >= _context!.triggers.count() {
return
}
self.selectedItem = nil;
let item:Trigger = _context!.triggers.objectAtIndex(self.tableView.selectedRow) as! Trigger
_context!.triggers.removeObject(item)
self.tableView.reloadData()
}
}
// MARK: NSTableViewDataSource
public func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return _context!.triggers.count()
}
public func tableViewSelectionDidChange(notification:NSNotification) {
let selectedRow = self.tableView.selectedRow
if(selectedRow > -1
&& selectedRow < _context!.triggers.count()) {
self.selectedItem =
_context!.triggers.objectAtIndex(selectedRow) as? Trigger;
}
else {
self.selectedItem = nil;
}
}
public func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if (row >= _context!.triggers.count()){
return "";
}
let item = _context!.triggers.objectAtIndex(row) as! Trigger
var res:String = ""
if(tableColumn!.identifier == "trigger") {
res = item.trigger != nil ? item.trigger! : ""
}
else if(tableColumn!.identifier == "action") {
res = item.action != nil ? item.action! : ""
}
else {
res = item.actionClass != nil ? item.actionClass! : ""
}
return res
}
}
| mit | 122d68647304a74f11099755bdd38596 | 30.614173 | 130 | 0.577335 | 5.221066 | false | false | false | false |
ngageoint/mage-ios | Mage/ObservationActionHandler.swift | 1 | 2894 | //
// ObservationActionHandler.swift
// MAGE
//
// Created by Daniel Barela on 1/28/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
class ObservationActionHandler {
static func getDirections(latitude: CLLocationDegrees, longitude: CLLocationDegrees, title: String, viewController: UIViewController, extraActions: [UIAlertAction]? = nil, sourceView: UIView? = nil) {
let appleMapsQueryString = "daddr=\(latitude),\(longitude)&ll=\(latitude),\(longitude)&q=\(title)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed);
let appleMapsUrl = URL(string: "https://maps.apple.com/?\(appleMapsQueryString ?? "")");
let googleMapsUrl = URL(string: "https://maps.google.com/?\(appleMapsQueryString ?? "")");
let alert = UIAlertController(title: "Navigate With...", message: nil, preferredStyle: .actionSheet);
alert.addAction(UIAlertAction(title: "Apple Maps", style: .default, handler: { (action) in
UIApplication.shared.open(appleMapsUrl!, options: [:]) { (success) in
print("opened? \(success)")
}
}))
alert.addAction(UIAlertAction(title:"Google Maps", style: .default, handler: { (action) in
UIApplication.shared.open(googleMapsUrl!, options: [:]) { (success) in
print("opened? \(success)")
}
}))
if let extraActions = extraActions {
for action in extraActions {
alert.addAction(action);
}
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil));
if let popoverController = alert.popoverPresentationController {
var view: UIView = viewController.view;
if let sourceView = sourceView {
view = sourceView;
} else {
popoverController.permittedArrowDirections = [];
}
popoverController.sourceView = view
popoverController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
}
viewController.present(alert, animated: true, completion: nil);
}
static func deleteObservation(observation: Observation, viewController: UIViewController, callback: ((Bool, Error?)->Void)?) {
let alert = UIAlertController(title: "Delete Observation", message: "Are you sure you want to delete this observation?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes, Delete", style: .destructive , handler:{ (UIAlertAction) in
observation.delete(completion: callback);
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel))
viewController.present(alert, animated: true, completion: nil)
}
}
| apache-2.0 | 003b1113e89b97392a6a21f1f7005d12 | 44.920635 | 204 | 0.62945 | 4.987931 | false | false | false | false |
TheSurfOffice/Foodpic | Foodpic/ViewControllers/MenuItemSwitcherViewController.swift | 1 | 2569 | //
// MenuItemSwitcherViewController.swift
// Foodpic
//
// Created by Leif Gensert on 10/12/14.
// Copyright (c) 2014 Olga Dalton. All rights reserved.
//
import UiKit
class MenuItemSwitcherViewController : UIViewController {
var restaurant = "mumbai"
var menuItems = [MenuItem]()
var currentItem = 0
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var translation: UILabel!
@IBOutlet weak var originalName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
loadMenuItems()
addResources(currentItem)
addSwiping()
}
func loadMenuItems() {
menuItems = [MenuItem]()
let filePath = NSBundle.mainBundle().pathForResource(restaurant, ofType: "json")
let jsonData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil)
let jsonObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error: nil)
if let jsonDict = jsonObj as? [String: AnyObject] {
if let itemsArray = jsonDict["items"] as? NSArray {
for item in itemsArray {
if let dict = item as? [String: AnyObject] {
self.menuItems.append(MenuItem(data: dict))
}
}
}
}
}
func rightSwiped() {
if currentItem > 0 {
currentItem -= 1
addResources(currentItem)
}
}
func leftSwiped(){
if currentItem < menuItems.count - 1 {
currentItem += 1
addResources(currentItem)
}
}
func addResources(currentItem: Int) {
let initialItem = menuItems[currentItem]
let imageFilePath = NSBundle.mainBundle().pathForResource("\(restaurant)_\(initialItem.image)", ofType: "")
let imageContent = NSData(contentsOfFile: imageFilePath!)!
mainImage.image = UIImage(data: imageContent)
translation.text = initialItem.translations["en"]
originalName.text = initialItem.name
}
func addSwiping() {
let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("rightSwiped"))
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("leftSwiped"))
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
}
}
| mit | 6c1092439a2fcf507301cebe9a9df56e | 31.1125 | 121 | 0.632542 | 5.189899 | false | false | false | false |
slimpp/CocoaSLIMPP | CocoaSLIMPP/SLIMPP.swift | 1 | 6742 | //
// SLIMPP.swift
// CocoaSLIMPP
//
// Created by 李方朔 on 14/8/3.
// Copyright (c) 2014年 slimpp.io. All rights reserved.
//
import Foundation
/**
* SLIMPP Delegate
*/
protocol SLIMPPDelegate {
func slimpp(slimpp: SLIMPP, DidLogin: Bool, error: String?)
func slimppDidOnline(slimpp: SLIMPP, json: NSDictionary)
func slimpp(slimpp: SLIMPP, didSendMessage: SLIMPPMessage)
func slimpp(slimpp: SLIMPP, didReceiveMessage: SLIMPPMessage)
func slimpp(slimpp: SLIMPP, didSendPresence: SLIMPPPresence)
func slimpp(slimpp: SLIMPP, didReceivePresence: SLIMPPPresence)
func slimppDidOffline(slimpp: SLIMPP)
}
/**
* SLIMPP Main Class
**/
class SLIMPP {
/**
* Shared Instance
*/
class var sharedInstance: SLIMPP {
struct Static {
static let instance : SLIMPP = SLIMPP()
}
return Static.instance
}
//delegate
var delegate: SLIMPPDelegate?
//model layer
let roster: SLIMPPRoster
let chatManager: SLIMPPChatManager
let historyManager: SLIMPPHistoryManager
//connection layer
var apiURL: String?
var ticket: String = ""
var connection = NSDictionary()
//mqtt
var mqttClient: CocoaMQTT?
init() {
roster = SLIMPPRoster()
chatManager = SLIMPPChatManager()
historyManager = SLIMPPHistoryManager()
}
func hello() {
println("Hello, CocoaSLIMPP!")
}
func login(username: String, password: String) {
let url = apiURL! + "login?client=ios"
let params = ["username": username, "password": password]
let httpManager = AFHTTPRequestOperationManager()
httpManager.POST(url,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description!)
if let json = responseObject as? NSDictionary {
if json["status"]? as NSString == "ok" {
self.delegate?.slimpp(self, DidLogin: true, error: "OK")
}
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
self.delegate?.slimpp(self, DidLogin: false, error: error.localizedDescription)
})
}
func online() {
let params = ["show": "available"]
let httpManager = AFHTTPRequestOperationManager()
httpManager.POST(_urlFor("online"),
parameters: params,
success: {(operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description!)
self._setup(responseObject as NSDictionary)
self.delegate?.slimppDidOnline(self, json: responseObject as NSDictionary)
self.startPolling()
},
failure: {(operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
func _setup(data: NSDictionary) {
connection = data["connection"] as NSDictionary
ticket = connection["ticket"] as String
println("ticket: " + ticket)
}
func sendMessage(message: SLIMPPMessage) {
let url = _urlFor("message")
println(url)
var params = Dictionary<String,String>()
params["ticket"] = ticket
params["from"] = "test"
params["nick"] = "test"
params["style"] = ""
params["offline"] = "false"
let httpManager = AFHTTPRequestOperationManager()
httpManager.POST(url,
parameters: params,
success: {(operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description!)
//self.delegate?.slimppMessageSent(self, message: message)
},
failure:{(operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
func sendPresence(presence: SLIMPPPresence) {
let url = _urlFor("presence")
println(url)
var params = Dictionary<String,String>()
params["ticket"] = ticket
params["show"] = "away"
let httpManager = AFHTTPRequestOperationManager()
httpManager.POST(url,
parameters: params,
success: {(operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description!)
//self.delegate?.slimppPresenceSent(self, presence:presence)
},
failure:{(operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
func offline() {
}
func startPolling() {
let domain = connection["domain"] as String
let server = connection["jsonpd"] as String
let params = ["domain": domain, "ticket": ticket]
let httpManager = AFHTTPRequestOperationManager()
httpManager.GET(server,
parameters: params,
success: {(operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("Packets Received: " + responseObject.description!)
self.receivedData(responseObject as NSDictionary)
//self.delegate?.slimppReceivedData(self, data: responseObject as NSDictionary)
self.startPolling();
},
failure: {(operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
func receivedData(data: NSDictionary) {
if data["messages"] {
let messages = data["messages"] as NSArray
for msg in messages {
let from = msg["from"] as String
let body = msg["body"] as String
//let to = msg["to"] as String
//chatManager.delegates[from]?.messageReceived(from, message: body)
}
}
}
func _urlFor(api: String) -> String {
return apiURL! + "slimpp.php/v1/" + api
}
}
| mit | b13dc3aec3c7a18b90ab92e0c2982764 | 28.665198 | 95 | 0.553015 | 5.078431 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/ScriptDescriptor.swift | 2 | 4340 | //
// ScriptDescriptor.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2017-10-28.
//
// ---------------------------------------------------------------------------
//
// © 2016-2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UniformTypeIdentifiers
enum ScriptingFileType: CaseIterable {
case appleScript
case unixScript
var fileTypes: [UTType] {
switch self {
case .appleScript: return [.appleScript, .osaScript, .osaScriptBundle] // .applescript, .scpt, .scptd
case .unixScript: return [.shellScript, .perlScript, .phpScript, .rubyScript, .pythonScript, .javaScript, .swiftSource]
}
}
}
enum ScriptingExecutionModel: String, Decodable {
case unrestricted
case persistent
}
enum ScriptingEventType: String, Decodable {
case documentOpened = "document opened"
case documentSaved = "document saved"
var eventID: AEEventID {
switch self {
case .documentOpened: return "edod"
case .documentSaved: return "edsd"
}
}
}
private struct ScriptInfo: Decodable {
var executionModel: ScriptingExecutionModel?
var eventType: [ScriptingEventType]?
private enum CodingKeys: String, CodingKey {
case executionModel = "CotEditorExecutionModel"
case eventType = "CotEditorHandlers"
}
/// Load from Info.plist in script bundle.
init(scriptBundle bundleURL: URL) throws {
let plistURL = bundleURL.appendingPathComponent("Contents/Info.plist")
let data = try Data(contentsOf: plistURL)
self = try PropertyListDecoder().decode(ScriptInfo.self, from: data)
}
}
// MARK: -
struct ScriptDescriptor {
// MARK: Public Properties
let url: URL
let name: String
let type: ScriptingFileType
let executionModel: ScriptingExecutionModel
let eventTypes: [ScriptingEventType]
// MARK: -
// MARK: Lifecycle
/// Create a descriptor that represents a user script at given URL.
///
/// `Contents/Info.plist` in the script at `url` will be read if they exist.
///
/// - Parameter url: The location of a user script.
init?(at url: URL, name: String) {
guard
let contentType = try? url.resourceValues(forKeys: [.contentTypeKey]).contentType,
let type = ScriptingFileType.allCases.first(where: { $0.fileTypes.contains { $0.conforms(to: contentType) } })
else { return nil }
self.url = url
self.name = name
self.type = type
// load some settings Info.plist if exists
let info = (self.type == .appleScript) ? (try? ScriptInfo(scriptBundle: url)) : nil
self.executionModel = info?.executionModel ?? .unrestricted
self.eventTypes = info?.eventType ?? []
}
// MARK: Public Methods
/// Create and return a user script instance.
///
/// - Returns: An instance of `Script` created by the receiver.
/// Returns `nil` if the script type is unsupported.
func makeScript() throws -> any Script {
return try self.scriptType.init(url: self.url, name: self.name)
}
// MARK: Private Methods
private var scriptType: Script.Type {
switch self.type {
case .appleScript:
switch self.executionModel {
case .unrestricted: return AppleScript.self
case .persistent: return PersistentOSAScript.self
}
case .unixScript: return UnixScript.self
}
}
}
| apache-2.0 | 43d199a1ad464743cb56afeef5a6bbac | 25.138554 | 131 | 0.602904 | 4.524505 | false | false | false | false |
kevinup7/S4HeaderExtensions | Tests/S4HeaderExtensions/EncodingTests.swift | 1 | 587 | @testable import S4HeaderExtensions
import XCTest
import S4
class EncodingTests: XCTestCase {
func testStringInitialization() {
XCTAssert(Encoding.chunked == Encoding(headerValue: "chunked")!)
XCTAssert(Encoding.compress == Encoding(headerValue: "compress")!)
XCTAssert(Encoding.deflate == Encoding(headerValue: "deflate")!)
XCTAssert(Encoding.gzip == Encoding(headerValue: "gzip")!)
XCTAssert(Encoding.identity == Encoding(headerValue: "identity")!)
XCTAssert(Encoding.custom("custom") == Encoding(headerValue: "custom")!)
}
}
| mit | 672aab661869e62197afaedd0e8cbd7c | 35.6875 | 80 | 0.698467 | 4.85124 | false | true | false | false |
Piwigo/Piwigo-Mobile | piwigo/Image/Parameters/Tags/TagsViewController+Search.swift | 1 | 2099 | //
// TagsViewController+Search.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 19/06/2022.
// Copyright © 2022 Piwigo.org. All rights reserved.
//
import Foundation
// MARK: - Search Images
@available(iOS 11.0, *)
extension TagsViewController
{
func initSearchBar() {
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.isTranslucent = false
searchController.searchBar.showsCancelButton = false
searchController.searchBar.showsSearchResultsButton = false
searchController.searchBar.tintColor = UIColor.piwigoColorOrange()
searchController.searchBar.placeholder = NSLocalizedString("tags", comment: "Tags")
searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
// Place the search bar in the header of the tableview
tagsTableView.tableHeaderView = searchController.searchBar
}
}
// MARK: - UISearchResultsUpdating Methods
@available(iOS 11.0, *)
extension TagsViewController: UISearchResultsUpdating
{
func updateSearchResults(for searchController: UISearchController) {
if let query = searchController.searchBar.text {
// Update query
searchQuery = query
// Do not update content before pushing view in tableView(_:didSelectRowAt:)
if searchController.isActive {
// Shows filtered data
tableView.reloadData()
}
}
}
}
// MARK: - UISearchBarDelegate Methods
@available(iOS 11.0, *)
extension TagsViewController: UISearchBarDelegate
{
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
// Animates Cancel button appearance
searchBar.setShowsCancelButton(true, animated: true)
return true
}
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// Animates Cancel button disappearance
searchBar.setShowsCancelButton(false, animated: true)
}
}
| mit | 7d99d56a01718ce877c63c1fc6cce922 | 31.261538 | 91 | 0.699571 | 5.577128 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/GroupChat/GroupViewModelProtocol.swift | 1 | 2935 | // Copyright (c) 2018 Token Browser, Inc
//
// 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
enum GroupItemType: Int {
case avatarTitle
case notifications
case isPublic
case participant
case addParticipant
case exitGroup
}
struct GroupInfo {
let placeholder = Localized.new_group_title
var title: String = ""
var avatar = ImageAsset.avatar_placeholder
var isPublic = false
var notificationsOn = true
var participantsIDs: [String] = []
}
protocol GroupViewModelCompleteActionDelegate: class {
func groupViewModelDidFinishCreateOrUpdate()
func groupViewModelDidStartCreateOrUpdate()
func groupViewModelDidRequireReload(_ viewModel: GroupViewModelProtocol)
}
protocol GroupViewModelProtocol: class {
var sectionModels: [TableSectionData] { get }
var viewControllerTitle: String { get }
var rightBarButtonTitle: String { get }
var imagePickerTitle: String { get }
var imagePickerCameraActionTitle: String { get }
var imagePickerLibraryActionTitle: String { get }
var imagePickerCancelActionTitle: String { get }
var groupThread: TSGroupThread? { get }
var errorAlertTitle: String { get }
var errorAlertMessage: String { get }
var rightBarButtonSelector: Selector { get }
var recipientsIds: [String] { get }
var allParticipantsIDs: [String] { get }
var sortedMembers: [Profile] { get set }
func updateAvatar(to image: UIImage)
func updatePublicState(to isPublic: Bool)
func updateNotificationsState(to notificationsOn: Bool)
func updateTitle(to title: String)
func updateRecipientsIds(to recipientsIds: [String])
func setupSortedMembers()
var isDoneButtonEnabled: Bool { get }
var completeActionDelegate: GroupViewModelCompleteActionDelegate? { get set }
}
extension GroupViewModelProtocol {
func setupSortedMembers() {
guard let currentUser = Profile.current else {
CrashlyticsLogger.log("Failed to access current user")
fatalError("Can't access current user")
}
var members = SessionManager.shared.profilesManager.profiles
members.append(currentUser)
members = members.filter { recipientsIds.contains($0.toshiId) }
sortedMembers = members.sorted { $0.username < $1.username }
}
}
| gpl-3.0 | 202eb83d4e03224dcc7adee05c99f77d | 30.902174 | 81 | 0.722658 | 4.61478 | false | false | false | false |
RuiAAPeres/ReactiveCocoa | ReactiveCocoaTests/Swift/DisposableSpec.swift | 13 | 3634 | //
// DisposableSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-07-13.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Nimble
import Quick
import ReactiveCocoa
class DisposableSpec: QuickSpec {
override func spec() {
describe("SimpleDisposable") {
it("should set disposed to true") {
let disposable = SimpleDisposable()
expect(disposable.disposed) == false
disposable.dispose()
expect(disposable.disposed) == true
}
}
describe("ActionDisposable") {
it("should run the given action upon disposal") {
var didDispose = false
let disposable = ActionDisposable {
didDispose = true
}
expect(didDispose) == false
expect(disposable.disposed) == false
disposable.dispose()
expect(didDispose) == true
expect(disposable.disposed) == true
}
}
describe("CompositeDisposable") {
var disposable = CompositeDisposable()
beforeEach {
disposable = CompositeDisposable()
}
it("should ignore the addition of nil") {
disposable.addDisposable(nil)
return
}
it("should dispose of added disposables") {
let simpleDisposable = SimpleDisposable()
disposable.addDisposable(simpleDisposable)
var didDispose = false
disposable.addDisposable {
didDispose = true
}
expect(simpleDisposable.disposed) == false
expect(didDispose) == false
expect(disposable.disposed) == false
disposable.dispose()
expect(simpleDisposable.disposed) == true
expect(didDispose) == true
expect(disposable.disposed) == true
}
it("should not dispose of removed disposables") {
let simpleDisposable = SimpleDisposable()
let handle = disposable += simpleDisposable
// We should be allowed to call this any number of times.
handle.remove()
handle.remove()
expect(simpleDisposable.disposed) == false
disposable.dispose()
expect(simpleDisposable.disposed) == false
}
}
describe("ScopedDisposable") {
it("should dispose of the inner disposable upon deinitialization") {
let simpleDisposable = SimpleDisposable()
func runScoped() {
let scopedDisposable = ScopedDisposable(simpleDisposable)
expect(simpleDisposable.disposed) == false
expect(scopedDisposable.disposed) == false
}
expect(simpleDisposable.disposed) == false
runScoped()
expect(simpleDisposable.disposed) == true
}
}
describe("SerialDisposable") {
var disposable: SerialDisposable!
beforeEach {
disposable = SerialDisposable()
}
it("should dispose of the inner disposable") {
let simpleDisposable = SimpleDisposable()
disposable.innerDisposable = simpleDisposable
expect(disposable.innerDisposable).notTo(beNil())
expect(simpleDisposable.disposed) == false
expect(disposable.disposed) == false
disposable.dispose()
expect(disposable.innerDisposable).to(beNil())
expect(simpleDisposable.disposed) == true
expect(disposable.disposed) == true
}
it("should dispose of the previous disposable when swapping innerDisposable") {
let oldDisposable = SimpleDisposable()
let newDisposable = SimpleDisposable()
disposable.innerDisposable = oldDisposable
expect(oldDisposable.disposed) == false
expect(newDisposable.disposed) == false
disposable.innerDisposable = newDisposable
expect(oldDisposable.disposed) == true
expect(newDisposable.disposed) == false
expect(disposable.disposed) == false
disposable.innerDisposable = nil
expect(newDisposable.disposed) == true
expect(disposable.disposed) == false
}
}
}
}
| mit | e6c8a235f614863f1321a42cc950217d | 24.412587 | 82 | 0.700605 | 4.215777 | false | false | false | false |
huonw/swift | test/IRGen/synthesized_conformance.swift | 1 | 2765 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s -swift-version 4 | %FileCheck %s
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Hashable where T: Hashable {}
extension Struct: Codable where T: Codable {}
enum Enum<T> {
case a(T), b(T)
}
extension Enum: Equatable where T: Equatable {}
extension Enum: Hashable where T: Hashable {}
final class Final<T> {
var x: T
init(x: T) { self.x = x }
}
extension Final: Encodable where T: Encodable {}
extension Final: Decodable where T: Decodable {}
class Nonfinal<T> {
var x: T
init(x: T) { self.x = x }
}
extension Nonfinal: Encodable where T: Encodable {}
func doEquality<T: Equatable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$S23synthesized_conformance8equalityyyF"()
public func equality() {
// CHECK: [[Struct_Equatable:%.*]] = call i8** @"$S23synthesized_conformance6StructVySiGACyxGs9EquatableAAsAFRzlWl"()
// CHECK-NEXT: call swiftcc void @"$S23synthesized_conformance10doEqualityyyxs9EquatableRzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Struct_Equatable]])
doEquality(Struct(x: 1))
// CHECK: [[Enum_Equatable:%.*]] = call i8** @"$S23synthesized_conformance4EnumOySiGACyxGs9EquatableAAsAFRzlWl"()
// CHECK-NEXT: call swiftcc void @"$S23synthesized_conformance10doEqualityyyxs9EquatableRzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Enum_Equatable]])
doEquality(Enum.a(1))
}
func doEncodable<T: Encodable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$S23synthesized_conformance9encodableyyF"()
public func encodable() {
// CHECK: [[Struct_Encodable:%.*]] = call i8** @"$S23synthesized_conformance6StructVySiGACyxGs9EncodableAAs9DecodableRzsAFRzlWl"()
// CHECK-NEXT: call swiftcc void @"$S23synthesized_conformance11doEncodableyyxs0D0RzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Struct_Encodable]])
doEncodable(Struct(x: 1))
// CHECK: [[Final_Encodable:%.*]] = call i8** @"$S23synthesized_conformance5FinalCySiGACyxGs9EncodableAAsAFRzlWl"()
// CHECK-NEXT: call swiftcc void @"$S23synthesized_conformance11doEncodableyyxs0D0RzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Final_Encodable]])
doEncodable(Final(x: 1))
// CHECK: [[Nonfinal_Encodable:%.*]] = call i8** @"$S23synthesized_conformance8NonfinalCySiGACyxGs9EncodableAAsAFRzlWl"()
// CHECK-NEXT: call swiftcc void @"$S23synthesized_conformance11doEncodableyyxs0D0RzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Nonfinal_Encodable]])
doEncodable(Nonfinal(x: 1))
}
| apache-2.0 | dd9ab6d7f63374260cfd7b1536f3ef36 | 49.272727 | 188 | 0.697649 | 3.667109 | false | false | false | false |
dominicpr/PagingMenuController | Pod/Classes/PagingMenuController.swift | 1 | 17811 | //
// PagingMenuController.swift
// PagingMenuController
//
// Created by Yusuke Kita on 3/18/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
@objc public protocol PagingMenuControllerDelegate: class {
optional func willMoveToMenuPage(page: Int)
optional func didMoveToMenuPage(page: Int)
}
public class PagingMenuController: UIViewController, UIScrollViewDelegate {
public weak var delegate: PagingMenuControllerDelegate?
private var options: PagingMenuOptions!
private var menuView: MenuView!
private var contentScrollView: UIScrollView!
private var contentView: UIView!
private var pagingViewControllers = [UIViewController]() {
willSet {
options.menuItemCount = newValue.count
}
}
private var currentPage: Int = 0
private var currentViewController: UIViewController!
private var menuItemTitles: [String] {
get {
return pagingViewControllers.map { viewController -> String in
return viewController.title ?? "Menu"
}
}
}
private enum PagingViewPosition {
case Left
case Center
case Right
case Unknown
init(order: Int) {
switch order {
case 0: self = .Left
case 1: self = .Center
case 2: self = .Right
default: self = .Unknown
}
}
}
private var currentPosition: PagingViewPosition = .Left
private let visiblePagingViewNumber: Int = 3
private let ExceptionName = "PMCException"
// MARK: - Lifecycle
public init(viewControllers: [UIViewController], options: PagingMenuOptions) {
super.init(nibName: nil, bundle: nil)
setup(viewControllers: viewControllers, options: options)
}
convenience public init(viewControllers: [UIViewController]) {
self.init(viewControllers: viewControllers, options: PagingMenuOptions())
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
moveToMenuPage(currentPage, animated: false)
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// fix unnecessary inset for menu view when implemented by programmatically
menuView.contentInset.top = 0
if let currentViewController = currentViewController {
contentScrollView.contentOffset.x = currentViewController.view!.frame.minX
}
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
menuView.updateMenuItemConstraintsIfNeeded(size: size)
view.setNeedsLayout()
view.layoutIfNeeded()
}
public func setup(viewControllers viewControllers: [UIViewController], options: PagingMenuOptions) {
self.options = options
pagingViewControllers = viewControllers
// validate
validateDefaultPage()
cleanup()
currentPage = self.options.defaultPage
constructMenuView()
constructContentScrollView()
layoutMenuView()
layoutContentScrollView()
constructContentView()
layoutContentView()
constructPagingViewControllers()
layoutPagingViewControllers()
currentPosition = currentPagingViewPosition()
currentViewController = pagingViewControllers[self.options.defaultPage]
}
public func rebuild(viewControllers: [UIViewController], options: PagingMenuOptions) {
setup(viewControllers: viewControllers, options: options)
view.setNeedsLayout()
view.layoutIfNeeded()
}
// MARK: - UISCrollViewDelegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
if !scrollView.isEqual(self.contentScrollView) || scrollView.dragging != true {
return
}
let position = currentPagingViewPosition()
if currentPosition != position {
let newPage: Int
switch position {
case .Left: newPage = currentPage - 1
case .Right: newPage = currentPage + 1
default: newPage = currentPage
}
menuView.moveToMenu(page: newPage, animated: true)
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if !scrollView.isEqual(self.contentScrollView) {
return
}
let position = currentPagingViewPosition()
// go back to starting position
if currentPosition == position {
menuView.moveToMenu(page: currentPage, animated: true)
return
}
// set new page number according to current moving direction
switch position {
case .Left: currentPage--
case .Right: currentPage++
default: return
}
delegate?.willMoveToMenuPage?(currentPage)
currentViewController = pagingViewControllers[currentPage]
contentScrollView.contentOffset.x = currentViewController.view!.frame.minX
constructPagingViewControllers()
layoutPagingViewControllers()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
currentPosition = currentPagingViewPosition()
delegate?.didMoveToMenuPage?(currentPage)
}
// MARK: - UIGestureRecognizer
internal func handleTapGesture(recognizer: UITapGestureRecognizer) {
let tappedMenuView = recognizer.view as! MenuItemView
if let tappedPage = menuView.menuItemViews.indexOf(tappedMenuView) where tappedPage != currentPage {
let page = targetPage(tappedPage: tappedPage)
moveToMenuPage(page, animated: true)
}
}
internal func handleSwipeGesture(recognizer: UISwipeGestureRecognizer) {
var newPage = currentPage
if recognizer.direction == .Left {
newPage = min(++newPage, menuView.menuItemViews.count - 1)
} else if recognizer.direction == .Right {
newPage = max(--newPage, 0)
}
moveToMenuPage(newPage, animated: true)
}
// MARK: - Constructor
private func constructMenuView() {
menuView = MenuView(menuItemTitles: menuItemTitles, options: options)
menuView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(menuView)
addTapGestureHandlers()
addSwipeGestureHandlersIfNeeded()
}
private func layoutMenuView() {
let viewsDictionary = ["menuView": menuView]
let metrics = ["height": options.menuHeight]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView(height)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView(height)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
menuView.setNeedsLayout()
menuView.layoutIfNeeded()
}
private func constructContentScrollView() {
contentScrollView = UIScrollView(frame: CGRectZero)
contentScrollView.delegate = self
contentScrollView.pagingEnabled = true
contentScrollView.showsHorizontalScrollIndicator = false
contentScrollView.showsVerticalScrollIndicator = false
contentScrollView.scrollsToTop = false
contentScrollView.bounces = false
contentScrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentScrollView)
}
private func layoutContentScrollView() {
let viewsDictionary = ["contentScrollView": contentScrollView, "menuView": menuView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView][contentScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentScrollView][menuView]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
private func constructContentView() {
contentView = UIView(frame: CGRectZero)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentScrollView.addSubview(contentView)
}
private func layoutContentView() {
let viewsDictionary = ["contentView": contentView, "contentScrollView": contentScrollView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(==contentScrollView)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
private func constructPagingViewControllers() {
for (index, pagingViewController) in pagingViewControllers.enumerate() {
if shouldLoadPage(index) != true {
// remove unnecessary child view controllers
if isVisiblePagingViewController(pagingViewController) {
pagingViewController.willMoveToParentViewController(nil)
pagingViewController.view!.removeFromSuperview()
pagingViewController.removeFromParentViewController()
}
continue
}
// construct three child view controllers at a maximum, previous(optional), current and next(optional)
if isVisiblePagingViewController(pagingViewController) {
continue
}
pagingViewController.view!.frame = CGRectZero
pagingViewController.view!.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(pagingViewController.view!)
addChildViewController(pagingViewController as UIViewController)
pagingViewController.didMoveToParentViewController(self)
}
}
private func layoutPagingViewControllers() {
// cleanup
NSLayoutConstraint.deactivateConstraints(contentView.constraints)
var viewsDictionary: [String: AnyObject] = ["contentScrollView": contentScrollView]
for (index, pagingViewController) in pagingViewControllers.enumerate() {
if shouldLoadPage(index) != true {
continue
}
viewsDictionary["pagingView"] = pagingViewController.view!
let horizontalVisualFormat: String
// only one view controller
if (options.menuItemCount == options.minumumSupportedViewCount) {
horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]|"
} else {
if index == 0 || index == currentPage - 1 {
horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]"
} else {
viewsDictionary["previousPagingView"] = pagingViewControllers[index - 1].view
if index == pagingViewControllers.count - 1 || index == currentPage + 1 {
horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]|"
} else {
horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]"
}
}
}
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pagingView(==contentScrollView)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
}
view.setNeedsLayout()
view.layoutIfNeeded()
}
// MARK: - Cleanup
private func cleanup() {
if let menuView = self.menuView, let contentScrollView = self.contentScrollView {
menuView.removeFromSuperview()
contentScrollView.removeFromSuperview()
}
currentPage = 0
}
// MARK: - Gesture handler
private func addTapGestureHandlers() {
for menuItemView in menuView.menuItemViews {
menuItemView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapGesture:"))
}
}
private func addSwipeGestureHandlersIfNeeded() {
switch options.menuDisplayMode {
case .FlexibleItemWidth(_, let scrollingMode):
switch scrollingMode {
case .PagingEnabled: break
default: return
}
case .FixedItemWidth(_, _, let scrollingMode):
switch scrollingMode {
case .PagingEnabled: break
default: return
}
case .SegmentedControl:
return
}
let leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
leftSwipeGesture.direction = .Left
menuView.panGestureRecognizer.requireGestureRecognizerToFail(leftSwipeGesture)
menuView.addGestureRecognizer(leftSwipeGesture)
let rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
rightSwipeGesture.direction = .Right
menuView.panGestureRecognizer.requireGestureRecognizerToFail(rightSwipeGesture)
menuView.addGestureRecognizer(rightSwipeGesture)
}
// MARK: - Page controller
private func moveToMenuPage(page: Int, animated: Bool) {
currentPage = page
currentViewController = pagingViewControllers[page]
menuView.moveToMenu(page: currentPage, animated: animated)
delegate?.willMoveToMenuPage?(currentPage)
let duration = animated ? options.animationDuration : 0
UIView.animateWithDuration(duration, animations: {
[unowned self] () -> Void in
self.contentScrollView.contentOffset.x = self.currentViewController.view!.frame.minX
}) { (_) -> Void in
self.delegate?.didMoveToMenuPage?(self.currentPage)
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
private func shouldLoadPage(index: Int) -> Bool {
if index < currentPage - 1 || index > currentPage + 1 {
return false
}
return true
}
private func isVisiblePagingViewController(pagingViewController: UIViewController) -> Bool {
return childViewControllers.contains(pagingViewController)
}
// MARK: - Page calculator
private func currentPagingViewPosition() -> PagingViewPosition {
let pageWidth = contentScrollView.frame.width
let order = Int(ceil((contentScrollView.contentOffset.x - pageWidth / 2) / pageWidth))
if currentPage == 0 &&
contentScrollView.contentSize.width < (pageWidth * CGFloat(visiblePagingViewNumber)) {
// consider left edge menu as center position
return PagingViewPosition(order: order + 1)
}
return PagingViewPosition(order: order)
}
private func targetPage(tappedPage tappedPage: Int) -> Int {
switch options.menuDisplayMode {
case .FlexibleItemWidth(_, let scrollingMode):
if case .PagingEnabled = scrollingMode {
return tappedPage < currentPage ? currentPage-1 : currentPage+1
}
case .FixedItemWidth(_, _, let scrollingMode):
if case .PagingEnabled = scrollingMode {
return tappedPage < currentPage ? currentPage-1 : currentPage+1
}
case .SegmentedControl:
return tappedPage
}
return tappedPage
}
// MARK: - Validator
private func validateDefaultPage() {
if options.defaultPage >= options.menuItemCount || options.defaultPage < 0 {
NSException(name: ExceptionName, reason: "default page is invalid", userInfo: nil).raise()
}
}
} | mit | 785b1ccd0c0ec9697326bccb41d20892 | 38.582222 | 208 | 0.65802 | 6.249474 | false | false | false | false |
robrix/Madness | MadnessTests/AlternationTests.swift | 1 | 2611 | // Copyright (c) 2015 Rob Rix. All rights reserved.
final class AlternationTests: XCTestCase {
// MARK: Alternation
func testAlternationParsesEitherAlternative() {
assertAdvancedBy(alternation, input: "xy".characters, lineOffset: 0, columnOffset: 1, offset: 1)
assertAdvancedBy(alternation, input: "yx".characters, lineOffset: 0, columnOffset: 1, offset: 1)
}
func testAlternationOfASingleTypeCoalescesTheParsedValue() {
assertTree(alternation, "xy".characters, ==, "x")
}
// MARK: Optional
func testOptionalProducesWhenPresent() {
assertTree(optional, "y".characters, ==, "y")
assertTree(prefixed, "xy".characters, ==, "xy")
assertTree(suffixed, "yzsandwiched".characters, ==, "yz")
}
func testOptionalProducesWhenAbsent() {
assertTree(optional, "".characters, ==, "")
assertTree(prefixed, "x".characters, ==, "x")
assertTree(suffixed, "z".characters, ==, "z")
assertTree(sandwiched, "xz".characters, ==, "xz")
}
// MARK: One-of
func testOneOfParsesFirstMatch() {
assertTree(one, "xyz".characters, ==, "x")
assertTree(one, "yzx".characters, ==, "y")
assertTree(one, "zxy".characters, ==, "z")
}
// MARK: Any-of
func testAnyOfParsesAnArrayOfMatchesPreservingOrder() {
assertTree(any, "xy".characters, ==, ["x", "y"])
assertTree(any, "yx".characters, ==, ["y", "x"])
assertTree(any, "zxy".characters, ==, ["z", "x", "y"])
}
func testAnyOfRejectsWhenNoneMatch() {
assertUnmatched(anyOf(Set("x")), Set("y".characters))
}
func testAnyOfOnlyParsesFirstMatch() {
assertTree(any, "xyy".characters, ==, ["x", "y"])
}
// MARK: All-of
func testAllOfParsesAnArrayOfMatchesPreservingOrder() {
assertTree(all, "xy".characters, ==, ["x", "y"])
assertTree(all, "yx".characters, ==, ["y", "x"])
assertTree(all, "zxy".characters, ==, ["z", "x", "y"])
}
func testAllOfRejectsWhenNoneMatch() {
assertUnmatched(allOf(Set("x")), Set(["y"]))
}
}
// MARK: - Fixtures
private let alternation = %"x" <|> %"y"
private let optional = map({ $0 ?? "" })((%"y")|?)
private let prefixed = { x in { y in x + y } } <^> %"x" <*> optional
private let suffixed = { x in { y in x + y } } <^> optional <*> %"z"
private let sandwiched = { x in { y in x + y } } <^> prefixed <*> %"z"
private let arrayOfChars: Set<Character> = ["x", "y", "z"]
private let chars: String = "xyz"
private let one = oneOf(chars)
private let any: Parser<String.CharacterView, [Character]>.Function = anyOf(arrayOfChars)
private let all: Parser<String.CharacterView, [Character]>.Function = allOf(arrayOfChars)
// MARK: - Imports
import Madness
import Result
import XCTest
| mit | b457c0f68ef0db93d188d34df343c11a | 27.380435 | 98 | 0.65607 | 3.195838 | false | true | false | false |
andreabondi/sdktester | SDKtester/ViewController.swift | 1 | 3520 | //
// ViewController.swift
// SDK Tester
//
// Created by Bondi, Andrea on 20/04/2017.
// Copyright © 2017 Bondi, Andrea. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
// Default test URLs
let nativeXoUrl = "https://ppxoab.herokuapp.com/cart/index.html"
let btUrl = "https://btnodeab.herokuapp.com/test.html"
// Default values for UI elements
var selectedSdk = 0
var url = "https://ppxoab.herokuapp.com/cart/index.html"
@IBOutlet weak var sdkSelector: UISegmentedControl!
@IBOutlet weak var urlToOpen: UITextField!
@IBOutlet weak var nativeSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
urlToOpen.text = url
urlToOpen.delegate = self
sdkSelector.selectedSegmentIndex = selectedSdk
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Handle the return key inside text field
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
loadPagePressed(textField)
return true
}
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
if (sender.selectedSegmentIndex == 0) {
urlToOpen.text = nativeXoUrl
nativeSwitch.isEnabled = true
} else {
urlToOpen.text = btUrl
nativeSwitch.isEnabled = false
}
}
@IBAction func loadPagePressed(_ sender: Any) {
if(sdkSelector.selectedSegmentIndex == 0){
if(urlToOpen.text != "https://ppxoab.herokuapp.com/cart/index.html" && nativeSwitch.isOn){
let alert = UIAlertController(title: "SDK Tester", message: "The native experience is restricted to the pre-set test environment. \n\n If you want to test another url please disable the native payment sheet.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
performSegue(withIdentifier: "OpenNativeXO", sender: Any?.self)
} else {
performSegue(withIdentifier: "OpenPopupBridge", sender: Any?.self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Pass the URL value to the subsequent VC
let url = urlToOpen.text
let nativeSheet = nativeSwitch.isOn
if let destinationVC = segue.destination as? NativeXOUIWebViewController {
destinationVC.storeUrl = url!
destinationVC.nativeSheet = nativeSheet
} else if let destinationVC = segue.destination as? PopupBridgeViewController {
destinationVC.storeUrl = url!
}
}
// Display info popup
@IBAction func infoPressed(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "SDK Tester", message: "Tester app for NativeXO and PopupBridge SDK. \n\n ©2018 Andrea Bondi\[email protected] \n\n THIS APP IS PROVIDED AS IS, see MIT license", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| mit | 7c00bcdd5879bef76fd397734832f840 | 38.088889 | 271 | 0.660603 | 4.728495 | false | true | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/Models/WMDownloadFileManager.swift | 1 | 5007 | //
// DownloadFileManager.swift
// WebimClientLibrary_Example
//
// Created by EVGENII Loshchenko on 04.05.2021.
// Copyright © 2021 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Nuke
import WebimClientLibrary
protocol WMDownloadFileManagerDelegate: AnyObject {
func updateImageDownloadProgress(url: URL, progress: Float, image: UIImage? )
}
class WMDownloadFileManager {
private var fileGuidURLDictionary: [String: String] = (WMKeychainWrapper.standard.dictionary(forKey: WMKeychainWrapper.fileGuidURLDictionaryKey) as? [String: String]) ?? [:]
private var delegatesSet = Set<WMWeakReferenseContainer<WMDownloadFileManagerDelegate>>()
func addDelegate(delegate: WMDownloadFileManagerDelegate) {
delegatesSet.insert(WMWeakReferenseContainer(delegate))
}
func removeDelegate(delegate: AnyObject) {
delegatesSet = delegatesSet.filter { $0.getValue() != nil && $0.getValue() as AnyObject !== delegate }
}
static var shared = WMDownloadFileManager()
func saveUrl(_ url: URL?, forGuid guid: String) {
self.fileGuidURLDictionary[guid] = url?.absoluteString
WMKeychainWrapper.standard.setDictionary(fileGuidURLDictionary, forKey: WMKeychainWrapper.fileGuidURLDictionaryKey)
}
var progressDictionary: [URL: Float] = [:]
func progressForURL(_ url: URL?) -> Float {
if let url = url {
return progressDictionary[url] ?? 0
}
return 0
}
private func expiredFromUrl(_ url: URL?) -> Int64 {
return Int64(url?.queryParameters?["expires"] ?? "0") ?? 0
}
func imageForFileInfo(_ fileInfo: FileInfo?) -> UIImage? {
return nil
}
func urlFromFileInfo(_ fileInfo: FileInfo?) -> URL? {
guard let fileInfo = fileInfo else { return nil }
if let guid = fileInfo.getGuid() {
if let cachedUrlString = self.fileGuidURLDictionary[guid] { // check url cached and not expired
let url = URL(string: cachedUrlString)
let expires = self.expiredFromUrl(url)
if Int64(Date().timeIntervalSince1970) < expires {
return url
} else {
self.saveUrl(fileInfo.getURL(), forGuid: guid)
}
} else {
self.saveUrl(fileInfo.getURL(), forGuid: guid)
}
return URL(string: self.fileGuidURLDictionary[guid] ?? "")
}
return fileInfo.getURL()
}
func imageForUrl(_ url: URL) -> UIImage? {
let request = ImageRequest(url: url)
if let image = ImageCache.shared[request] {
return image
} else {
Nuke.ImagePipeline.shared.loadImage(
with: url,
progress: { _, completed, total in
self.delegatesSet = self.delegatesSet.filter { $0.getValue() != nil }
self.delegatesSet.forEach { container in
container.getValue()?.updateImageDownloadProgress(
url: url,
progress: Float(total) == 0 ? 0 : Float(completed) / Float(total),
image: nil
)
}
},
completion: { _ in
self.delegatesSet = self.delegatesSet.filter { $0.getValue() != nil }
self.delegatesSet.forEach { container in
container.getValue()?.updateImageDownloadProgress(
url: url,
progress: 1,
image: ImageCache.shared[request]
)
}
}
)
}
return nil
}
}
| mit | 647f17997a80f9fa0987176fe90203af | 36.924242 | 177 | 0.594087 | 4.888672 | false | false | false | false |
tebs1200/swift-currency-field | CurrencyField/CurrencyField.swift | 1 | 2800 | //
// CurrencyField.swift
// CurrencyField
//
// Created by Aaren Tebbutt on 20/5/17.
// Copyright © 2017 Noshjournal. All rights reserved.
//
import UIKit
public class CurrencyField: UITextField {
private var internalValue: Decimal?
public var value: Decimal? {
get {
return internalValue
}
set(val) {
internalValue = val
setTextToCurrencyString(for: val)
}
}
private var lastValidText: String? = nil
fileprivate lazy var currencyFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
return numberFormatter
}()
// MARK: Initialisers
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
keyboardType = .decimalPad
self.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
}
override public init(frame: CGRect) {
super.init(frame: frame)
keyboardType = .decimalPad
self.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
}
// Prevent the user from moving the cursor
override public func closestPosition(to point: CGPoint) -> UITextPosition? {
let beginning = self.beginningOfDocument
let end = self.position(from: beginning, offset: (self.text?.characters.count)!)
return end
}
public func textDidChange() {
if let currentText = self.text, currentText != "" {
if currentText == NSLocale.current.currencySymbol {
internalValue = nil
lastValidText = currentText
} else {
if let parsedDecimalValue = parseCurrencyString(currentText) {
internalValue = parsedDecimalValue
lastValidText = currentText
} else {
self.text = lastValidText
}
}
} else {
internalValue = nil
lastValidText = nil
}
}
// MARK: Helper Functions
private func setTextToCurrencyString(for value: Decimal?) {
if let value = value {
self.text = NumberFormatter.localizedString(from: NSDecimalNumber(decimal: value), number: .currency)
} else {
self.text = nil
}
}
private func parseCurrencyString(_ currencyString: String) -> Decimal? {
if let decimal = Decimal(string: currencyString) {
return decimal
} else if let number = currencyFormatter.number(from: currencyString) {
return number.decimalValue
}
return nil
}
}
| mit | 2495b38319221cd08464cb4ebebc7b4b | 27.561224 | 113 | 0.578778 | 5.301136 | false | false | false | false |
xiaowinner/YXWShineButton | YXWShineButton.swift | 1 | 3468 | import UIKit
@objc public class YXWShineButton: UIControl {
/// 更多的配置参数
public var params: YXWShineParams {
didSet {
clickLayer.animDuration = params.animDuration/3
shineLayer.params = params
}
}
/// 未点击的颜色
public var color: UIColor = UIColor.lightGray {
willSet {
clickLayer.color = newValue
}
}
/// 点击后的颜色
public var fillColor: UIColor = UIColor(rgb: (255, 102, 102)) {
willSet {
clickLayer.fillColor = newValue
shineLayer.fillColor = newValue
}
}
/// button的图片
public var image: YXWShineImage = .heart {
willSet {
clickLayer.image = newValue
}
}
/// 是否点击的状态
public override var isSelected:Bool {
didSet {
clickLayer.clicked = isSelected
}
}
public var currentSelected:Bool = false {
willSet {
clickLayer.clicked = currentSelected
}
}
private var clickLayer = YXWShineClickLayer()
private var shineLayer = YXWShineLayer()
//MARK: Initial Methods
public init(frame: CGRect, params: YXWShineParams) {
self.params = params
super.init(frame: frame)
initLayers()
}
public override init(frame: CGRect) {
params = YXWShineParams()
super.init(frame: frame)
initLayers()
}
required public init?(coder aDecoder: NSCoder) {
params = YXWShineParams()
super.init(coder: aDecoder)
layoutIfNeeded()
initLayers()
}
public override func sendActions(for controlEvents: UIControlEvents) {
super.sendActions(for: controlEvents)
weak var weakSelf = self
if clickLayer.clicked == false {
shineLayer.endAnim = { Void in
weakSelf?.clickLayer.clicked = !(weakSelf?.clickLayer.clicked ?? false)
weakSelf?.clickLayer.startAnim()
weakSelf?.currentSelected = weakSelf?.clickLayer.clicked ?? false
}
shineLayer.startAnim()
}else {
clickLayer.clicked = !clickLayer.clicked
currentSelected = clickLayer.clicked
}
}
//MARK: Override
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
weak var weakSelf = self
if clickLayer.clicked == false {
shineLayer.endAnim = { Void in
weakSelf?.clickLayer.clicked = !(weakSelf?.clickLayer.clicked ?? false)
weakSelf?.clickLayer.startAnim()
weakSelf?.currentSelected = weakSelf?.clickLayer.clicked ?? false
}
shineLayer.startAnim()
}else {
clickLayer.clicked = !clickLayer.clicked
currentSelected = clickLayer.clicked
}
}
//MARK: Privater Methods
private func initLayers() {
clickLayer.animDuration = params.animDuration/3
shineLayer.params = params
clickLayer.frame = bounds
shineLayer.frame = bounds
layer.addSublayer(clickLayer)
layer.addSublayer(shineLayer)
}
}
| mit | 83b07eb901e724830c32b06e6d29d281 | 25.230769 | 87 | 0.553079 | 4.978102 | false | false | false | false |
Maggie005889/weibo4 | 新浪微博3/Classes/Module/Main/MainTabBar.swift | 1 | 1578 | //
// MainTabBar.swift
// 新浪微博3
//
// Created by Maggie on 15/10/8.
// Copyright © 2015年 Maggie. All rights reserved.
//
import UIKit
class MainTabBar: UITabBar {
override func layoutSubviews() {
super.layoutSubviews()
var index: CGFloat = 0
let w = UIScreen.mainScreen().bounds.width / 5
let h = self.bounds.height
let frame = CGRectMake(0, 0, w, h)
for view in subviews {
if view is UIControl && !(view is UIButton){
view.frame = CGRectOffset(frame, index * w, 0)
//递增index
if index == 1 {
index++
}
index++
}
}
//设置撰写按钮的位置
composeButton.frame = CGRectOffset(frame, 2 * w, 0)
}
lazy var composeButton:UIButton = {
let btn = UIButton(type:UIButtonType.Custom)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
// self.addSbuview(btn)
self.addSubview(btn)
return btn
}()
}
| apache-2.0 | 154765cf9e0bf818860a4f47bd5611f6 | 25.186441 | 121 | 0.546278 | 4.61194 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Home/HomeScreen.swift | 1 | 3917 | ////
/// HomeScreen.swift
//
class HomeScreen: StreamableScreen, HomeScreenProtocol {
weak var delegate: HomeScreenDelegate?
let controllerContainer: UIView = Container()
override func arrange() {
super.arrange()
addSubview(controllerContainer)
controllerContainer.snp.makeConstraints { make in
make.edges.equalTo(self)
}
}
}
@objc
protocol HomeScreenNavBar: class {
@objc func homeScreenScrollToTop()
@objc optional func homeScreenEditorialsTapped()
@objc optional func homeScreenArtistInvitesTapped()
@objc optional func homeScreenFollowingTapped()
@objc optional func homeScreenDiscoverTapped()
}
struct HomeScreenNavBarSize {
static let typeOffset: CGFloat = 18.625
static let tabBarOffset: CGFloat = 4.5
}
private typealias Size = HomeScreenNavBarSize
enum HomeScreenType {
case editorials(loggedIn: Bool)
case artistInvites(loggedIn: Bool)
case following
case discover
}
private let logoButtonTag = 0x312
extension HomeScreenNavBar {
func styleHomeScreenNavBar(navigationBar: UIView) {
guard let logoButton:UIButton = navigationBar.findSubview({ $0.tag == logoButtonTag })
else { return }
logoButton.setImage(.elloType, imageStyle: .dynamic, for: .normal)
}
func arrangeHomeScreenNavBar(type: HomeScreenType, navigationBar: UIView) {
let logoButton = UIButton()
logoButton.tag = logoButtonTag
logoButton.addTarget(self, action: #selector(homeScreenScrollToTop), for: .touchUpInside)
let tabBar = NestedTabBarView()
let editorialsTab = tabBar.createTab(title: InterfaceString.Editorials.NavbarTitle)
let otherTab = tabBar.createTab()
let middleTab = tabBar.createTab(title: InterfaceString.ArtistInvites.Title)
editorialsTab.addTarget(self, action: #selector(homeScreenEditorialsTapped))
middleTab.addTarget(self, action: #selector(homeScreenArtistInvitesTapped))
tabBar.addTab(editorialsTab)
tabBar.addTab(middleTab)
tabBar.addTab(otherTab)
switch type {
case let .editorials(loggedIn):
tabBar.select(tab: editorialsTab)
if loggedIn {
otherTab.title = InterfaceString.Following.Title
otherTab.addTarget(self, action: #selector(homeScreenFollowingTapped))
}
else {
otherTab.title = InterfaceString.Discover.Title
otherTab.addTarget(self, action: #selector(homeScreenDiscoverTapped))
}
case .following:
tabBar.select(tab: otherTab)
otherTab.title = InterfaceString.Following.Title
case let .artistInvites(loggedIn):
tabBar.select(tab: middleTab)
if loggedIn {
otherTab.title = InterfaceString.Following.Title
otherTab.addTarget(self, action: #selector(homeScreenFollowingTapped))
}
else {
otherTab.title = InterfaceString.Discover.Title
otherTab.addTarget(self, action: #selector(homeScreenDiscoverTapped))
}
case .discover:
tabBar.select(tab: otherTab)
otherTab.title = InterfaceString.Discover.Title
}
navigationBar.addSubview(logoButton)
navigationBar.addSubview(tabBar)
logoButton.snp.makeConstraints { make in
make.centerX.equalTo(navigationBar)
make.top.equalTo(navigationBar).offset(
StatusBar.Size.height + HomeScreenNavBarSize.typeOffset
)
}
tabBar.snp.makeConstraints { make in
make.leading.trailing.equalTo(navigationBar)
make.top.equalTo(logoButton.snp.bottom).offset(HomeScreenNavBarSize.tabBarOffset)
}
styleHomeScreenNavBar(navigationBar: navigationBar)
}
}
| mit | 346f5fd84425efce45170f11ab0d66a7 | 31.915966 | 97 | 0.66505 | 4.84178 | false | false | false | false |
AcroMace/DreamBig | DreamBig/Camera/Scene.swift | 1 | 3575 | //
// Scene.swift
// DreamBig
//
// Created by Andy Cho on 2017-06-10.
// Copyright © 2017 AcroMace. All rights reserved.
//
import SpriteKit
import ARKit
class Scene: SKScene {
var drawingModel: DrawingModel?
var emojiSpacingScale: Float = 1 // spacing between emojis
var spawnDistance: Float = 1 // m away from the user
private(set) var identifierToEmoji = [UUID: String]()
// On tap, reset the position of all nodes
func resetNodes() {
if let `drawingModel` = drawingModel {
resetNodes(drawingModel: drawingModel)
}
}
func resetNodes(drawingModel: DrawingModel) {
self.removeAllChildren()
identifierToEmoji = [:]
// Translate a coordinate position to an angle
let posToAngleConstant = 0.0003 * Float.pi * emojiSpacingScale
// Get the maximum size of an emoji
let maxSize = (drawingModel.points.max { p1, p2 in p1.size < p2.size })?.size ?? 0
// Add the emoji nodes to the scene
for drawingPoint in drawingModel.points {
addEmojiNode(x: posToAngleConstant * Float(drawingPoint.x - drawingModel.canvasSize.width / 2),
// For the position, y increases as it goes down
y: posToAngleConstant * Float(drawingModel.canvasSize.height / 2 - drawingPoint.y),
// All emojis are at least 1 meter in front, distance exaggerated by a factor of 10
z: Float(drawingPoint.size - maxSize) - spawnDistance,
emoji: drawingPoint.emoji)
}
}
// Add an emoji node in the relative coordinate system of the camera
// - x is the angle RIGHT from the centre of the screen
// - y is the angle UP from the centre of the screen
// - z is the metres coming out TOWARDS YOU from the screen
// - emoji is the text on the node
private func addEmojiNode(x: Float, y: Float, z: Float, emoji: String) {
guard let sceneView = self.view as? ARSKView else {
return
}
// Create anchor using the camera's current position
// Important note in case implementation changes later:
// The angles for rotation are based on portrait mode (positive is right, up)
// The translations are based on landscape mode where the home button is on the right
// (positive is to the home button to go right, right side of the iPad to go up)
if let currentFrame = sceneView.session.currentFrame {
// Rotate the emoji - directions based on assuming we are in landscape right mode
// If this was portrait mode, it would be (x, 1, 0, 0), (y, 0, 1, 0) as expected
let horizontalRotation = matrix_float4x4(SCNMatrix4MakeRotation(x, 0, -1, 0))
let verticalRotation = matrix_float4x4(SCNMatrix4MakeRotation(y, 1, 0, 0))
let rotation = simd_mul(horizontalRotation, verticalRotation)
// Translate the emoji
var translation = matrix_identity_float4x4
translation.columns.3.z = z
// Transform the emoji around the current camera direction
// Note that the order of the multiplications matter here
let transform = simd_mul(currentFrame.camera.transform, simd_mul(rotation, translation))
// Add a new anchor to the session
let anchor = ARAnchor(transform: transform)
identifierToEmoji[anchor.identifier] = emoji
sceneView.session.add(anchor: anchor)
}
}
}
| mit | 97e8be5bcdd4368b3fab0e6c277cc51c | 43.123457 | 108 | 0.632345 | 4.434243 | false | false | false | false |
L-Zephyr/Drafter | Sources/Drafter/AST/Common/ClassNode.swift | 1 | 4606 | //
// NodeConstant.swift
// Mapper
//
// Created by LZephyr on 2017/9/26.
// Copyright © 2017年 LZephyr. All rights reserved.
//
import Cocoa
/// 保存类型信息的节点
class ClassNode: Node {
var isSwift: Bool = false // 是否为swift
var superCls: String? = nil // 父类
var className: String = "" // 类名
var protocols: [String] = [] // 实现的协议
var methods: [MethodNode] = [] // 方法
var accessControl: AccessControlLevel = .public // 访问权限
// sourcery:inline:ClassNode.AutoCodable
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
isSwift = try container.decode(Bool.self, forKey: .isSwift)
superCls = try container.decode(String?.self, forKey: .superCls)
className = try container.decode(String.self, forKey: .className)
protocols = try container.decode([String].self, forKey: .protocols)
methods = try container.decode([MethodNode].self, forKey: .methods)
accessControl = try container.decode(AccessControlLevel.self, forKey: .accessControl)
}
init() { }
// sourcery:end
}
// MARK: - 自定义初始化方法
extension ClassNode {
convenience init(_ isSwift: Bool, _ accessLevel: String?, _ name: String, _ superClass: String?, _ protos: [String], _ methods: [MethodNode]) {
self.init()
if let superClass = superClass, !superClass.isEmpty {
self.superCls = superClass
}
self.isSwift = isSwift
self.className = name
self.protocols = protos
self.methods = methods
self.accessControl = AccessControlLevel(stringLiteral: accessLevel ?? "internal")
}
convenience init(clsName: String) {
self.init(false, nil, clsName, nil, [], [])
}
// 解析OC时所用的初始化方法
convenience init(interface: InterfaceNode? = nil, implementation: ImplementationNode? = nil) {
self.init()
self.isSwift = false
if let interface = interface {
self.className = interface.className
self.superCls = interface.superCls ?? ""
self.protocols = interface.protocols
}
if let imp = implementation {
let interfaceMethods = Set<MethodNode>(interface?.methods ?? [])
/// 作用域
self.methods = imp.methods.map { method -> MethodNode in
if let index = interfaceMethods.index(of: method) {
method.accessControl = max(method.accessControl, interfaceMethods[index].accessControl)
}
return method
}
}
}
}
// MARK: - 数据格式化
extension ClassNode: CustomStringConvertible {
var description: String {
var desc = "{class: \(className)"
if let superCls = superCls {
desc.append(contentsOf: ", superClass: \(superCls)")
}
if protocols.count > 0 {
desc.append(contentsOf: ", protocols: \(protocols.joined(separator: ", "))")
}
desc.append(contentsOf: "}")
return desc
}
}
extension ClassNode {
/// 转换成前端模板用的JSON数据
func toTemplateJSON() -> [String: Any] {
var info = [String: Any]()
let methodIds = self.methods.map { $0.hashValue }
let clsId = ID_MD5(className)
info["type"] = "class" // type
info["name"] = className // name
if let superClass = superCls { // super
info["super"] = superClass
} else {
info["super"] = ""
}
info["accessControl"] = accessControl.description // access level
info["protocols"] = protocols.map { ["name": $0, "id": ID_MD5($0)] } // protocols
info["isSwift"] = isSwift // isSwift
info["id"] = clsId // id
// 以方法的id作为Key转换成字典
info["methods"] = // methods
methods.map {
$0.toTemplateJSON(clsId: clsId, methods: methodIds)
}
.toDictionary({ (json) -> String? in
return json["id"] as? String
})
return info
}
}
// MARK: - Hashable
extension ClassNode: Hashable {
static func ==(lhs: ClassNode, rhs: ClassNode) -> Bool {
return lhs.className == rhs.className
}
var hashValue: Int {
return className.hashValue
}
}
| mit | c0614db1354b6095eb56b6633a856951 | 30.792857 | 147 | 0.56302 | 4.312984 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.