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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SlackKit/SKWebAPI | Sources/Endpoint.swift | 1 | 3531 | //
// WebAPI.swift
//
// Copyright © 2017 Peter Zignego. 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.
public enum Endpoint: String {
case apiTest = "api.test"
case authRevoke = "auth.revoke"
case authTest = "auth.test"
case channelsHistory = "channels.history"
case channelsInfo = "channels.info"
case channelsList = "channels.list"
case channelsMark = "channels.mark"
case channelsCreate = "channels.create"
case channelsInvite = "channels.invite"
case channelsSetPurpose = "channels.setPurpose"
case channelsSetTopic = "channels.setTopic"
case chatDelete = "chat.delete"
case chatPostMessage = "chat.postMessage"
case chatMeMessage = "chat.meMessage"
case chatUpdate = "chat.update"
case conversationsList = "conversations.list"
case dndInfo = "dnd.info"
case dndTeamInfo = "dnd.teamInfo"
case emojiList = "emoji.list"
case filesCommentsAdd = "files.comments.add"
case filesCommentsEdit = "files.comments.edit"
case filesCommentsDelete = "files.comments.delete"
case filesDelete = "files.delete"
case filesInfo = "files.info"
case filesUpload = "files.upload"
case groupsClose = "groups.close"
case groupsHistory = "groups.history"
case groupsInfo = "groups.info"
case groupsList = "groups.list"
case groupsMark = "groups.mark"
case groupsOpen = "groups.open"
case groupsSetPurpose = "groups.setPurpose"
case groupsSetTopic = "groups.setTopic"
case imClose = "im.close"
case imHistory = "im.history"
case imList = "im.list"
case imMark = "im.mark"
case imOpen = "im.open"
case mpimClose = "mpim.close"
case mpimHistory = "mpim.history"
case mpimList = "mpim.list"
case mpimMark = "mpim.mark"
case mpimOpen = "mpim.open"
case oauthAccess = "oauth.access"
case pinsList = "pins.list"
case pinsAdd = "pins.add"
case pinsRemove = "pins.remove"
case reactionsAdd = "reactions.add"
case reactionsGet = "reactions.get"
case reactionsList = "reactions.list"
case reactionsRemove = "reactions.remove"
case rtmStart = "rtm.start"
case rtmConnect = "rtm.connect"
case starsAdd = "stars.add"
case starsRemove = "stars.remove"
case teamInfo = "team.info"
case usersGetPresence = "users.getPresence"
case usersInfo = "users.info"
case usersList = "users.list"
case usersSetActive = "users.setActive"
case usersSetPresence = "users.setPresence"
}
| mit | 8c0040ce896ced4d78cec738e777c954 | 40.046512 | 80 | 0.711331 | 3.857923 | false | false | false | false |
tschob/HSAudioPlayer | HSAudioPlayer/Core/Public/Player/HSAudioPlayer+URL.swift | 1 | 2561 | //
// HSAudioPlayer+URL.swift
// HSAudioPlayer
//
// Created by Hans Seiffert on 02.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import MediaPlayer
extension HSAudioPlayer {
// MARK: - Play
public func play(urlString urlString: String) {
self.play(url: NSURL(string: urlString))
}
public func play(urlStrings urlStrings: [String], startPosition: Int) {
self.play(urls: HSURLAudioPlayerItem.convertToURLs(urlStrings), startPosition: startPosition)
}
public func play(url url: NSURL?) {
if let _playerItem = HSURLAudioPlayerItem(url: url) {
self.play(_playerItem)
}
}
public func play(urls urls: [NSURL?], startPosition: Int) {
// Play the first item directly and add the other items to the queue in the background
if let firstPlayableItem = HSURLAudioPlayerItem.firstPlayableItem(urls, startPosition: startPosition) {
// Play the first item directly
self.play(firstPlayableItem.playerItem)
// Split the items into array which contain the ones which have to be prepended and appended to queue
var urlsToPrepend = Array(urls)
if (firstPlayableItem.index > 0) {
// If the index of the first playable item is greater than 0 there are items to prepend
urlsToPrepend.removeRange(firstPlayableItem.index..<urlsToPrepend.count)
}
var urlsToAppend = Array(urls)
urlsToAppend.removeRange(0..<(firstPlayableItem.index + 1))
// Append the remaining urls to queue in the background
// As the creation of the player items takes some time, we avoid a blocked UI
self.addToQueueInBackground(prepend: urlsToPrepend, append: urlsToAppend, queueGeneration: self.queueGeneration)
}
}
private func addToQueueInBackground(prepend urlsToPrepend: [NSURL?], append urlsToAppend: [NSURL?], queueGeneration: Int) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let itemsToPrepend = HSURLAudioPlayerItem.playerItems(urlsToPrepend, startPosition: 0)
let itemsToAppend = HSURLAudioPlayerItem.playerItems(urlsToAppend, startPosition: 0)
dispatch_async(dispatch_get_main_queue()) {
self.prepend(itemsToPrepend.playerItems, queueGeneration: queueGeneration)
self.append(itemsToAppend.playerItems, queueGeneration: queueGeneration)
}
}
}
// MARK: - Helper
public func isPlaying(urlString urlString: String) -> Bool {
return self.isPlaying(url: NSURL(string: urlString))
}
public func isPlaying(url url: NSURL?) -> Bool {
return (self.isPlaying() == true && self.currentPlayerItem()?.identifier() == url?.absoluteString)
}
}
| mit | e3a05c4efece8943907c65c71c5942f9 | 37.208955 | 124 | 0.747656 | 3.832335 | false | false | false | false |
gp09/Beefit | BeefitMsc/BeefitMsc/BeeSignUpViewController.swift | 1 | 2017 | //
// BeeSignUpViewController.swift
// BeefitMsc
//
// Created by Priyank on 31/07/2017.
// Copyright © 2017 priyank. All rights reserved.
//
import UIKit
import FirebaseAuth
class BeeSignUpViewController: UIViewController {
@IBOutlet var emailTxtField: UITextField!
@IBOutlet var passTxtField: UITextField!
@IBOutlet var confirmTxtField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signUpBtnTapped(_ sender: Any) {
signUP()
}
func signUP() {
Auth.auth().createUser(withEmail: "[email protected]", password: "123456") { (user, error) in
print("Login Successful")
user?.getIDToken(completion: { (token, error) in
print("\(String(describing: token))")
BeeKeychainService.saveToken(token: token! as NSString)
})
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
let email = user.email
let photoURL = user.photoURL
// ...
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 14642585ec9e9526171037aa09335d2d | 30.015385 | 107 | 0.594246 | 5.002481 | false | false | false | false |
DeepestDesire/WelcomePages | WelcomePages/Classes/WelcomePageManager.swift | 1 | 1703 | //
// WelcomePageManager.swift
// dentist
//
// Created by GeorgeCharles on 8/2/17.
// Copyright © 2017 GeorgeCharles. All rights reserved.
//
import UIKit
class WelcomePageManager: NSObject {
func workout(json: [String: Any]?) {
guard let info = json else {
return
}
guard let needShow = info["is_activity"] as? Bool else {
return
}
let alreadyShow: Bool = alreadyShowUserInfo()
if needShow && !alreadyShow {
showPage(content: (info["content"] as? String ?? ""),
nickName: (info["nickname"] as? String ?? ""),
profileIcon: (info["profileIcon"] as? String ?? ""))
}
}
func showPage(content: String, nickName: String, profileIcon: String) {
let welcomePage = WelcomePageController(nibName: "WelcomePageController", bundle: nil)
UIApplication.shared.keyWindow?.rootViewController?.present(welcomePage, animated: false) {
welcomePage.setInfo(content: content, nickName: nickName, profileIcon: profileIcon)
}
setAlreadyShow()
}
let welcomPageKey = "_Show_WelcomePage_2017"
/// 是否显示过用户信息
func alreadyShowUserInfo() -> Bool {
if let mobile = UserDefaults.standard.string(forKey: "CLUserMobile") {
let result = UserDefaults.standard.bool(forKey: "\(mobile+welcomPageKey)")
return result
}
return true
}
func setAlreadyShow() {
if let mobile = UserDefaults.standard.string(forKey: "CLUserMobile") {
UserDefaults.standard.set(true, forKey: "\(mobile+welcomPageKey)")
}
}
}
| mit | c098fbaf36d4913562d58662c0e14b39 | 32.019608 | 99 | 0.601544 | 4.340206 | false | false | false | false |
bradhilton/SwiftTable | SwiftTable/Bridge/Bridge+Interface.swift | 1 | 11516 | //
// Bride+TableInterface.swift
// SwiftTable
//
// Created by Bradley Hilton on 2/12/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
extension Bridge : ParentInterface {
var style: UITableView.Style {
return _tableView.style
}
var rowHeight: CGFloat {
get {
return _tableView.rowHeight
}
set {
tableView?.rowHeight = newValue
}
}
var sectionHeaderHeight: CGFloat {
get {
return _tableView.sectionHeaderHeight
}
set {
tableView?.sectionHeaderHeight = newValue
}
}
var sectionFooterHeight: CGFloat {
get {
return _tableView.sectionFooterHeight
}
set {
tableView?.sectionFooterHeight = newValue
}
}
var estimatedRowHeight: CGFloat {
get {
return _tableView.estimatedRowHeight
}
set {
tableView?.estimatedRowHeight = newValue
}
}
var estimatedSectionHeaderHeight: CGFloat {
get {
return _tableView.estimatedSectionHeaderHeight
}
set {
tableView?.estimatedSectionHeaderHeight = newValue
}
}
var estimatedSectionFooterHeight: CGFloat {
get {
return _tableView.estimatedSectionFooterHeight
}
set {
tableView?.estimatedSectionFooterHeight = newValue
}
}
var separatorInset: UIEdgeInsets {
get {
return _tableView.separatorInset
}
set {
tableView?.separatorInset = newValue
}
}
var backgroundView: UIView? {
get {
return tableView?.backgroundView
}
set {
tableView?.backgroundView = newValue
}
}
func reloadData() {
tableView?.reloadData()
}
func reloadSectionIndexTitles() {
tableView?.reloadSectionIndexTitles()
}
func numberOfSectionsInTable(_ table: TableSource) -> Int {
return _tableView.numberOfSections
}
func numberOfRowsInSection(_ section: Int, inTable table: TableSource) -> Int {
return _tableView.numberOfRows(inSection: section)
}
func rectForSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _tableView.rect(forSection: section)
}
func rectForHeaderInSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _tableView.rectForHeader(inSection: section)
}
func rectForFooterInSection(_ section: Int, inTable table: TableSource) -> CGRect {
return _tableView.rectForFooter(inSection: section)
}
func rectForRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource) -> CGRect {
return _tableView.rectForRow(at: indexPath)
}
func indexPathForRowAtPoint(_ point: CGPoint, inTable table: TableSource) -> IndexPath? {
return tableView?.indexPathForRow(at: point)
}
func indexPathForCell(_ cell: UITableViewCell, inTable table: TableSource) -> IndexPath? {
return tableView?.indexPath(for: cell)
}
func indexPathsForRowsInRect(_ rect: CGRect, inTable table: TableSource) -> [IndexPath]? {
return tableView?.indexPathsForRows(in: rect)
}
func cellForRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource) -> UITableViewCell? {
return tableView?.cellForRow(at: indexPath)
}
var visibleCells: [UITableViewCell] {
return _tableView.visibleCells
}
func indexPathsForVisibleRowsInTable(_ table: TableSource) -> [IndexPath]? {
return tableView?.indexPathsForVisibleRows
}
func headerViewForSection(_ section: Int, inTable table: TableSource) -> UITableViewHeaderFooterView? {
return tableView?.headerView(forSection: section)
}
func footerViewForSection(_ section: Int, inTable table: TableSource) -> UITableViewHeaderFooterView? {
return tableView?.footerView(forSection: section)
}
func scrollToRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource, atScrollPosition scrollPosition: UITableView.ScrollPosition, animated: Bool) {
tableView?.scrollToRow(at: indexPath, at: scrollPosition, animated: animated)
}
func scrollToNearestSelectedRowAtScrollPosition(_ scrollPosition: UITableView.ScrollPosition, animated: Bool) {
tableView?.scrollToNearestSelectedRow(at: scrollPosition, animated: animated)
}
func beginUpdates() {
tableView?.beginUpdates()
}
func endUpdates() {
tableView?.endUpdates()
}
func insertSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.insertSections(sections, with: animation)
}
func deleteSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.deleteSections(sections, with: animation)
}
func reloadSections(_ sections: IndexSet, inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.reloadSections(sections, with: animation)
}
func moveSection(_ section: Int, toSection newSection: Int, inTable table: TableSource) {
tableView?.moveSection(section, toSection: newSection)
}
func insertRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.insertRows(at: indexPaths, with: animation)
}
func deleteRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.deleteRows(at: indexPaths, with: animation)
}
func reloadRowsAtIndexPaths(_ indexPaths: [IndexPath], inTable table: TableSource, withRowAnimation animation: UITableView.RowAnimation) {
tableView?.reloadRows(at: indexPaths, with: animation)
}
func moveRowAtIndexPath(_ indexPath: IndexPath, toIndexPath newIndexPath: IndexPath, inTable table: TableSource) {
tableView?.moveRow(at: indexPath, to: newIndexPath)
}
var editing: Bool {
get {
return _tableView.isEditing
}
set {
tableView?.isEditing = newValue
}
}
func setEditing(_ editing: Bool, animated: Bool) {
tableView?.setEditing(editing, animated: animated)
}
var allowsSelection: Bool {
get {
return _tableView.allowsSelection
}
set {
tableView?.allowsSelection = newValue
}
}
var allowsSelectionDuringEditing: Bool {
get {
return _tableView.allowsSelectionDuringEditing
}
set {
tableView?.allowsSelectionDuringEditing = newValue
}
}
var allowsMultipleSelection: Bool {
get {
return _tableView.allowsMultipleSelection
}
set {
tableView?.allowsMultipleSelection = newValue
}
}
var allowsMultipleSelectionDuringEditing: Bool {
get {
return _tableView.allowsMultipleSelectionDuringEditing
}
set {
tableView?.allowsMultipleSelectionDuringEditing = newValue
}
}
func indexPathForSelectedRowInTable(_ table: TableSource) -> IndexPath? {
return tableView?.indexPathForSelectedRow
}
func indexPathsForSelectedRowsInTable(_ table: TableSource) -> [IndexPath]? {
return tableView?.indexPathsForSelectedRows
}
func selectRowAtIndexPath(_ indexPath: IndexPath?, inTable table: TableSource, animated: Bool, scrollPosition: UITableView.ScrollPosition) {
tableView?.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
func deselectRowAtIndexPath(_ indexPath: IndexPath, inTable table: TableSource, animated: Bool) {
tableView?.deselectRow(at: indexPath, animated: animated)
}
var sectionIndexMinimumDisplayRowCount: Int {
get {
return _tableView.sectionIndexMinimumDisplayRowCount
}
set {
tableView?.sectionIndexMinimumDisplayRowCount = newValue
}
}
var sectionIndexColor: UIColor? {
get {
return tableView?.sectionIndexColor
}
set {
tableView?.sectionIndexColor = newValue
}
}
var sectionIndexBackgroundColor: UIColor? {
get {
return tableView?.sectionIndexBackgroundColor
}
set {
tableView?.sectionIndexBackgroundColor = newValue
}
}
var sectionIndexTrackingBackgroundColor: UIColor? {
get {
return tableView?.sectionIndexTrackingBackgroundColor
}
set {
tableView?.sectionIndexTrackingBackgroundColor = newValue
}
}
var separatorStyle: UITableViewCell.SeparatorStyle {
get {
return _tableView.separatorStyle
}
set {
tableView?.separatorStyle = newValue
}
}
var separatorColor: UIColor? {
get {
return tableView?.separatorColor
}
set {
tableView?.separatorColor = newValue
}
}
var separatorEffect: UIVisualEffect? {
get {
return tableView?.separatorEffect
}
set {
tableView?.separatorEffect = newValue
}
}
var tableHeaderView: UIView? {
get {
return tableView?.tableHeaderView
}
set {
tableView?.tableHeaderView = newValue
}
}
var tableFooterView: UIView? {
get {
return tableView?.tableFooterView
}
set {
tableView?.tableFooterView = newValue
}
}
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return tableView?.dequeueReusableCell(withIdentifier: identifier)
}
func dequeueReusableCellWithIdentifier(_ identifier: String, forIndexPath indexPath: IndexPath, inTable table: TableSource) -> UITableViewCell {
return _tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
func dequeueReusableHeaderFooterViewWithIdentifier(_ identifier: String) -> UITableViewHeaderFooterView? {
return tableView?.dequeueReusableHeaderFooterView(withIdentifier: identifier)
}
func registerNib(_ nib: UINib?, forCellReuseIdentifier identifier: String) {
tableView?.register(nib, forCellReuseIdentifier: identifier)
}
func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
tableView?.register(cellClass, forCellReuseIdentifier: identifier)
}
func registerNib(_ nib: UINib?, forHeaderFooterViewReuseIdentifier identifier: String) {
tableView?.register(nib, forHeaderFooterViewReuseIdentifier: identifier)
}
func registerClass(_ aClass: AnyClass?, forHeaderFooterViewReuseIdentifier identifier: String) {
tableView?.register(aClass, forHeaderFooterViewReuseIdentifier: identifier)
}
}
| mit | 6d87a96cf643c9629ed0025fa9256ef8 | 29.871314 | 162 | 0.636127 | 5.978712 | false | false | false | false |
insidegui/WWDC | WWDC/SessionsTableViewController.swift | 1 | 24542 | //
// SessionsTableViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 22/04/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RxSwift
import RxCocoa
import RealmSwift
import ConfCore
import os.log
// MARK: - Sessions Table View Controller
class SessionsTableViewController: NSViewController, NSMenuItemValidation {
private let disposeBag = DisposeBag()
weak var delegate: SessionsTableViewControllerDelegate?
var selectedSession = BehaviorRelay<SessionViewModel?>(value: nil)
let style: SessionsListStyle
init(style: SessionsListStyle) {
self.style = style
super.init(nibName: nil, bundle: nil)
identifier = NSUserInterfaceItemIdentifier(rawValue: "videosList")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: MainWindowController.defaultRect.height))
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.darkWindowBackground.cgColor
view.widthAnchor.constraint(lessThanOrEqualToConstant: 675).isActive = true
scrollView.frame = view.bounds
tableView.frame = view.bounds
scrollView.widthAnchor.constraint(greaterThanOrEqualToConstant: 320).isActive = true
view.addSubview(scrollView)
view.addSubview(searchController.view)
searchController.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: searchController.view.bottomAnchor).isActive = true
searchController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
setupContextualMenu()
tableView.rx.selectedRow.map { index -> SessionViewModel? in
guard let index = index else { return nil }
guard case .session(let viewModel) = self.displayedRows[index].kind else { return nil }
return viewModel
}.bind(to: selectedSession).disposed(by: disposeBag)
}
override func viewDidAppear() {
super.viewDidAppear()
view.window?.makeFirstResponder(tableView)
performFirstUpdateIfNeeded()
}
// MARK: - Selection
private var initialSelection: SessionIdentifiable?
private func selectSessionImmediately(with identifier: SessionIdentifiable) {
guard let index = displayedRows.firstIndex(where: { row in
row.represents(session: identifier)
}) else {
return
}
tableView.scrollRowToCenter(index)
tableView.selectRowIndexes(IndexSet([index]), byExtendingSelection: false)
}
func select(session: SessionIdentifiable) {
// If we haven't yet displayed our rows, likely because we haven't come on screen
// yet. We defer scrolling to the requested identifier until that time.
guard hasPerformedInitialRowDisplay else {
initialSelection = session
return
}
let needsToClearSearchToAllowSelection = !isSessionVisible(for: session) && canDisplay(session: session)
if needsToClearSearchToAllowSelection {
searchController.resetFilters()
setFilterResults(.empty, animated: view.window != nil, selecting: session)
} else {
selectSessionImmediately(with: session)
}
}
func scrollToToday() {
sessionRowProvider?.sessionRowIdentifierForToday().flatMap { select(session: $0) }
}
var hasPerformedFirstUpdate = false
/// This function is meant to ensure the table view gets populated
/// even if its data model gets added while it is offscreen. Specifically,
/// when this table view is not the initial active tab.
private func performFirstUpdateIfNeeded() {
guard !hasPerformedFirstUpdate && sessionRowProvider != nil && view.window != nil else { return }
hasPerformedFirstUpdate = true
updateWith(searchResults: filterResults.latestSearchResults, animated: false, selecting: nil)
}
private func updateWith(searchResults: Results<Session>?, animated: Bool, selecting session: SessionIdentifiable?) {
guard hasPerformedFirstUpdate else { return }
guard let results = searchResults else {
setDisplayedRows(sessionRowProvider?.allRows ?? [], animated: animated, overridingSelectionWith: session)
return
}
guard let sessionRowProvider = sessionRowProvider else { return }
let sessionRows = sessionRowProvider.filteredRows(onlyIncludingRowsFor: results)
setDisplayedRows(sessionRows, animated: animated, overridingSelectionWith: session)
}
// MARK: - Updating the Displayed Rows
var sessionRowProvider: SessionRowProvider? {
didSet {
performFirstUpdateIfNeeded()
}
}
private(set) var displayedRows: [SessionRow] = []
lazy var displayedRowsLock = DispatchQueue(label: "io.wwdc.sessiontable.displayedrows.lock\(self.hashValue)", qos: .userInteractive)
private var hasPerformedInitialRowDisplay = false
private func performInitialRowDisplayIfNeeded(displaying rows: [SessionRow]) -> Bool {
guard !hasPerformedInitialRowDisplay else { return true }
hasPerformedInitialRowDisplay = true
displayedRowsLock.suspend()
displayedRows = rows
// Clear filters if there is an initial selection that we can display that isn't gonna be visible
if let initialSelection = self.initialSelection,
!isSessionVisible(for: initialSelection) && canDisplay(session: initialSelection) {
searchController.resetFilters()
_filterResults = .empty
displayedRows = sessionRowProvider?.allRows ?? []
}
tableView.reloadData()
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0
if let deferredSelection = self.initialSelection {
self.initialSelection = nil
self.selectSessionImmediately(with: deferredSelection)
}
// Ensure an initial selection
if self.tableView.selectedRow == -1,
let defaultIndex = rows.firstSessionRowIndex() {
self.tableView.selectRowIndexes(IndexSet(integer: defaultIndex), byExtendingSelection: false)
}
self.scrollView.alphaValue = 1
self.tableView.allowsEmptySelection = false
}, completionHandler: {
self.displayedRowsLock.resume()
})
return false
}
func setDisplayedRows(_ newValue: [SessionRow], animated: Bool, overridingSelectionWith session: SessionIdentifiable?) {
guard performInitialRowDisplayIfNeeded(displaying: newValue) else { return }
// Dismiss the menu when the displayed rows are about to change otherwise it will crash
tableView.menu?.cancelTrackingWithoutAnimation()
displayedRowsLock.async {
let oldValue = self.displayedRows
// Same elements, same order: https://github.com/apple/swift/blob/master/stdlib/public/core/Arrays.swift.gyb#L2203
if oldValue == newValue { return }
let oldRowsSet = Set(oldValue.enumerated().map { IndexedSessionRow(sessionRow: $1, index: $0) })
let newRowsSet = Set(newValue.enumerated().map { IndexedSessionRow(sessionRow: $1, index: $0) })
let removed = oldRowsSet.subtracting(newRowsSet)
let added = newRowsSet.subtracting(oldRowsSet)
let removedIndexes = IndexSet(removed.map { $0.index })
let addedIndexes = IndexSet(added.map { $0.index })
// Only reload rows if their relative positioning changes. This prevents
// cell contents from flashing when cells are unnecessarily reloaded
var needReloadedIndexes = IndexSet()
let sortedOldRows = oldRowsSet.intersection(newRowsSet).sorted(by: { (row1, row2) -> Bool in
return row1.index < row2.index
})
let sortedNewRows = newRowsSet.intersection(oldRowsSet).sorted(by: { (row1, row2) -> Bool in
return row1.index < row2.index
})
for (oldSessionRowIndex, newSessionRowIndex) in zip(sortedOldRows, sortedNewRows) where oldSessionRowIndex.sessionRow != newSessionRowIndex.sessionRow {
needReloadedIndexes.insert(newSessionRowIndex.index)
}
DispatchQueue.main.sync {
var selectedIndexes = IndexSet()
if let session = session,
let overrideIndex = newValue.index(of: session) {
selectedIndexes.insert(overrideIndex)
} else {
// Preserve selected rows if possible
let previouslySelectedRows = self.tableView.selectedRowIndexes.compactMap { (index) -> IndexedSessionRow? in
guard index < oldValue.endIndex else { return nil }
return IndexedSessionRow(sessionRow: oldValue[index], index: index)
}
let newSelection = newRowsSet.intersection(previouslySelectedRows)
if let topOfPreviousSelection = previouslySelectedRows.first, newSelection.isEmpty {
// The update has removed the selected row(s).
// e.g. You have the unwatched filter active and then mark the selection as watched
stride(from: topOfPreviousSelection.index, to: -1, by: -1).lazy.compactMap {
return IndexedSessionRow(sessionRow: oldValue[$0], index: $0)
}.first { (indexedRow: IndexedSessionRow) -> Bool in
newRowsSet.contains(indexedRow)
}.flatMap {
newRowsSet.firstIndex(of: $0)
}.map {
newRowsSet[$0].index
}.map {
selectedIndexes = IndexSet(integer: $0)
}
} else {
selectedIndexes = IndexSet(newSelection.map { $0.index })
}
}
if selectedIndexes.isEmpty, let defaultIndex = newValue.firstSessionRowIndex() {
selectedIndexes.insert(defaultIndex)
}
NSAnimationContext.beginGrouping()
let context = NSAnimationContext.current
context.duration = animated ? 0.35 : 0
context.completionHandler = {
NSAnimationContext.runAnimationGroup({ (context) in
context.allowsImplicitAnimation = animated
self.tableView.scrollRowToCenter(selectedIndexes.first ?? 0)
}, completionHandler: nil)
}
self.tableView.beginUpdates()
self.tableView.removeRows(at: removedIndexes, withAnimation: [.slideLeft])
self.tableView.insertRows(at: addedIndexes, withAnimation: [.slideDown])
// insertRows(::) and removeRows(::) will query the delegate for the row count at the beginning
// so we delay updating the data model until after those methods have done their thing
self.displayedRows = newValue
// This must be after you update the backing model
self.tableView.reloadData(forRowIndexes: needReloadedIndexes, columnIndexes: IndexSet(integersIn: 0..<1))
self.tableView.selectRowIndexes(selectedIndexes, byExtendingSelection: false)
self.tableView.endUpdates()
NSAnimationContext.endGrouping()
}
}
}
func isSessionVisible(for session: SessionIdentifiable) -> Bool {
assert(hasPerformedInitialRowDisplay, "Rows must be displayed before checking this value")
return displayedRows.contains { row -> Bool in
row.represents(session: session)
}
}
func canDisplay(session: SessionIdentifiable) -> Bool {
return sessionRowProvider?.allRows.contains { row -> Bool in
row.represents(session: session)
} ?? false
}
// MARK: - Search
/// Provide a session identifier if you'd like to override the default selection behavior. Provide
/// nil to let the table figure out what selection to apply after the update.
func setFilterResults(_ filterResults: FilterResults, animated: Bool, selecting: SessionIdentifiable?) {
_filterResults = filterResults
filterResults.observe { [weak self] in
self?.updateWith(searchResults: $0, animated: animated, selecting: selecting)
}
}
var _filterResults = FilterResults.empty
private var filterResults: FilterResults {
get {
return _filterResults
}
set {
_filterResults = newValue
filterResults.observe { [weak self] in
self?.updateWith(searchResults: $0, animated: false, selecting: nil)
}
}
}
// MARK: - UI
lazy var searchController = SearchFiltersViewController.loadFromStoryboard()
lazy var tableView: WWDCTableView = {
let v = WWDCTableView()
// We control the intial selection during initialization
v.allowsEmptySelection = true
v.wantsLayer = true
v.focusRingType = .none
v.allowsMultipleSelection = true
v.backgroundColor = .listBackground
v.headerView = nil
v.rowHeight = Metrics.sessionRowHeight
v.autoresizingMask = [.width, .height]
v.floatsGroupRows = true
v.gridStyleMask = .solidHorizontalGridLineMask
v.gridColor = .darkGridColor
if #available(macOS 11.0, *) { v.style = .plain }
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "session"))
v.addTableColumn(column)
return v
}()
lazy var scrollView: NSScrollView = {
let v = NSScrollView()
v.focusRingType = .none
v.backgroundColor = .listBackground
v.borderType = .noBorder
v.documentView = self.tableView
v.hasVerticalScroller = true
v.hasHorizontalScroller = false
v.translatesAutoresizingMaskIntoConstraints = false
v.alphaValue = 0
return v
}()
// MARK: - Contextual menu
fileprivate enum ContextualMenuOption: Int {
case watched = 1000
case unwatched = 1001
case favorite = 1002
case removeFavorite = 1003
case download = 1004
case cancelDownload = 1005
case revealInFinder = 1006
}
private func setupContextualMenu() {
let contextualMenu = NSMenu(title: "TableView Menu")
let watchedMenuItem = NSMenuItem(title: "Mark as Watched", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
watchedMenuItem.option = .watched
contextualMenu.addItem(watchedMenuItem)
let unwatchedMenuItem = NSMenuItem(title: "Mark as Unwatched", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
unwatchedMenuItem.option = .unwatched
contextualMenu.addItem(unwatchedMenuItem)
contextualMenu.addItem(.separator())
let favoriteMenuItem = NSMenuItem(title: "Add to Favorites", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
favoriteMenuItem.option = .favorite
contextualMenu.addItem(favoriteMenuItem)
let removeFavoriteMenuItem = NSMenuItem(title: "Remove From Favorites", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
removeFavoriteMenuItem.option = .removeFavorite
contextualMenu.addItem(removeFavoriteMenuItem)
contextualMenu.addItem(.separator())
let downloadMenuItem = NSMenuItem(title: "Download", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
downloadMenuItem.option = .download
contextualMenu.addItem(downloadMenuItem)
let cancelDownloadMenuItem = NSMenuItem(title: "Cancel Download", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
contextualMenu.addItem(cancelDownloadMenuItem)
cancelDownloadMenuItem.option = .cancelDownload
let revealInFinderMenuItem = NSMenuItem(title: "Reveal in Finder", action: #selector(tableViewMenuItemClicked(_:)), keyEquivalent: "")
contextualMenu.addItem(revealInFinderMenuItem)
revealInFinderMenuItem.option = .revealInFinder
tableView.menu = contextualMenu
}
private func selectedAndClickedRowIndexes() -> IndexSet {
let clickedRow = tableView.clickedRow
let selectedRowIndexes = tableView.selectedRowIndexes
if clickedRow < 0 || selectedRowIndexes.contains(clickedRow) {
return selectedRowIndexes
} else {
return IndexSet(integer: clickedRow)
}
}
@objc private func tableViewMenuItemClicked(_ menuItem: NSMenuItem) {
var viewModels = [SessionViewModel]()
selectedAndClickedRowIndexes().forEach { row in
guard case .session(let viewModel) = displayedRows[row].kind else { return }
viewModels.append(viewModel)
}
guard !viewModels.isEmpty else { return }
switch menuItem.option {
case .watched:
delegate?.sessionTableViewContextMenuActionWatch(viewModels: viewModels)
case .unwatched:
delegate?.sessionTableViewContextMenuActionUnWatch(viewModels: viewModels)
case .favorite:
delegate?.sessionTableViewContextMenuActionFavorite(viewModels: viewModels)
case .removeFavorite:
delegate?.sessionTableViewContextMenuActionRemoveFavorite(viewModels: viewModels)
case .download:
delegate?.sessionTableViewContextMenuActionDownload(viewModels: viewModels)
case .cancelDownload:
delegate?.sessionTableViewContextMenuActionCancelDownload(viewModels: viewModels)
case .revealInFinder:
delegate?.sessionTableViewContextMenuActionRevealInFinder(viewModels: viewModels)
}
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
for row in selectedAndClickedRowIndexes() {
let sessionRow = displayedRows[row]
guard case .session(let viewModel) = sessionRow.kind else { break }
if shouldEnableMenuItem(menuItem: menuItem, viewModel: viewModel) { return true }
}
return false
}
private func shouldEnableMenuItem(menuItem: NSMenuItem, viewModel: SessionViewModel) -> Bool {
switch menuItem.option {
case .watched:
let canMarkAsWatched = !viewModel.session.isWatched
&& viewModel.session.instances.first?.isCurrentlyLive != true
&& viewModel.session.asset(ofType: .streamingVideo) != nil
return canMarkAsWatched
case .unwatched:
return viewModel.session.isWatched || viewModel.session.progresses.count > 0
case .favorite:
return !viewModel.isFavorite
case .removeFavorite:
return viewModel.isFavorite
default: ()
}
switch menuItem.option {
case .download:
return DownloadManager.shared.isDownloadable(viewModel.session) &&
!DownloadManager.shared.isDownloading(viewModel.session) &&
!DownloadManager.shared.hasDownloadedVideo(session: viewModel.session)
case .cancelDownload:
return DownloadManager.shared.isDownloadable(viewModel.session) && DownloadManager.shared.isDownloading(viewModel.session)
case .revealInFinder:
return DownloadManager.shared.hasDownloadedVideo(session: viewModel.session)
default: ()
}
return false
}
}
private extension NSMenuItem {
var option: SessionsTableViewController.ContextualMenuOption {
get {
guard let value = SessionsTableViewController.ContextualMenuOption(rawValue: tag) else {
fatalError("Invalid ContextualMenuOption: \(tag)")
}
return value
}
set {
tag = newValue.rawValue
}
}
}
// MARK: - Datasource / Delegate
extension SessionsTableViewController: NSTableViewDataSource, NSTableViewDelegate {
fileprivate struct Metrics {
static let headerRowHeight: CGFloat = 20
static let sessionRowHeight: CGFloat = 64
}
private struct Constants {
static let sessionCellIdentifier = "sessionCell"
static let titleCellIdentifier = "titleCell"
static let rowIdentifier = "row"
}
func numberOfRows(in tableView: NSTableView) -> Int {
return displayedRows.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let sessionRow = displayedRows[row]
switch sessionRow.kind {
case .session(let viewModel):
return cellForSessionViewModel(viewModel)
case .sectionHeader(let title):
return cellForSectionTitle(title)
}
}
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
var rowView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.rowIdentifier), owner: tableView) as? WWDCTableRowView
if rowView == nil {
rowView = WWDCTableRowView(frame: .zero)
rowView?.identifier = NSUserInterfaceItemIdentifier(rawValue: Constants.rowIdentifier)
}
switch displayedRows[row].kind {
case .sectionHeader:
rowView?.isGroupRowStyle = true
default:
rowView?.isGroupRowStyle = false
}
return rowView
}
private func cellForSessionViewModel(_ viewModel: SessionViewModel) -> SessionTableCellView? {
var cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.sessionCellIdentifier), owner: tableView) as? SessionTableCellView
if cell == nil {
cell = SessionTableCellView(frame: .zero)
cell?.identifier = NSUserInterfaceItemIdentifier(rawValue: Constants.sessionCellIdentifier)
}
cell?.viewModel = viewModel
return cell
}
private func cellForSectionTitle(_ title: String) -> TitleTableCellView? {
var cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.titleCellIdentifier), owner: tableView) as? TitleTableCellView
if cell == nil {
cell = TitleTableCellView(frame: .zero)
cell?.identifier = NSUserInterfaceItemIdentifier(rawValue: Constants.titleCellIdentifier)
}
cell?.title = title
return cell
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
switch displayedRows[row].kind {
case .session:
return Metrics.sessionRowHeight
case .sectionHeader:
return Metrics.headerRowHeight
}
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
switch displayedRows[row].kind {
case .sectionHeader:
return false
case .session:
return true
}
}
func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool {
switch displayedRows[row].kind {
case .sectionHeader:
return true
case .session:
return false
}
}
}
| bsd-2-clause | be623429dd4c246885f2c884e665e253 | 36.183333 | 170 | 0.650422 | 5.381798 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Race View Controllers/GameViewController/GameViewController+UI.swift | 2 | 6493 | //
// GameViewController+UI.swift
// WikiRaces
//
// Created by Andrew Finke on 8/5/17.
// Copyright © 2017 Andrew Finke. All rights reserved.
//
import UIKit
import WKRUIKit
extension GameViewController {
// MARK: - Interface
override var prefersHomeIndicatorAutoHidden: Bool {
return true
}
func setupInterface() {
guard let navigationController = navigationController,
let navigationView = navigationController.view else {
fatalError("No navigation controller view")
}
helpBarButtonItem = WKRUIBarButtonItem(
systemName: "questionmark",
target: self,
action: #selector(helpButtonPressed))
quitBarButtonItem = WKRUIBarButtonItem(
systemName: "xmark",
target: self,
action: #selector(quitButtonPressed))
navigationItem.hidesBackButton = true
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
navigationView.addSubview(navigationBarBottomLine)
setupElements()
setupProgressView()
let constraints: [NSLayoutConstraint] = [
navigationBarBottomLine.topAnchor.constraint(equalTo: navigationView.bottomAnchor),
navigationBarBottomLine.leftAnchor.constraint(equalTo: navigationView.leftAnchor),
navigationBarBottomLine.rightAnchor.constraint(equalTo: navigationView.rightAnchor),
navigationBarBottomLine.heightAnchor.constraint(equalToConstant: 1),
connectingLabel.widthAnchor.constraint(equalTo: view.widthAnchor),
connectingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
connectingLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 185),
activityIndicatorView.topAnchor.constraint(equalTo: connectingLabel.bottomAnchor, constant: 25),
activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
]
NSLayoutConstraint.activate(constraints)
navigationController.setNavigationBarHidden(true, animated: false)
}
// MARK: - Elements
private func setupElements() {
navigationBarBottomLine.alpha = 0
navigationBarBottomLine.translatesAutoresizingMaskIntoConstraints = false
connectingLabel.translatesAutoresizingMaskIntoConstraints = false
connectingLabel.alpha = 0.0
connectingLabel.text = "PREPARING"
connectingLabel.textAlignment = .center
connectingLabel.font = UIFont.systemFont(ofSize: 24, weight: .medium)
view.addSubview(connectingLabel)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.alpha = 0.0
activityIndicatorView.color = .darkText
activityIndicatorView.startAnimating()
view.addSubview(activityIndicatorView)
}
private func setupProgressView() {
progressView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressView)
let constraints: [NSLayoutConstraint] = [
progressView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
progressView.leftAnchor.constraint(equalTo: view.leftAnchor),
progressView.rightAnchor.constraint(equalTo: view.rightAnchor),
progressView.heightAnchor.constraint(equalToConstant: 4)
]
NSLayoutConstraint.activate(constraints)
}
func setupNewWebView() {
webView?.removeFromSuperview()
let webView = WKRUIWebView()
view.addSubview(webView)
view.bringSubviewToFront(progressView)
webView.progressView = progressView
let constraints: [NSLayoutConstraint] = [
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
webView.leftAnchor.constraint(equalTo: view.leftAnchor),
webView.rightAnchor.constraint(equalTo: view.rightAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
NSLayoutConstraint.activate(constraints)
gameManager.webView = webView
self.webView = webView
}
// MARK: - Alerts
func quitAlertController(raceStarted: Bool) -> UIAlertController {
let message = "Are you sure you want to leave the match?"
let alertController = UIAlertController(title: "Leave the Match?",
message: message,
preferredStyle: .alert)
alertController.addCancelAction(title: "Keep Playing")
if raceStarted {
let forfeitAction = UIAlertAction(title: "Forfeit Race", style: .default) { [weak self] _ in
PlayerFirebaseAnalytics.log(event: .userAction("quitAlertController:forfeit"))
PlayerFirebaseAnalytics.log(event: .forfeited, attributes: ["Page": self?.finalPage?.title as Any])
self?.gameManager.player(.forfeited)
}
alertController.addAction(forfeitAction)
let reloadAction = UIAlertAction(title: "Reload Page", style: .default) { _ in
PlayerFirebaseAnalytics.log(event: .userAction("quitAlertController:reload"))
PlayerFirebaseAnalytics.log(event: .usedReload)
self.webView?.reload()
}
alertController.addAction(reloadAction)
}
let quitAction = UIAlertAction(title: "Leave Match", style: .destructive) { [weak self] _ in
PlayerFirebaseAnalytics.log(event: .userAction("quitAlertController:quit"))
PlayerFirebaseAnalytics.log(event: .quitRace, attributes: nil)
self?.attemptQuit()
}
alertController.addAction(quitAction)
return alertController
}
func attemptQuit() {
guard transitionState == TransitionState.none || transitionState == TransitionState.inProgress else {
return
}
if transitionState == .none {
performQuit()
} else {
transitionState = .quitting(.waiting)
}
}
func performQuit() {
transitionState = .quitting(.inProgress)
resetActiveControllers()
gameManager.player(.quit)
NotificationCenter.default.post(name: NSNotification.Name.localPlayerQuit,
object: nil)
}
}
| mit | 3f0d187a9d5e3320b977b6bccf64fefb | 36.744186 | 115 | 0.661429 | 5.714789 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatStickersTouchBarPopover.swift | 1 | 7291 | //
// ChatStickersTouchBarPopover.swift
// Telegram
//
// Created by Mikhail Filimonov on 14/09/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import HackUtils
import Postbox
import SwiftSignalKit
@available(OSX 10.12.2, *)
fileprivate extension NSTouchBarItem.Identifier {
static let sticker = NSTouchBarItem.Identifier("\(Bundle.main.bundleIdentifier!).touchBar.chat.sticker")
}
@available(OSX 10.12.2, *)
private extension NSTouchBar.CustomizationIdentifier {
static let stickersScrubber = NSTouchBar.CustomizationIdentifier("\(Bundle.main.bundleIdentifier!).touchBar.chat.StickersScrubber")
}
enum TouchBarStickerEntry {
case header(TextViewLayout)
case sticker(TelegramMediaFile)
}
@available(OSX 10.12.2, *)
class StickersScrubberBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource, NSScrubberFlowLayoutDelegate {
private static let stickerItemViewIdentifier = "StickersItemViewIdentifier"
private static let headerItemViewIdentifier = "HeaderItemViewIdentifier"
private let entries: [TouchBarStickerEntry]
private let context: AccountContext
private let sendSticker: (TelegramMediaFile)->Void
private let animated: Bool
init(identifier: NSTouchBarItem.Identifier, context: AccountContext, animated: Bool, sendSticker:@escaping(TelegramMediaFile)->Void, entries: [TouchBarStickerEntry]) {
self.entries = entries
self.context = context
self.sendSticker = sendSticker
self.animated = animated
super.init(identifier: identifier)
let scrubber = TGScrubber()
scrubber.register(TouchBarStickerItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(rawValue: StickersScrubberBarItem.stickerItemViewIdentifier))
scrubber.register(TouchBarScrubberHeaderItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(rawValue: StickersScrubberBarItem.headerItemViewIdentifier))
scrubber.mode = .free
scrubber.selectionBackgroundStyle = .roundedBackground
scrubber.floatsSelectionViews = true
scrubber.delegate = self
scrubber.dataSource = self
let gesture = NSPressGestureRecognizer(target: self, action: #selector(self.pressGesture(_:)))
gesture.allowedTouchTypes = NSTouch.TouchTypeMask.direct
gesture.minimumPressDuration = 0.3
gesture.allowableMovement = 0
scrubber.addGestureRecognizer(gesture)
self.view = scrubber
}
fileprivate var modalPreview: PreviewModalController?
@objc private func pressGesture(_ gesture: NSPressGestureRecognizer) {
let runSelector:()->Void = { [weak self] in
guard let `self` = self else {
return
}
let scrollView = HackUtils.findElements(byClass: "NSScrollView", in: self.view)?.first as? NSScrollView
guard let container = scrollView?.documentView?.subviews.first else {
return
}
var point = gesture.location(in: container)
point.y = 0
for itemView in container.subviews {
if NSPointInRect(point, itemView.frame) {
if let itemView = itemView as? TouchBarStickerItemView {
self.modalPreview?.update(with: itemView.quickPreview)
}
}
}
}
switch gesture.state {
case .began:
modalPreview = PreviewModalController(context)
showModal(with: modalPreview!, for: context.window)
runSelector()
case .failed, .cancelled, .ended:
modalPreview?.close()
modalPreview = nil
case .changed:
runSelector()
case .possible:
break
@unknown default:
break
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfItems(for scrubber: NSScrubber) -> Int {
return entries.count
}
func scrubber(_ scrubber: NSScrubber, didHighlightItemAt highlightedIndex: Int) {
switch entries[highlightedIndex] {
case .header:
scrubber.selectionBackgroundStyle = nil
scrubber.selectedIndex = -1
default:
scrubber.selectionBackgroundStyle = .roundedBackground
}
}
func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
let itemView: NSScrubberItemView
switch entries[index] {
case let .header(title):
let view = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: StickersScrubberBarItem.headerItemViewIdentifier), owner: nil) as! TouchBarScrubberHeaderItemView
view.update(title)
itemView = view
case let .sticker(file):
let view = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: StickersScrubberBarItem.stickerItemViewIdentifier), owner: nil) as! TouchBarStickerItemView
view.update(context: context, file: file, animated: self.animated)
itemView = view
}
return itemView
}
func scrubber(_ scrubber: NSScrubber, layout: NSScrubberFlowLayout, sizeForItemAt itemIndex: Int) -> NSSize {
switch entries[itemIndex] {
case let .header(layout):
return NSMakeSize(layout.layoutSize.width + 20, 30)
case .sticker:
return NSSize(width: 40, height: 30)
}
}
func scrubber(_ scrubber: NSScrubber, didSelectItemAt index: Int) {
switch entries[index] {
case let .sticker(file):
sendSticker(file)
default:
break
}
}
}
@available(OSX 10.12.2, *)
final class ChatStickersTouchBarPopover : NSTouchBar, NSTouchBarDelegate {
private let chatInteraction: ChatInteraction
private let entries: [TouchBarStickerEntry]
private let dismiss:(TelegramMediaFile?) -> Void
init(chatInteraction: ChatInteraction, dismiss:@escaping(TelegramMediaFile?)->Void, entries: [TouchBarStickerEntry]) {
self.dismiss = dismiss
self.entries = entries
self.chatInteraction = chatInteraction
super.init()
delegate = self
customizationIdentifier = .stickersScrubber
defaultItemIdentifiers = [.sticker]
customizationAllowedItemIdentifiers = [.sticker]
}
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .sticker:
let scrubberItem: NSCustomTouchBarItem = StickersScrubberBarItem(identifier: identifier, context: chatInteraction.context, animated: true, sendSticker: { [weak self] file in
self?.dismiss(file)
}, entries: self.entries)
return scrubberItem
default:
return nil
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 2e9fa587ce07b653e261c6710566c4db | 35.268657 | 195 | 0.659396 | 5.344575 | false | false | false | false |
J-Mendes/Weather | Weather/WeatherUITests/Utils/TextUtils.swift | 1 | 1345 | //
// TextUtils.swift
// Weather
//
// Created by Jorge Mendes on 08/07/17.
// Copyright © 2017 Jorge Mendes. All rights reserved.
//
import Foundation
class TextUtils {
// MARK: - Static text utils
class var currentLanguage: (langCode: String, localeCode: String)? {
let currentLocale = Locale(identifier: Locale.preferredLanguages.first!)
guard let langCode = currentLocale.languageCode else {
return nil
}
var localeCode = langCode
if let scriptCode = currentLocale.scriptCode {
localeCode = "\(langCode)-\(scriptCode)"
} else if let regionCode = currentLocale.regionCode {
localeCode = "\(langCode)-\(regionCode)"
}
return (langCode, localeCode)
}
class func localizedString(_ key: String) -> String {
let testBundle = Bundle(for: WeatherUITests.self)
if let currentLanguage = currentLanguage,
let testBundlePath = testBundle.path(forResource: currentLanguage.localeCode, ofType: "lproj") ?? testBundle.path(forResource: currentLanguage.langCode, ofType: "lproj"),
let localizedBundle = Bundle(path: testBundlePath) {
return NSLocalizedString(key, bundle: localizedBundle, comment: "")
}
return "?"
}
}
| gpl-3.0 | 688e9cb49d201b63379b338e1d032929 | 31 | 182 | 0.625744 | 4.905109 | false | true | false | false |
johndpope/Coiffeur | Coiffeur/src/AppDelegate.swift | 1 | 3299 | //
// AppDelegate.swift
// Coiffeur
//
// Created by Anton Leuski on 4/7/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
@NSApplicationMain
class AppDelegate : NSObject, NSApplicationDelegate {
private struct Private {
static private let AboutFileName = "about"
static private let AboutFileNameExtension = "html"
static private let UserDefaultsFileNameExtension = "plist"
static private let UserDefaultsFileName = "UserDefaults"
}
@IBOutlet weak var languagesMenu : NSMenu!
@IBOutlet weak var makeNewDocumentMenu : NSMenu!
var bundle : NSBundle {
return NSBundle.mainBundle()
}
var aboutURL : NSURL? {
return self.bundle.URLForResource(Private.AboutFileName,
withExtension:Private.AboutFileNameExtension)
}
override init()
{
super.init()
DocumentController() // load ours...
MGSFragaria.initializeFramework()
let bundle = NSBundle(forClass:self.dynamicType)
if let UDURL = bundle.URLForResource(Private.UserDefaultsFileName,
withExtension:Private.UserDefaultsFileNameExtension),
let ud = NSDictionary(contentsOfURL:UDURL) as? [String:AnyObject]
{
NSUserDefaults.standardUserDefaults().registerDefaults(ud)
}
}
func applicationDidFinishLaunching(aNotification:NSNotification)
{
for l in Language.supportedLanguages {
var item = NSMenuItem(title: l.displayName,
action: "changeLanguage:", keyEquivalent: "")
item.representedObject = l
self.languagesMenu.addItem(item)
}
var count = 0
for aClass in CoiffeurController.availableTypes {
var item = NSMenuItem(title: aClass.documentType,
action: "openUntitledDocumentOfType:", keyEquivalent: "")
item.representedObject = aClass.documentType
if (count < 2) {
item.keyEquivalent = "n"
var mask = NSEventModifierFlags.CommandKeyMask
if (count > 0) {
mask |= NSEventModifierFlags.AlternateKeyMask
}
item.keyEquivalentModifierMask = Int(mask.rawValue)
}
self.makeNewDocumentMenu.addItem(item)
++count
}
}
func applicationWillTerminate(aNotification:NSNotification)
{
// Insert code here to tear down your application
}
@IBAction func openUntitledDocumentOfType(sender : AnyObject)
{
if let type = sender.representedObject as? String {
let controller = NSDocumentController.sharedDocumentController()
as! DocumentController
var error : NSError?
if nil == controller.openUntitledDocumentOfType(type,
display:true, error:&error)
{
if error != nil {
NSApp.presentError(error!)
}
}
}
}
}
| apache-2.0 | b30120abb782d42985e6b749f6a9f2de | 27.439655 | 76 | 0.692634 | 4.476255 | false | false | false | false |
huangboju/Moots | Examples/Thread/Thread_Swift3.0/Thread_Swift3.0/SecondController.swift | 1 | 21256 | //
// SecondController.swift
// Thread_Swift3.0
//
// Created by 伯驹 黄 on 2016/10/26.
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
// https://www.allaboutswift.com/dev/2016/7/12/gcd-with-swfit3
// http://www.cnblogs.com/ludashi/p/5336169.html
// https://justinyan.me/post/2420
// https://bestswifter.com/deep-gcd/
// http://www.cocoachina.com/ios/20170829/20404.html
class SecondController: UIViewController {
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
let tags: [[(String, Selector)]] = [
[
("同步执行串行队列", #selector(performSerialQueuesUseSynchronization)),
("同步执行并行队列", #selector(performConcurrentQueuesUseSynchronization))
],
[
("异步执行串行队列", #selector(performSerialQueuesUseAsynchronization)),
("异步执行并行队列", #selector(performConcurrentQueuesUseAsynchronization))
],
[
("延迟执行", #selector(deferPerform))
],
[
("设置全局队列的优先级", #selector(globalQueuePriority)),
("设置自建队列优先级", #selector(setCustomeQueuePriority))
],
[
("自动执行任务组", #selector(autoGlobalQueue)),
("手动执行任务组", #selector(performGroupUseEnterAndleave))
],
[
("使用信号量添加同步锁", #selector(useSemaphoreLock))
],
[
("使用Apply循环执行", #selector(useDispatchApply)),
("暂停和重启队列", #selector(queueSuspendAndResume)),
("使用任务隔离栅栏", #selector(useBarrierAsync))
],
[
("dispatch源,ADD", #selector(useDispatchSourceAdd)),
("dispatch源,OR", #selector(useDispatchSourceOR)),
("dispatch源,定时器", #selector(useDispatchSourceTimer))
],
[
("不同queue opration 依赖", #selector(diffQueue))
]
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Swift5.0 GCD"
view.addSubview(tableView)
}
@objc func performSerialQueuesUseSynchronization() {
let queue = DispatchQueue(label: "syn.serial.queue")
for i in 0..<3 {
queue.sync() {
currentThreadSleep(1)
print("当前执行线程:\(Thread.current)")
print("执行\(i.toEmoji)")
}
print("\(i.toEmoji)执行完毕")
}
print("所有队列使用同步方式执行完毕")
ended()
}
@objc func performConcurrentQueuesUseSynchronization() {
let queue = DispatchQueue(label: "syn.concurrent.queue", attributes: .concurrent)
for i in 0..<3 {
queue.sync() {
currentThreadSleep(1)
print("当前执行线程:\(Thread.current)")
print("执行\(i.toEmoji)")
}
print("\(i.toEmoji)执行完毕")
}
print("所有队列使用同步方式执行完毕")
ended()
}
@objc func performSerialQueuesUseAsynchronization() {
//一个串行队列,用于同步执行
let queue = DispatchQueue(label: "asyn.serial.queue")
let group = DispatchGroup()
let q = DispatchQueue(label: "serialQueue")
for i in 0..<3 {
group.enter()
queue.async(group: group) {
self.currentThreadSleep(Double(arc4random()%3))
let currentThread = Thread.current
q.sync { //同步锁
group.leave()
print("①Sleep的线程\(currentThread)")
print("②当前输出内容的线程\(Thread.current)")
print("③执行\(i.toEmoji):\(queue)\n")
}
}
print("\(i.toEmoji)添加完毕\n")
}
print("使用异步方式添加队列")
group.notify(queue: DispatchQueue.main) {
self.ended()
}
}
@objc func performConcurrentQueuesUseAsynchronization() {
//一个串行队列,用于同步执行
let queue = DispatchQueue(label: "asyn.concurrent.queue", attributes: .concurrent)
let group = DispatchGroup()
let q = DispatchQueue(label: "serialQueue")
for i in 0..<3 {
group.enter()
queue.async(group: group) {
self.currentThreadSleep(Double(arc4random()%3))
let currentThread = Thread.current
print("asyn.concurrent.queue", currentThread)
q.sync { //同步锁
group.leave()
print("①Sleep的线程\(currentThread)")
print("②当前输出内容的线程\(Thread.current)")
print("③执行\(i.toEmoji):\(queue)\n")
}
}
print("\(i.toEmoji)添加完毕\n")
}
print("使用异步方式添加队列")
group.notify(queue: DispatchQueue.main) {
self.ended()
}
}
@objc func diffQueue() {
let queue1 = OperationQueue()
queue1.name = "queue1"
let queue2 = OperationQueue()
queue2.name = "queue2"
let opration1 = BlockOperation {
sleep(2)
print("我是1")
}
queue1.addOperation(opration1)
let opration2 = BlockOperation {
print("我是2")
}
opration2.addDependency(opration1)
queue2.addOperation(opration2)
}
func currentThreadSleep(_ timer: TimeInterval) {
print("😪😪😪延时😪😪😪")
Thread.sleep(forTimeInterval: timer)
}
/// 创建并行队列
func getConcurrentQueue(_ label: String) -> DispatchQueue {
return DispatchQueue(label: label, attributes: .concurrent)
}
/// 延迟执行
@objc func deferPerform(_ time: Int = 1) {
let semaphore = DispatchSemaphore(value: 0)
let queue = globalQueue()
let delaySecond = DispatchTimeInterval.seconds(time)
print(Date())
let delayTime = DispatchTime.now() + delaySecond
queue.asyncAfter(deadline: delayTime) {
print("执行线程:\(Thread.current)\ndispatch_time: 延迟\(time)秒执行\n",Date())
semaphore.signal()
}
//DispatchWallTime用于计算绝对时间,而DispatchWallTime是根据挂钟来计算的时间,即使设备睡眠了,他也不会睡眠。
// let nowInterval = Date().timeIntervalSince1970
// let nowStruct = timespec(tv_sec: Int(nowInterval), tv_nsec: 0)
// let delayWalltime = DispatchWallTime(timespec: nowStruct)
let delayWalltime = DispatchWallTime.now() + delaySecond
queue.asyncAfter(wallDeadline: delayWalltime) {
print("执行线程:\(Thread.current)\ndispatch_walltime: 延迟\(time)秒执行\n", Date())
}
semaphore.wait()
ended()
}
/// 全局队列的优先级关系
@objc func globalQueuePriority() {
//高 > 默认 > 低 > 后台
let queueHeight = globalQueue(qos: .userInitiated)
let queueDefault = globalQueue()
let queueLow = globalQueue(qos: .utility)
let queueBackground = globalQueue(qos: .background)
let group = DispatchGroup()
//优先级不是绝对的,大体上会按这个优先级来执行。 一般都是使用默认(default)优先级
queueLow.async(group: group) {
print("Low:\(Thread.current)")
}
queueBackground.async(group: group) {
print("Background:\(Thread.current)")
}
queueDefault.async(group: group) {
print("Default:\(Thread.current)")
}
queueHeight.async(group: group) {
print("High:\(Thread.current)")
}
group.wait()
ended()
}
/// 给串行队列或者并行队列设置优先级
@objc func setCustomeQueuePriority() {
//优先级的执行顺序也不是绝对的
//给serialQueueHigh设定DISPATCH_QUEUE_PRIORITY_HIGH优先级
let serialQueueHigh = DispatchQueue(label: "cn.zeluli.serial1")
globalQueue(qos: .userInitiated).setTarget(queue: serialQueueHigh)
let serialQueueLow = DispatchQueue(label: "cn.zeluli.serial1")
globalQueue(qos: .utility).setTarget(queue: serialQueueLow)
serialQueueLow.async {
print("低:\(Thread.current)")
}
serialQueueHigh.async {
print("高:\(Thread.current)")
self.ended()
}
}
func performGroupQueue() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
let group = DispatchGroup()
//将group与queue进行管理,并且自动执行
for i in 1...3 {
concurrentQueue.async(group: group) {
self.currentThreadSleep(1)
print("任务\(i)执行完毕\n")
}
}
//队列组的都执行完毕后会进行通知
group.notify(queue: DispatchQueue.main) {
self.ended()
}
print("异步执行测试,不会阻塞当前线程")
}
@objc func autoGlobalQueue() {
globalQueue().async {
self.performGroupQueue()
}
}
/// 使用enter与leave手动管理group与queue
@objc func performGroupUseEnterAndleave() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
let group = DispatchGroup()
//将group与queue进行手动关联和管理,并且自动执行
for i in 1...3 {
group.enter() //进入队列组
concurrentQueue.async {
self.currentThreadSleep(1)
print("任务\(i.toEmoji)执行完毕\n")
group.leave() //离开队列组
}
}
_ = group.wait(timeout: .distantFuture) //阻塞当前线程,直到所有任务执行完毕
print("任务组执行完毕")
group.notify(queue: concurrentQueue) {
self.ended()
}
}
//信号量同步锁
@objc func useSemaphoreLock() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
//创建信号量
let semaphoreLock = DispatchSemaphore(value: 2)
var testNumber = 0
for index in 0 ... 9 {
concurrentQueue.async {
let wait = semaphoreLock.wait(timeout: .distantFuture) //上锁
print("wait=\(wait)")
testNumber += 1
self.currentThreadSleep(1)
print(Thread.current)
print("第\(index.toEmoji)次执行: testNumber = \(testNumber)\n")
semaphoreLock.signal() //开锁
}
}
}
@objc func useBarrierAsync() {
// 那你啥时候改用 barrier 方法,啥时候不该用呢?
//
// * 自定义串行队列 Custom Serial Queue: 没有必要在串行队列中使用,barrier 对于串行队列来说毫无用处,因为本来串行队列就是一次只会执行一个任务的。
// * 全局并发队列 Global Concurrent Queue: 要小心使用。在全局队列中使用 barrier 可能不是太好,因为系统也会使用这个队列,一般你不会希望自己的操作垄断了这个队列从而导致系统调用的延迟。
// * 自定义并发队列 Custom Concurrent Queue: 对于需要原子操作和访问临界区的代码,barrier 方法是最佳使用场景。任何你需要线程安全的实例,barrier 都是一个不错的选择。
let concurrentQueue = getConcurrentQueue("cn.zeluli")
for i in 0...2 {
concurrentQueue.async {
self.currentThreadSleep(Double(i))
print("第一批:\(i.toEmoji)\(Thread.current)")
}
}
for i in 0...3 {
concurrentQueue.async(flags: .barrier) {
self.currentThreadSleep(Double(i))
print("第二批:\(i.toEmoji)\(Thread.current)")
}
}
let workItem = DispatchWorkItem(flags: .barrier) {
print("\n第二批执行完毕后才会执行第三批\n\(Thread.current)\n")
}
concurrentQueue.async(execute: workItem)
for i in 0...3 {
concurrentQueue.async {
self.currentThreadSleep(Double(i))
print("第三批:\(i.toEmoji)\(Thread.current)")
}
}
print("😁😁😁不会阻塞主线程😁😁😁")
}
/// 循环执行
@objc func useDispatchApply() {
print("循环多次执行并行队列")
DispatchQueue.global(qos: .background).async {
DispatchQueue.concurrentPerform(iterations: 3) { index in
self.currentThreadSleep(Double(index))
print("第\(index)次执行,\n\(Thread.current)\n")
}
DispatchQueue.main.async {
self.ended()
}
}
}
//暂停和重启队列
@objc func queueSuspendAndResume() {
let concurrentQueue = getConcurrentQueue("cn.zeluli")
concurrentQueue.suspend() //将队列进行挂起
concurrentQueue.async {
print("任务执行, \(Thread.current)")
}
currentThreadSleep(2)
concurrentQueue.resume() //将挂起的队列进行唤醒
ended()
}
/// 以加法运算的方式合并数据
// http://www.tanhao.me/pieces/360.html/
@objc func useDispatchSourceAdd() {
var sum = 0 //手动计数的sum, 来模拟记录merge的数据
let queue = globalQueue()
//创建source
let dispatchSource = DispatchSource.makeUserDataAddSource(queue: queue)
dispatchSource.setEventHandler() {
print("source中所有的数相加的和等于\(dispatchSource.data)")
print("sum = \(sum)\n")
sum = 0
self.currentThreadSleep(0.3)
}
// DispatchQueue启动时默认状态是挂起的,创建完毕之后得主动恢复,否则事件不会被传送
dispatchSource.resume()
for i in 1...10 {
sum += i
print("i=\(i)")
dispatchSource.add(data: UInt(i))
currentThreadSleep(0.1)
}
ended()
}
/// 以或运算的方式合并数据
@objc func useDispatchSourceOR() {
var or = 0 //手动计数的sum, 来记录merge的数据
let queue = globalQueue()
//创建source
let dispatchSource = DispatchSource.makeUserDataOrSource(queue: queue)
dispatchSource.setEventHandler {
print("source中所有的数相加的和等于\(dispatchSource.data)")
print("or = \(or)\n")
or = 0
self.currentThreadSleep(0.3)
}
dispatchSource.resume()
for i in 1...10 {
or |= i
print("i=\(i)")
dispatchSource.or(data: UInt(i))
currentThreadSleep(0.1)
}
print("\nsum = \(or)")
}
/// 使用DispatchSource创建定时器
@objc func useDispatchSourceTimer() {
let queue = globalQueue()
let source = DispatchSource.makeTimerSource(queue: queue)
// deadline 结束时间
// interval 时间间隔
// leeway 时间精度
// source.schedule(deadline: .now(), leeway: .nanoseconds(0))
source.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(0))
// source.scheduleRepeating(deadline: .now(), interval: 1, leeway: .nanoseconds(0))
var timeout = 10 //倒计时时间
//设置要处理的事件, 在我们上面创建的queue队列中进行执行
source.setEventHandler {
print(Thread.current)
if timeout <= 0 {
source.cancel()
} else {
print("\(timeout)s", Date())
timeout -= 1
}
}
//倒计时结束的事件
source.setCancelHandler {
print("倒计时结束")
}
source.resume()
}
func ended() { print("**************************结束**************************\n") }
// http://www.jianshu.com/p/7efbecee6af8
/*
* DISPATCH_QUEUE_PRIORITY_HIGH: .userInitiated
* DISPATCH_QUEUE_PRIORITY_DEFAULT: .default
* DISPATCH_QUEUE_PRIORITY_LOW: .utility
* DISPATCH_QUEUE_PRIORITY_BACKGROUND: .background
*/
// * QOS_CLASS_USER_INTERACTIVE:User Interactive(用户交互)类的任务关乎用户体验,这类任务是需要立刻被执行的。这类任务应该用在更新 UI,处理事件,执行一些需要低延迟的轻量的任务。这种类型的任务应该要压缩到尽可能少。
// * QOS_CLASS_USER_INITIATED: User Initiated(用户发起)类是指由 UI 发起的可以异步执行的任务。当用户在等待任务返回的结果,然后才能执行下一步动作的时候可以使用这种类型。
// * QOS_CLASS_UTILITY:Utility(工具)类是指耗时较长的任务,通常会展示给用户一个进度条。这种类型应该用在大量计算,I/O 操作,网络请求,实时数据推送之类的任务。这个类是带有节能设计的。
// * QOS_CLASS_BACKGROUND:background(后台)类是指用户并不会直接感受到的任务。这个类应该用在数据预拉取,维护以及其他不需要用户交互,对时间不敏感的任务。
func globalQueue(qos: DispatchQoS.QoSClass = .default) -> DispatchQueue {
return DispatchQueue.global(qos: qos)
}
}
extension DispatchQueue {
private static var _onceTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token: String, block: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
}
extension Int {
var toEmoji: String {
let dict = [
0: "0️⃣",
1: "1️⃣",
2: "2️⃣",
3: "3️⃣",
4: "4️⃣",
5: "5️⃣",
6: "6️⃣",
7: "7️⃣",
8: "8️⃣",
9: "9️⃣",
]
return dict[self] ?? self.description
}
}
extension SecondController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return tags.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tags[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}
}
extension SecondController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.tintColor = UIColor.red
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = tags[indexPath.section][indexPath.row].0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let tag = tags[indexPath.section][indexPath.row]
print("🍀🍀🍀\(tag.0)🍀🍀🍀")
print("**************************开始**************************")
perform(tag.1)
}
}
| mit | 5657cc9023e099773280f7a4f660ac96 | 29.91015 | 139 | 0.536255 | 4.235522 | false | false | false | false |
n8armstrong/ching | Ching/Playground.playground/Contents.swift | 1 | 673 | //: Playground - noun: a place where people can play
import UIKit
NSDecimalNumber(string: "100.01", locale: NSLocale.currentLocale())
NSDecimalNumber(string: "192.168.1.1", locale: NSLocale.currentLocale())
NSDecimalNumber(string: "192abc", locale: NSLocale.currentLocale())
let num = NSDecimalNumber(string: "0", locale: NSLocale.currentLocale())
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.locale = NSLocale.currentLocale()
formatter.currencySymbol = ""
formatter.stringFromNumber(num)
NSDate(timeIntervalSinceNow: -(60 * 60 * 24 * 32))
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.dateFromString("2015-08-10")
| mit | 001da274ea6b104847d0364e4c16a45e | 31.047619 | 72 | 0.762259 | 4.02994 | false | false | false | false |
tomlokhorst/swift-cancellationtoken | Sources/CancellationToken/CancellationToken.swift | 1 | 2824 | //
// CancellationToken.swift
// CancellationToken
//
// Created by Tom Lokhorst on 2014-10-31.
//
//
import Foundation
/**
A `CancellationToken` indicates if cancellation of "something" was requested.
Can be passed around and checked by whatever wants to be cancellable.
To create a cancellation token, use `CancellationTokenSource`.
*/
public struct CancellationToken {
private weak var source: CancellationTokenSource?
internal init(source: CancellationTokenSource) {
self.source = source
}
public var isCancellationRequested: Bool {
return source?.isCancellationRequested ?? true
}
public func register(_ handler: @escaping () -> Void) {
guard let source = source else {
return handler()
}
source.register(handler)
}
}
/**
A `CancellationTokenSource` is used to create a `CancellationToken`.
The created token can be set to "cancellation requested" using the `cancel()` method.
*/
public class CancellationTokenSource {
private let internalState: InternalState
fileprivate var isCancellationRequested: Bool {
return internalState.readCancelled()
}
public init() {
internalState = InternalState()
}
deinit {
tryCancel()
}
public var token: CancellationToken {
return CancellationToken(source: self)
}
public func register(_ handler: @escaping () -> Void) {
if let handler = internalState.addHandler(handler) {
handler()
}
}
public func cancel() {
tryCancel()
}
public func cancelAfter(deadline dispatchTime: DispatchTime) {
// On a background queue
let queue = DispatchQueue.global(qos: .userInitiated)
queue.asyncAfter(deadline: dispatchTime) { [weak self] in
self?.tryCancel()
}
}
public func cancelAfter(timeInterval: TimeInterval) {
cancelAfter(deadline: .now() + timeInterval)
}
internal func tryCancel() {
let handlers = internalState.tryCancel()
// Call all previously scheduled handlers
for handler in handlers {
handler()
}
}
}
extension CancellationTokenSource {
typealias Handler = () -> Void
fileprivate class InternalState {
private let lock = NSLock()
private var cancelled = false
private var handlers: [() -> Void] = []
func readCancelled() -> Bool {
lock.lock(); defer { lock.unlock() }
return cancelled
}
func tryCancel() -> [Handler] {
lock.lock(); defer { lock.unlock() }
if cancelled {
return []
}
let handlersToExecute = handlers
cancelled = true
handlers = []
return handlersToExecute
}
func addHandler(_ handler: @escaping Handler) -> Handler? {
lock.lock(); defer { lock.unlock() }
if !cancelled {
handlers.append(handler)
return nil
}
return handler
}
}
}
| mit | 2d9089050c62f9c006cb36fbb4aba242 | 20.074627 | 85 | 0.66289 | 4.599349 | false | false | false | false |
barteljan/VISPER | Example/VISPER-Wireframe-Tests/Mocks/MockRouter.swift | 1 | 2596 | //
// MockRouter.swift
// VISPER-Wireframe_Example
//
// Created by bartel on 19.11.17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
@testable import VISPER_Core
@testable import VISPER_Wireframe
class MockRouter: NSObject, Router {
var invokedAdd = false
var invokedAddCount = 0
var invokedAddParameters: (routePattern: String, Void)?
var invokedAddParametersList = [(routePattern: String, Void)]()
func add(routePattern: String) {
invokedAdd = true
invokedAddCount += 1
invokedAddParameters = (routePattern, ())
invokedAddParametersList.append((routePattern, ()))
}
var invokedRouteUrlRoutingOptionParameters = false
var invokedRouteUrlRoutingOptionParametersCount = 0
var invokedRouteUrlRoutingOptionParametersParameters: (url: URL, parameters: [String: Any]?, routingOption: RoutingOption?)?
var invokedRouteUrlRoutingOptionParametersParametersList = [(url: URL, parameters: [String: Any]?, routingOption: RoutingOption?)]()
var stubbedRouteUrlRoutingOptionParametersResult: RouteResult?
func route(url: URL, parameters: [String: Any]?, routingOption: RoutingOption?) -> RouteResult? {
invokedRouteUrlRoutingOptionParameters = true
invokedRouteUrlRoutingOptionParametersCount += 1
invokedRouteUrlRoutingOptionParametersParameters = (url, parameters, routingOption)
invokedRouteUrlRoutingOptionParametersParametersList.append((url, parameters, routingOption))
return stubbedRouteUrlRoutingOptionParametersResult
}
var invokedRouteUrl = false
var invokedRouteUrlCount = 0
var invokedRouteUrlParameters: (url: URL, parameters: [String: Any]?)?
var invokedRouteUrlParametersList = [(url: URL, parameters: [String: Any]?)]()
var stubbedRouteUrlResult: RouteResult!
func route(url: URL, parameters: [String: Any]?) -> RouteResult? {
invokedRouteUrl = true
invokedRouteUrlCount += 1
invokedRouteUrlParameters = (url, parameters)
invokedRouteUrlParametersList.append((url, parameters))
return stubbedRouteUrlResult
}
var invokedRoute = false
var invokedRouteCount = 0
var invokedRouteParameters: (url: URL, Void)?
var invokedRouteParametersList = [(url: URL, Void)]()
var stubbedRouteResult: RouteResult!
func route(url: URL) -> RouteResult? {
invokedRoute = true
invokedRouteCount += 1
invokedRouteParameters = (url, ())
invokedRouteParametersList.append((url, ()))
return stubbedRouteResult
}
}
| mit | 9c959ed63c12f1b082a14eb9de92c4fb | 37.161765 | 136 | 0.717534 | 4.675676 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsAreaLayer.swift | 7 | 1509 | //
// ChartPointsAreaLayer.swift
// swiftCharts
//
// Created by ischuetz on 15/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartPointsAreaLayer<T: ChartPoint>: ChartPointsLayer<T> {
private let areaColor: UIColor
private let animDuration: Float
private let animDelay: Float
private let addContainerPoints: Bool
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], areaColor: UIColor, animDuration: Float, animDelay: Float, addContainerPoints: Bool) {
self.areaColor = areaColor
self.animDuration = animDuration
self.animDelay = animDelay
self.addContainerPoints = addContainerPoints
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints)
}
override func display(chart chart: Chart) {
var points = self.chartPointScreenLocs
let origin = self.innerFrame.origin
let xLength = self.innerFrame.width
let bottomY = origin.y + self.innerFrame.height
if self.addContainerPoints {
points.append(CGPointMake(origin.x + xLength, bottomY))
points.append(CGPointMake(origin.x, bottomY))
}
let areaView = ChartAreasView(points: points, frame: chart.bounds, color: self.areaColor, animDuration: self.animDuration, animDelay: self.animDelay)
chart.addSubview(areaView)
}
}
| mit | 53b788618eddced89467b54cf01d5279 | 34.093023 | 186 | 0.676607 | 4.558912 | false | false | false | false |
Tornquist/NTKit | NTKitDemo/TileDemoViewController.swift | 1 | 8675 | //
// TileDemoViewController.swift
// NTKitDemo
//
// Created by Nathan Tornquist on 2/22/16.
// Copyright © 2016 Nathan Tornquist. All rights reserved.
//
// Hosted on github at github.com/Tornquist/NTKit
//
// 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 NTKit
class TileDemoViewController: UIViewController, NTTileViewDataSource {
@IBOutlet weak var tileView: NTTileView!
override func viewDidLoad() {
super.viewDidLoad()
configureTileView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureTileView() {
guard self.tileView != nil else { return }
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[tileView]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["tileView":tileView!])
let horizontalConstrints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tileView]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["tileView":tileView!])
self.view.addConstraints(verticalConstraints)
self.view.addConstraints(horizontalConstrints)
tileView.dataSource = self
tileView.reloadTiles()
}
override func viewDidAppear(_ animated: Bool) {
tileView.arrangeTiles()
}
// MARK: - Tile View Data Source Methods
func numberOfTilesFor(tileView: NTTileView) -> Int {
return 5
}
func tileFor(tileView: NTTileView, atIndexPath indexPath: IndexPath) -> NTTile {
switch (indexPath as NSIndexPath).item {
case 0:
let newTile = NTBasicTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.red
newTile.tileText.text = "Centered Anchor"
return newTile
case 1:
let newTile = NTTitleDetailTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.yellow
newTile.titleText.text = "Anchor 1/3"
return newTile
case 2:
let newTile = NTBasicTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.green
newTile.tileText.text = "Centered Anchor"
return newTile
case 3: // NTImageViewTile with NTImage custom drawing
let newTile = NTImageViewDemoTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.blue
newTile.imageView.image = NTImageExample()
newTile.imageView.backgroundColor = UIColor.clear
newTile.titleText.text = "NTImage with NTImageEffects"
return newTile
case 4: // NTImageViewTile
let newTile = NTImageViewDemoTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.purple
newTile.imageView.image = UIImage(named: "Landscape")
newTile.imageView.backgroundColor = UIColor.clear
return newTile
default:
let newTile = NTBasicTile.build(inRect: UIScreen.main.bounds)
newTile.view.backgroundColor = UIColor.brown
newTile.tileText.text = "Centered Anchor"
return newTile
}
}
//MARK: - NTImage Examples
func NTImageExample() -> UIImage? {
let image = NTImage(named: "Landscape")
guard image != nil else {
return nil
}
let rectEffect = NTImageRectangleEffect(rect: CGRect(x: 50, y: 50, width: 100, height: 100),
color: UIColor.red)
let shadeEffect = NTImageShadeEffect(shape: .TriangleBottomRight,
color: UIColor(red: 0, green: 1, blue: 0, alpha: 0.5))
let progressEffect = NTImageProgressCircleEffect(center: CGPoint(x: image!.size.width/2, y: image!.size.height/2),
innerRadius: 100,
outerRadius: 200,
startAngle: 0,
endAngle: 4,
color: UIColor(red: 0, green: 1, blue: 1, alpha: 0.75),
strokeInnerCircle: true,
strokeOuterCircle: true)
let progressEffect2 = NTImageProgressCircleEffect(center: CGPoint(x: image!.size.width/2 - 500, y: image!.size.height/2),
radius: 200,
percent: 0.66,
color: UIColor.orange,
strokeCircle: false)
let textEffect = NTImageTextEffect(anchor: CGPoint(x: 100, y: 500),
text: "Hello World",
fontColor: UIColor.darkGray)
let textEffect2 = NTImageTextEffect(anchor: CGPoint(x: image!.size.width/2, y: image!.size.height/2),
anchorPosition: .Center,
text: "This is a test of\nmultiline right\naligned text.",
textAlignment: .right,
font: UIFont.systemFont(ofSize: 60),
fontColor: UIColor.black)
let textEffect3 = NTImageBlockTextEffect(anchor: CGPoint(x: image!.size.width, y: image!.size.height),
anchorPosition: .BottomRight,
maxWidth: 500,
text: "This will be a\ncomplicated string with multiple different\nlengths of lines.",
baseFont: UIFont.systemFont(ofSize: 60),
fontColor: UIColor.black,
capitalize: true,
trailingTargetCharacterThreshold: 100)
let textEffect4 = NTImageBlockTextEffect(anchor: CGPoint(x: image!.size.width, y: 0),
anchorPosition: .TopRight,
maxWidth: 1000,
text: "This will be a complicated string with multiple different lengths of lines. As you type, more lines are added.",
baseFont: UIFont.systemFont(ofSize: 60),
fontColor: UIColor.black,
capitalize: true)
image!.effects.append(rectEffect)
image!.effects.append(shadeEffect)
image!.effects.append(progressEffect)
image!.effects.append(progressEffect2)
image!.effects.append(textEffect)
image!.effects.append(textEffect2)
image!.effects.append(textEffect3)
image!.effects.append(textEffect4)
return image!.withEffects()
}
// MARK: - Button Events
@IBAction func closePressed(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
}
| mit | 0297a74330e01dcc351b481b41062829 | 50.94012 | 197 | 0.556837 | 5.194012 | false | false | false | false |
daniel-beard/SwiftLint | Source/SwiftLintFramework/Models/Linter.swift | 1 | 2069 | //
// Linter.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct Linter {
public let file: File
private let rules: [Rule]
public let reporter: Reporter.Type
public var styleViolations: [StyleViolation] {
return getStyleViolations().0
}
public var styleViolationsAndRuleTimes: ([StyleViolation], [(rule: String, time: Double)]) {
return getStyleViolations(true)
}
private func getStyleViolations(benchmark: Bool = false) ->
([StyleViolation], [(rule: String, time: Double)]) {
let regions = file.regions()
var ruleTimes = [(rule: String, time: Double)]()
let violations = rules.flatMap { rule -> [StyleViolation] in
let start: NSDate! = benchmark ? NSDate() : nil
let violations = rule.validateFile(self.file)
if benchmark {
let id = rule.dynamicType.description.identifier
ruleTimes.append((id, -start.timeIntervalSinceNow))
}
return violations.filter { violation in
guard let violationRegion = regions.filter({ $0.contains(violation.location) })
.first else {
return true
}
return violationRegion.isRuleEnabled(rule)
}
}
return (violations, ruleTimes)
}
public init(file: File, configuration: Configuration = Configuration()!) {
self.file = file
rules = configuration.rules
reporter = configuration.reporterFromString
}
public func correct() -> [Correction] {
var corrections = [Correction]()
for rule in rules.flatMap({ $0 as? CorrectableRule }) {
let newCorrections = rule.correctFile(file)
corrections += newCorrections
if !newCorrections.isEmpty {
file.invalidateCache()
}
}
return corrections
}
}
| mit | 45f90afdc2918a9b4cfdea8c0f8c3b77 | 31.328125 | 96 | 0.59449 | 4.845433 | false | true | false | false |
quickthyme/PUTcat | PUTcat/Application/Data/Environment/Entity/PCEnvironment.swift | 1 | 1133 |
import Foundation
final class PCEnvironment: PCItem, PCCopyable, PCLocal {
var id: String
var name: String
var variables : PCList<PCVariable>?
init(id: String, name: String) {
self.id = id
self.name = name
}
convenience init(name: String) {
self.init(id: UUID().uuidString, name: name)
}
convenience init() {
self.init(name: "New Environment")
}
required convenience init(copy: PCEnvironment) {
self.init(name: copy.name)
self.variables = copy.variables?.copy()
}
required init(fromLocal: [String:Any]) {
self.id = fromLocal["id"] as? String ?? ""
self.name = fromLocal["name"] as? String ?? ""
}
func toLocal() -> [String:Any] {
return [
"id" : self.id,
"name" : self.name
]
}
}
extension PCEnvironment : PCLocalExport {
func toLocalExport() -> [String:Any] {
var local = self.toLocal()
if let array = self.variables?.toLocalExport() {
local["variables"] = array
}
return local
}
}
| apache-2.0 | 81b96d5908412c706596257f7da75079 | 22.122449 | 56 | 0.54722 | 3.934028 | false | false | false | false |
milseman/swift | test/Parse/multiline_string.swift | 13 | 2451 | // RUN: %target-swift-frontend -dump-ast %s 2>&1 | %FileCheck %s
import Swift
// ===---------- Multiline --------===
_ = """
One
""Alpha""
"""
// CHECK: "One\n\"\"Alpha\"\""
_ = """
Two
Beta
"""
// CHECK: " Two\nBeta"
_ = """
Three
Gamma
"""
// CHECK: " Three\n Gamma"
_ = """
Four
Delta
"""
// CHECK: " Four\n Delta"
_ = """
Five\n
Epsilon
"""
// CHECK: "Five\n\n\nEpsilon"
_ = """
Six
Zeta
"""
// CHECK: "Six\nZeta\n"
_ = """
Seven
Eta\n
"""
// CHECK: "Seven\nEta\n"
_ = """
\"""
"\""
""\"
Iota
"""
// CHECK: "\"\"\"\n\"\"\"\n\"\"\"\nIota"
_ = """
\("Nine")
Kappa
"""
// CHECK: "\nKappa"
_ = """
first
second
third
"""
// CHECK: "first\n second\nthird"
_ = """
first
second
third
"""
// CHECK: "first\n\tsecond\nthird"
_ = """
\\
"""
// CHECK: "\\"
_ = """
\\
"""
// CHECK: "\\"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC"
// contains tabs
_ = """
Twelve
Nu
"""
// CHECK: "Twelve\nNu"
_ = """
newline \
elided
"""
// CHECK: "newline elided"
// contains trailing whitepsace
_ = """
trailing \
\("""
substring1 \
\("""
substring2 \
substring3
""")
""") \
whitepsace
"""
// CHECK: "trailing "
// CHECK: "substring1 "
// CHECK: "substring2 substring3"
// CHECK: " whitepsace"
// contains trailing whitepsace
_ = """
foo\
bar
"""
// CHECK: "foo\nbar"
// contains trailing whitepsace
_ = """
foo\
bar
"""
// CHECK: "foo\nbar"
_ = """
foo \
bar
"""
// CHECK: "foo bar"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC\n"
_ = """
"""
// CHECK: "\n"
_ = """
"""
// CHECK: ""
_ = """
"""
// CHECK: ""
_ = "\("""
\("a" + """
valid
""")
""") literal"
// CHECK: "a"
// CHECK: " valid"
// CHECK: " literal"
_ = "hello\("""
world
""")"
// CHECK: "hello"
// CHECK: "world"
_ = """
hello\("""
world
""")
abc
"""
// CHECK: "hello"
// CHECK: "world"
// CHECK: "\nabc"
_ = "hello\("""
"world'
""")abc"
// CHECK: "hello"
// CHECK: "\"world'"
// CHECK: "abc"
_ = """
welcome
\(
"to\("""
Swift
""")"
)
!
"""
// CHECK: "welcome\n"
// CHECK: "to"
// CHECK: "Swift"
// CHECK: "\n!"
| apache-2.0 | 65993bde4ed1ffb896c0a612dc84009a | 9.519313 | 64 | 0.386781 | 2.735491 | false | false | false | false |
hughbe/swift | stdlib/public/core/UTFEncoding.swift | 4 | 3332 | //===--- UTFEncoding.swift - Common guts of the big 3 UnicodeEncodings ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// These components would be internal if it were possible to use internal
// protocols to supply public conformance requirements.
//
//===----------------------------------------------------------------------===//
public protocol _UTFParser {
associatedtype Encoding : _UnicodeEncoding_
func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8)
func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar
var _buffer: _UIntBuffer<UInt32, Encoding.CodeUnit> { get set }
}
extension _UTFParser
where Encoding.EncodedScalar : RangeReplaceableCollection {
@inline(__always)
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
// Bufferless single-scalar fastpath.
if _fastPath(_buffer.isEmpty) {
guard let codeUnit = input.next() else { return .emptyInput }
// ASCII, return immediately.
if Encoding._isScalar(codeUnit) {
return .valid(Encoding.EncodedScalar(CollectionOfOne(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_buffer.append(codeUnit)
} else if Encoding._isScalar(
Encoding.CodeUnit(extendingOrTruncating: _buffer._storage)
) {
// ASCII in _buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
let codeUnit = Encoding.CodeUnit(extendingOrTruncating: _buffer._storage)
_buffer.remove(at: _buffer.startIndex)
return .valid(Encoding.EncodedScalar(CollectionOfOne(codeUnit)))
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
repeat {
if let codeUnit = input.next() {
_buffer.append(codeUnit)
} else {
if _buffer.isEmpty { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _buffer.count < _buffer.capacity
// Find one unicode scalar.
let (isValid, scalarBitCount) = _parseMultipleCodeUnits()
_sanityCheck(scalarBitCount % numericCast(Encoding.CodeUnit.bitWidth) == 0)
_sanityCheck(1...4 ~= scalarBitCount / 8)
_sanityCheck(scalarBitCount <= _buffer._bitCount)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let encodedScalar = _bufferedScalar(bitCount: scalarBitCount)
_buffer._storage = UInt32(
// widen to 64 bits so that we can empty the buffer in the 4-byte case
extendingOrTruncating: UInt64(_buffer._storage) &>> scalarBitCount)
_buffer._bitCount = _buffer._bitCount &- scalarBitCount
if _fastPath(isValid) {
return .valid(encodedScalar)
}
return .error(
length: Int(scalarBitCount / numericCast(Encoding.CodeUnit.bitWidth)))
}
}
| apache-2.0 | 07b03edd4936f8a3bccedfbe91e06f8d | 37.298851 | 80 | 0.657563 | 4.589532 | false | false | false | false |
k-o-d-e-n/CGLayout | Sources/Classes/stack.layoutGuide.cglayout.swift | 1 | 18390 | //
// stack.layoutGuide.cglayout.swift
// CGLayout
//
// Created by Denis Koryttsev on 04/09/2017.
// Copyright © 2017 K-o-D-e-N. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#elseif os(Linux)
import Foundation
#endif
/// Version - Alpha
/// Base protocol for any layout distribution
protocol RectBasedDistribution {
func distribute(rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis) -> [CGRect]
}
func distributeFromLeading(rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis, spacing: CGFloat) -> [CGRect] {
var previous: CGRect?
return rects.map { rect in
var rect = rect
axis.set(origin: (previous.map { _ in spacing } ?? 0) + (previous.map { axis.get(maxOf: $0) } ?? axis.get(minOf: sourceRect)), for: &rect)
previous = rect
return rect
}
}
func distributeFromTrailing(rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis, spacing: CGFloat) -> [CGRect] {
var previous: CGRect?
return rects.map { rect in
var rect = rect
axis.set(origin: (previous.map { _ in -spacing } ?? 0) + (previous.map { axis.get(minOf: $0) } ?? (axis.get(maxOf: sourceRect))) - axis.get(sizeAt: rect), for: &rect)
previous = rect
return rect
}
}
func alignByCenter(rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis) -> [CGRect] {
let offset = axis.get(midOf: sourceRect) - (((axis.get(maxOf: rects.last!) - axis.get(minOf: rects.first!)) / 2) + axis.get(minOf: rects.first!))
return rects.map { axis.offset(rect: $0, by: offset) }
}
func space(for rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis) -> CGFloat {
let fullLength = rects.reduce(0) { $0 + axis.get(sizeAt: $1) }
return (axis.get(sizeAt: sourceRect) - fullLength) / CGFloat(rects.count - 1)
}
public struct StackDistribution: RectBasedDistribution {
public enum Spacing {
case equally
case equal(CGFloat)
}
public struct Alignment: RectAxisLayout {
let layout: RectAxisLayout
var axis: RectAxis { return layout.axis }
init<T: RectAxisLayout>(_ layout: T) {
self.layout = layout
}
init(_ layout: RectAxisLayout) {
self.layout = layout
}
public static func leading(_ offset: CGFloat = 0) -> Alignment { return Alignment(Layout.Alignment.leading(by: CGRectAxis.vertical, offset: offset)) }
public static func trailing(_ offset: CGFloat = 0) -> Alignment { return Alignment(Layout.Alignment.trailing(by: CGRectAxis.vertical, offset: offset)) }
public static func center(_ offset: CGFloat = 0) -> Alignment { return Alignment(Layout.Alignment.center(by: CGRectAxis.vertical, offset: offset)) }
public func formLayout(rect: inout CGRect, in source: CGRect) {
layout.formLayout(rect: &rect, in: source)
}
func by(axis: RectAxis) -> Alignment {
let l = layout.by(axis: axis)
return .init(l)
}
}
public enum Direction {
case fromLeading
case fromTrailing
case fromCenter
}
public enum Filling {
case equally
case equal(CGFloat)
}
var spacing: Spacing
var alignment: Alignment
var direction: Direction
var filling: Filling
public func distribute(rects: [CGRect], in sourceRect: CGRect, along axis: RectAxis) -> [CGRect] {
guard rects.count > 0 else { return rects }
let fill: CGFloat = {
let count = CGFloat(rects.count)
switch (self.filling, self.spacing) {
case (.equal(let val), _):
return val
case (.equally, .equal(let space)):
return (axis.get(sizeAt: sourceRect) - (count - 1) * space) / count
case (.equally, .equally):
return axis.get(sizeAt: sourceRect) / count
}
}()
let transverseAxis = axis.transverse()
let filledRects = rects.map { rect -> CGRect in
var rect = rect
axis.set(size: fill, for: &rect)
transverseAxis.set(size: transverseAxis.get(sizeAt: sourceRect), for: &rect)
return rect
}
let spacing: CGFloat = {
switch self.spacing {
case .equally:
return space(for: filledRects, in: sourceRect, along: axis)
case .equal(let space):
return space
}
}()
let alignedRects = filledRects.map { alignment.layout(rect: $0, in: sourceRect) }
guard direction != .fromCenter else {
let leftDistributedRects = distributeFromLeading(rects: alignedRects, in: sourceRect, along: axis, spacing: spacing)
return alignByCenter(rects: leftDistributedRects, in: sourceRect, along: axis)
}
let rtl = CGLConfiguration.default.isRTLMode && axis.isHorizontal
if (direction == .fromLeading && !rtl) || (direction == .fromTrailing && rtl) {
return distributeFromLeading(rects: alignedRects, in: sourceRect, along: axis, spacing: spacing)
} else {
return distributeFromTrailing(rects: alignedRects, in: sourceRect, along: axis, spacing: spacing)
}
}
}
/// Defines layout for arranged items
public struct StackLayoutScheme: LayoutBlockProtocol {
private let items: () -> [LayoutElement]
public /// Flag, defines that block will be used for layout
var isActive: Bool { return true }
/// Designed initializer
///
/// - Parameter items: Closure provides items
public init(items: @escaping () -> [LayoutElement]) {
self.items = items
}
public var axis: RectAxis = CGRectAxis.horizontal {
didSet { alignment = alignment.by(axis: axis.transverse()) }
}
private var distribution: StackDistribution = StackDistribution(
spacing: .equally,
alignment: .center(),
direction: .fromLeading,
filling: .equally
)
public var spacing: StackDistribution.Spacing {
set { distribution.spacing = newValue }
get { return distribution.spacing }
}
public var alignment: StackDistribution.Alignment {
set { distribution.alignment = newValue.by(axis: axis.transverse()) }
get { return distribution.alignment }
}
public var filling: StackDistribution.Filling {
set { distribution.filling = newValue }
get { return distribution.filling }
}
public var direction: StackDistribution.Direction {
set { distribution.direction = newValue }
get { return distribution.direction }
}
// MARK: LayoutBlockProtocol
public /// Snapshot for current state without recalculating
var currentSnapshot: LayoutSnapshotProtocol {
var snapshotFrame: CGRect?
return LayoutSnapshot(childSnapshots: items().map { block in
let blockFrame = block.frame
snapshotFrame = snapshotFrame?.union(blockFrame) ?? blockFrame
return blockFrame
}, frame: snapshotFrame ?? .zero)
}
public var currentRect: CGRect {
let items = self.items()
guard items.count > 0 else { fatalError(StackLayoutScheme.message(forNotActive: self)) }
return items.reduce(nil) { return $0?.union($1.frame) ?? $1.frame }!
}
public /// Calculate and apply frames layout items in custom space.
///
/// - Parameter sourceRect: Source space
func layout(in sourceRect: CGRect) {
let subItems = items()
let frames = distribution.distribute(rects: subItems.map { $0.inLayoutTime.frame }, in: sourceRect, along: axis)
zip(subItems, frames).forEach { $0.0.frame = $0.1 }
}
public /// Applying frames from snapshot to `LayoutItem` items in this block.
/// Snapshot array should be ordered such to match `LayoutItem` items sequence.
///
/// - Parameter snapshot: Snapshot represented as array of frames.
func apply(snapshot: LayoutSnapshotProtocol) {
var iterator = items().makeIterator()
for child in snapshot.childSnapshots {
iterator.next()?.frame = child.frame
}
}
public /// Returns snapshot for all `LayoutItem` items in block. Attention: in during calculating snapshot frames of layout items must not changed.
///
/// - Parameter sourceRect: Source space for layout
/// - Returns: Snapshot contained frames layout items
func snapshot(for sourceRect: CGRect) -> LayoutSnapshotProtocol {
var completedFrames: [ObjectIdentifier: CGRect] = [:]
return snapshot(for: sourceRect, completedRects: &completedFrames)
}
public /// Method for perform layout calculation in child blocks. Does not call this method directly outside `LayoutBlockProtocol` object.
/// Layout block should be insert contained `LayoutItem` items to completedRects
///
/// - Parameters:
/// - sourceRect: Source space for layout. For not top level blocks rect should be define available bounds of block
/// - completedRects: `LayoutItem` items with corrected frame
/// - Returns: Frame of this block
func snapshot(for sourceRect: CGRect, completedRects: inout [ObjectIdentifier : CGRect]) -> LayoutSnapshotProtocol {
let subItems = items()
let frames = distribution.distribute(
rects: subItems.map { $0.inLayoutTime.frame }, // TODO: Alignment center is fail, apply for source rect, that may have big size.
in: sourceRect,
along: axis
)
var iterator = subItems.makeIterator()
let snapshotFrame = frames.reduce(into: frames.first) { snapRect, current in
completedRects[ObjectIdentifier(iterator.next()!)] = current
snapRect = snapRect?.union(current) ?? current
}
return LayoutSnapshot(childSnapshots: frames, frame: snapshotFrame ?? CGRect(origin: sourceRect.origin, size: .zero))
}
}
/// StackLayoutGuide layout guide for arranging items in ordered list. It's analogue UIStackView.
/// For configure layout parameters use property `scheme`.
/// Attention: before addition items to stack, need add stack layout guide to super layout element using `func add(layoutGuide:)` method.
open class StackLayoutGuide<Parent: LayoutElement>: LayoutGuide<Parent>, AdjustableLayoutElement, AdaptiveLayoutElement {
private var insetAnchor: RectBasedConstraint?
internal var items: [Element] = []
/// StackLayoutScheme entity for configuring axis, distribution and other parameters.
open lazy var scheme: StackLayoutScheme = StackLayoutScheme { [unowned self] in self.arrangedItems }
/// The list of items arranged by the stack layout guide
open var arrangedItems: [LayoutElement] { return items.map { $0.child } }
/// Insets for distribution space
open var contentInsets: EdgeInsets = .zero {
didSet { insetAnchor = Inset(contentInsets) }
}
/// Layout item where added this layout guide. For addition use `func add(layoutGuide:)`.
open override var ownerElement: Parent? {
willSet {
if newValue == nil {
items.forEach { $0.child.removeFromSuperElement() }
}
}
/// while stack layout guide cannot add subitems
didSet {
if let owner = ownerElement {
items.forEach({ $0.add(to: owner) })
}
}
}
public convenience init(items: [Element]) {
self.init(frame: .zero)
self.items = items
}
internal func removeItem(_ item: LayoutElement) -> LayoutElement? {
guard let index = items.index(where: { $0.child === item }) else { return nil }
return items.remove(at: index).child
}
/// Performs layout for subitems, which this layout guide manages, in layout space rect
///
/// - Parameter rect: Space for layout
override open func layout(in rect: CGRect) {
super.layout(in: rect)
scheme.layout(in: rect)
}
/// Defines rect for `bounds` property. Calls on change `frame`.
///
/// - Parameter frame: New frame value.
/// - Returns: Content rect
open override func contentRect(forFrame frame: CGRect) -> CGRect {
let lFrame = super.contentRect(forFrame: frame)
return insetAnchor?.constrained(sourceRect: lFrame, by: .zero) ?? lFrame
}
open /// Asks the layout item to calculate and return the size that best fits the specified size
///
/// - Parameter size: The size for which the view should calculate its best-fitting size
/// - Returns: A new size that fits the receiver’s content
func sizeThatFits(_ size: CGSize) -> CGSize {
let sourceRect = CGRect(origin: .zero, size: size)
var result = scheme.snapshot(for: insetAnchor?.constrained(sourceRect: sourceRect, by: .zero) ?? sourceRect).frame.distanceFromOrigin
result.width += contentInsets.right
result.height += contentInsets.bottom
return result
}
override open var debugContentOfDescription: String {
return " - items: \(items.debugDescription)"
}
}
extension StackLayoutGuide {
public struct Element {
let base: _AnyEnterPoint<Parent>
var child: LayoutElement { return base.child }
init<Point: EnterPoint>(_ base: Point) where Point.Container == Parent {
self.base = _Enter(base)
}
func add(to container: Parent) {
base.add(to: container)
}
}
/// Adds an element to the end of the `arrangedItems` list.
///
/// - Parameter point: Enter point.
public func addArranged(element: Element) {
insertArranged(element: element, at: items.count)
}
/// Inserts an element to arrangedItems list at specific index.
///
/// - Parameters:
/// - point: Enter point
/// - index: Index in list.
public func insertArranged(element: Element, at index: Int) {
items.insert(element, at: index)
if let owner = ownerElement {
element.add(to: owner)
}
}
/// Removes element from `arrangedItems` list and from hierarchy.
///
/// - Parameter element: Layout element for removing.
public func removeArranged(element: LayoutElement) {
removeItem(element)?.removeFromSuperElement()
}
}
#if os(macOS) || os(iOS) || os(tvOS)
public extension StackLayoutGuide.Element where Parent: CALayer {
static func caLayer<C: CALayer>(_ child: C) -> Self {
return Self(Sublayer<Parent>(layer: child))
}
private struct Sublayer<L: CALayer>: EnterPoint {
let layer: CALayer
var child: LayoutElement { layer }
func add(to container: L) {
container.addSublayer(layer)
}
}
static func layoutGuide<LG, C: CALayer>(_ child: LG) -> Self where LG: LayoutGuide<C> {
return Self(LayoutGuideSublayer<C, Parent>(lg: child))
}
private struct LayoutGuideSublayer<Owner: CALayer, L: CALayer>: EnterPoint {
let lg: LayoutGuide<Owner>
var child: LayoutElement { lg }
func add(to container: L) {
container.add(layoutGuide: lg)
}
}
}
#endif
#if os(iOS) || os(tvOS)
public extension StackLayoutGuide.Element where Parent: UIView {
static func caLayer<C: CALayer>(_ child: C) -> Self {
return Self(Layer<Parent>(layer: child))
}
private struct Layer<V: UIView>: EnterPoint {
let layer: CALayer
var child: LayoutElement { layer }
func add(to container: V) {
container.layer.addSublayer(layer)
}
}
static func uiView<C: UIView>(_ child: C) -> Self {
return Self(View<Parent>(view: child))
}
private struct View<V: UIView>: EnterPoint {
let view: UIView
var child: LayoutElement { view }
func add(to container: V) {
container.addSubview(view)
}
}
static func layoutGuide<LG, C: UIView>(_ child: LG) -> Self where LG: LayoutGuide<C> {
return Self(LayoutGuideView<C, Parent>(lg: child))
}
private struct LayoutGuideView<Owner: UIView, V: UIView>: EnterPoint {
let lg: LayoutGuide<Owner>
var child: LayoutElement { lg }
func add(to container: V) {
container.add(layoutGuide: lg)
}
}
static func layoutGuide<LG, C: CALayer>(_ child: LG) -> Self where LG: LayoutGuide<C> {
return Self(LayoutGuideLayer<C, Parent>(lg: child))
}
private struct LayoutGuideLayer<Owner: CALayer, V: UIView>: EnterPoint {
let lg: LayoutGuide<Owner>
var child: LayoutElement { lg }
func add(to container: V) {
container.layer.add(layoutGuide: lg)
}
}
}
#endif
#if os(macOS)
public extension StackLayoutGuide.Element where Parent: NSView {
static func caLayer<C: CALayer>(_ child: C) -> Self {
return Self(Layer<Parent>(layer: child))
}
private struct Layer<V: NSView>: EnterPoint {
let layer: CALayer
var child: LayoutElement { layer }
func add(to container: V) {
container.layer?.addSublayer(layer)
}
}
static func uiView<C: NSView>(_ child: C) -> Self {
return Self(View<Parent>(view: child))
}
private struct View<V: NSView>: EnterPoint {
let view: NSView
var child: LayoutElement { view }
func add(to container: V) {
container.addSubview(view)
}
}
static func layoutGuide<LG, C: NSView>(_ child: LG) -> Self where LG: LayoutGuide<C> {
return Self(LayoutGuideView<C, Parent>(lg: child))
}
private struct LayoutGuideView<Owner: NSView, V: NSView>: EnterPoint {
let lg: LayoutGuide<Owner>
var child: LayoutElement { lg }
func add(to container: V) {
container.add(layoutGuide: lg)
}
}
static func layoutGuide<LG, C: CALayer>(_ child: LG) -> Self where LG: LayoutGuide<C> {
return Self(LayoutGuideLayer<C, Parent>(lg: child))
}
private struct LayoutGuideLayer<Owner: CALayer, V: NSView>: EnterPoint {
let lg: LayoutGuide<Owner>
var child: LayoutElement { lg }
func add(to container: V) {
container.layer?.add(layoutGuide: lg)
}
}
}
#endif
| mit | 5372452cd209ddf95f3abf46f54e28a8 | 37.87315 | 174 | 0.632023 | 4.347836 | false | false | false | false |
adamnemecek/AudioKit | Sources/AudioKit/Taps/MultiChannelInputNodeTap+WriteableFile.swift | 1 | 5686 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
extension MultiChannelInputNodeTap {
/// An inner class to represent one channel of data to record to file
public class WriteableFile: CustomStringConvertible {
/// Simple description of the file
public var description: String {
"url: \(url.path), channel: \(channel), file is open: \(file != nil)"
}
/// The url being written to, persists after close
public private(set) var url: URL
/// The file format being written
public private(set) var fileFormat: AVAudioFormat
/// The channel of the audio device this is reading from
public private(set) var channel: Int32
/// This is the internal file which is only valid when open for writing, then nil'd
/// out to allow its release
public private(set) var file: AVAudioFile?
/// Current amplitude being written represented as RMS. Suitable for use with a VU meter
public private(set) var amplitude: Float = 0
/// Total current duration of the file, will increment while writing
public private(set) var duration: TimeInterval = 0
/// An array of amplitude values used to create a temporary waveform for display
/// while recording is progressing
public private(set) var amplitudeArray = [Float]()
/// Timestamp when the first samples appear in the process block during writing
public private(set) var timestamp: AVAudioTime?
/// Create the file, passing in an optional hardware latency
public init(url: URL,
fileFormat: AVAudioFormat,
channel: Int32,
ioLatency: AVAudioFrameCount = 0) {
self.fileFormat = fileFormat
self.channel = channel
self.url = url
self.ioLatency = ioLatency
}
internal func createFile() {
guard file == nil else { return }
do {
timestamp = nil
file = try AVAudioFile(forWriting: url,
settings: fileFormat.settings)
} catch let error as NSError {
Log(error)
}
}
/// Should be set the amount of latency samples in the input device
public private(set) var ioLatency: AVAudioFrameCount = 0
/// The total samples read from the input stream
public private(set) var totalFramesRead: AVAudioFrameCount = 0
/// The actual amount of samples written to file. In the case of using
/// calculated hardware latency, this would be less than the samples read
/// from the tap
public private(set) var totalFramesWritten: AVAudioFramePosition = 0 {
didSet {
duration = Double(totalFramesWritten) / fileFormat.sampleRate
}
}
private var ioLatencyHandled: Bool = false
/// Handle incoming data from the tap
public func process(buffer: AVAudioPCMBuffer, time: AVAudioTime, write: Bool) throws {
if write {
try writeFile(buffer: buffer, time: time)
}
amplitude = buffer.rms
}
// The actual buffer length is unpredicatable if using a Tap. This isn't ideal.
// The system will change the buffer size to whatever it wants to, which seems
// strange that they let you set a buffer size in the first place. macOS is setting to
// 4800 when at 48k, or sampleRate / 10. That's a big buffer.
private func writeFile(buffer: AVAudioPCMBuffer, time: AVAudioTime) throws {
guard let file = file else { return }
var buffer = buffer
totalFramesRead += buffer.frameLength
if timestamp == nil {
timestamp = time
}
if !ioLatencyHandled, ioLatency > 0 {
Log("Actual buffer size is", buffer.frameLength,
"totalFramesRead", totalFramesRead,
"Attempting to skip", ioLatency, "frames for latency compensation")
if totalFramesRead > ioLatency {
let latencyOffset: AVAudioFrameCount = totalFramesRead - ioLatency
let startSample = buffer.frameLength - latencyOffset
// edit the first buffer to remove io latency samples length
if buffer.frameLength > latencyOffset,
let offsetBuffer = buffer.copyFrom(startSample: startSample) {
buffer = offsetBuffer
Log("Writing partial buffer", offsetBuffer.frameLength, "frames, ioLatency is", ioLatency, "latencyOffset", latencyOffset)
} else {
Log("Unexpected buffer size of", buffer.frameLength)
}
ioLatencyHandled = true
} else {
// Latency is longer than bufferSize so wait till next iterations
return
}
}
try file.write(from: buffer)
amplitudeArray.append(amplitude)
totalFramesWritten = file.length
}
/// Release the file
public func close() {
Log("recorded duration is", duration,
"initial timestamp is", timestamp,
"totalFramesRead", totalFramesRead,
"file.length", file?.length)
file = nil
amplitudeArray.removeAll()
}
}
}
| mit | f609e4973fc2f9967b03e32a521e0955 | 38.213793 | 146 | 0.584066 | 5.477842 | false | false | false | false |
stowy/LayoutKit | LayoutKit.playground/Pages/TextView.xcplaygroundpage/Contents.swift | 2 | 1029 | import UIKit
import PlaygroundSupport
import LayoutKit
let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
rootView.backgroundColor = .white
let textString = "Hello World\nHello World\nHello World\nHello World\nHello World\n"
let attributedString1 = NSMutableAttributedString(
string: textString,
attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)])
let attributedString2 = NSMutableAttributedString(
string: textString,
attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 12)])
attributedString1.append(attributedString2)
let attributedText = Text.attributed(attributedString1)
let textContainerInset = UIEdgeInsets(top: 2, left: 3, bottom: 4, right: 5)
let textViewLayout = TextViewLayout(text: attributedText, textContainerInset: textContainerInset)
let arrangement = textViewLayout.arrangement()
arrangement.makeViews(in: rootView)
Debug.addBorderColorsRecursively(rootView)
Debug.printRecursiveDescription(rootView)
PlaygroundPage.current.liveView = rootView
| apache-2.0 | 86b6f1c72e7917c13a1da7bcf5c475d8 | 37.111111 | 97 | 0.809524 | 4.573333 | false | false | false | false |
rxwei/cuda-swift | Sources/CUDADriver/Error.swift | 1 | 14139 | //
// Error.swift
// CUDA
//
// Created by Richard Wei on 10/16/16.
//
//
import CCUDA
public enum DriverError : UInt32, Error {
/**
* This indicates that one or more of the parameters passed to the API call
* is not within an acceptable range of values.
*/
case invalidValue = 1
/**
* The API call failed because it was unable to allocate enough memory to
* perform the requested operation.
*/
case outOfMemory = 2
/**
* This indicates that the CUDA driver has not been initialized with
* ::cuInit() or that initialization has failed.
*/
case notInitialized = 3
/**
* This indicates that the CUDA driver is in the process of shutting down.
*/
case deinitialized = 4
/**
* This indicates profiler is not initialized for this run. This can
* happen when the application is running with external profiling tools
* like visual profiler.
*/
case profilerDisabled = 5
/**
* \deprecated
* This error return is deprecated as of CUDA 5.0. It is no longer an error
* to attempt to enable/disable the profiling via ::cuProfilerStart or
* ::cuProfilerStop without initialization.
*/
@available(*, message: "Deprecated as of CUDA 5.0")
case profilerNotInitialized = 6
/**
* \deprecated
* This error return is deprecated as of CUDA 5.0. It is no longer an error
* to call cuProfilerStart() when profiling is already enabled.
*/
@available(*, message: "Deprecated as of CUDA 5.0")
case profilerAlreadyStarted = 7
/**
* \deprecated
* This error return is deprecated as of CUDA 5.0. It is no longer an error
* to call cuProfilerStart() when profiling is already enabled.
*/
@available(*, message: "Deprecated as of CUDA 5.0")
case profilerAlreadyStopped = 8
/**
* This indicates that no CUDA-capable devices were detected by the installed
* CUDA driver.
*/
case noDevice = 100
/**
* This indicates that the device ordinal supplied by the user does not
* correspond to a valid CUDA device.
*/
case invalidDevice = 101
/**
* This indicates that the device kernel image is invalid. This can also
* indicate an invalid CUDA module.
*/
case invalidImage = 200
/**
* This most frequently indicates that there is no context bound to the
* current thread. This can also be returned if the context passed to an
* API call is not a valid handle (such as a context that has had
* ::cuCtxDestroy() invoked on it). This can also be returned if a user
* mixes different API versions (i.e. 3010 context with 3020 API calls).
* See ::cuCtxGetApiVersion() for more details.
*/
case invalidContext = 201
/**
* This indicated that the context being supplied as a parameter to the
* API call was already the active context.
* \deprecated
* This error return is deprecated as of CUDA 3.2. It is no longer an
* error to attempt to push the active context via ::cuCtxPushCurrent().
*/
@available(*, message: "Deprecated as of CUDA 3.2")
case contextAlreadyCurrent = 202
/**
* This indicates that a map or register operation has failed.
*/
case mapFailed = 205
/**
* This indicates that an unmap or unregister operation has failed.
*/
case unmapFailed = 206
/**
* This indicates that the specified array is currently mapped and thus
* cannot be destroyed.
*/
case arrayCurrentlyMapped = 207
/**
* This indicates that the resource is already mapped.
*/
case alreadyMapped = 208
/**
* This indicates that there is no kernel image available that is suitable
* for the device. This can occur when a user specifies code generation
* options for a particular CUDA source file that do not include the
* corresponding device configuration.
*/
case noBinaryForGPU = 209
/**
* This indicates that a resource has already been acquired.
*/
case alreadyAcquired = 210
/**
* This indicates that a resource is not mapped.
*/
case notMapped = 211
/**
* This indicates that a mapped resource is not available for access as an
* array.
*/
case notMappedAsArray = 212
/**
* This indicates that a mapped resource is not available for access as a
* pointer.
*/
case notMappedAsPointer = 213
/**
* This indicates that an uncorrectable ECC error was detected during
* execution.
*/
case uncorrectableECC = 214
/**
* This indicates that the ::CUlimit passed to the API call is not
* supported by the active device.
*/
case unsupportedLimit = 215
/**
* This indicates that the ::CUcontext passed to the API call can
* only be bound to a single CPU thread at a time but is already
* bound to a CPU thread.
*/
case contextAlreadyInUse = 216
/**
* This indicates that peer access is not supported across the given
* devices.
*/
case peerAccessUnsupported = 217
/**
* This indicates that a PTX JIT compilation failed.
*/
case invalidPTX = 218
/**
* This indicates an error with OpenGL or DirectX context.
*/
case invalidGraphicsContext = 219
/**
* This indicates that an uncorrectable NVLink error was detected during the
* execution.
*/
case nvlinkUncorrectable = 220
/**
* This indicates that the device kernel source is invalid.
*/
case invalidSource = 300
/**
* This indicates that the file specified was not found.
*/
case fileNotFound = 301
/**
* This indicates that a link to a shared object failed to resolve.
*/
case sharedObjectSymbolNotFound = 302
/**
* This indicates that initialization of a shared object failed.
*/
case sharedObjectInitFailed = 303
/**
* This indicates that an OS call failed.
*/
case operatingSystem = 304
/**
* This indicates that a resource handle passed to the API call was not
* valid. Resource handles are opaque types like ::CUstream and ::CUevent.
*/
case invalidHandle = 400
/**
* This indicates that a named symbol was not found. Examples of symbols
* are global/constant variable names, texture names, and surface names.
*/
case symbolNotFound = 500
/**
* This indicates that asynchronous operations issued previously have not
* completed yet. This result is not actually an error, but must be indicated
* differently than ::CUDA_SUCCESS (which indicates completion). Calls that
* may return this value include ::cuEventQuery() and ::cuStreamQuery().
*/
case notReady = 600
/**
* While executing a kernel, the device encountered a
* load or store instruction on an invalid memory address.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case illegalAddress = 700
/**
* This indicates that a launch did not occur because it did not have
* appropriate resources. This error usually indicates that the user has
* attempted to pass too many arguments to the device kernel, or the
* kernel launch specifies too many threads for the kernel's register
* count. Passing arguments of the wrong size (i.e. a 64-bit pointer
* when a 32-bit int is expected) is equivalent to passing too many
* arguments and can also result in this error.
*/
case launchOutOfResources = 701
/**
* This indicates that the device kernel took too long to execute. This can
* only occur if timeouts are enabled - see the device attribute
* ::CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT for more information. The
* context cannot be used (and must be destroyed similar to
* ::CUDA_ERROR_LAUNCH_FAILED). All existing device memory allocations from
* this context are invalid and must be reconstructed if the program is to
* continue using CUDA.
*/
case launchTimeout = 702
/**
* This error indicates a kernel launch that uses an incompatible texturing
* mode.
*/
case launchIncompatibleTexturing = 703
/**
* This error indicates that a call to ::cuCtxEnablePeerAccess() is
* trying to re-enable peer access to a context which has already
* had peer access to it enabled.
*/
case peerAccessAlreadyEnabled = 704
/**
* This error indicates that ::cuCtxDisablePeerAccess() is
* trying to disable peer access which has not been enabled yet
* via ::cuCtxEnablePeerAccess().
*/
case peerAccessNotEnabled = 705
/**
* This error indicates that the primary context for the specified device
* has already been initialized.
*/
case primaryContextActive = 708
/**
* This error indicates that the context current to the calling thread
* has been destroyed using ::cuCtxDestroy, or is a primary context which
* has not yet been initialized.
*/
case contextDestroyed = 709
/**
* A device-side assert triggered during kernel execution. The context
* cannot be used anymore, and must be destroyed. All existing device
* memory allocations from this context are invalid and must be
* reconstructed if the program is to continue using CUDA.
*/
case assertion = 710
/**
* This error indicates that the hardware resources required to enable
* peer access have been exhausted for one or more of the devices
* passed to ::cuCtxEnablePeerAccess().
*/
case tooManyPeers = 711
/**
* This error indicates that the memory range passed to ::cuMemHostRegister()
* has already been registered.
*/
case hostMemoryAlreadyRegistered = 712
/**
* This error indicates that the pointer passed to ::cuMemHostUnregister()
* does not correspond to any currently registered memory region.
*/
case hostMemoryNotRegistered = 713
/**
* While executing a kernel, the device encountered a stack error.
* This can be due to stack corruption or exceeding the stack size limit.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case hardwareStackError = 714
/**
* While executing a kernel, the device encountered an illegal instruction.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case illegalInstruction = 715
/**
* While executing a kernel, the device encountered a load or store instruction
* on a memory address which is not aligned.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case misalignedAddress = 716
/**
* While executing a kernel, the device encountered an instruction
* which can only operate on memory locations in certain address spaces
* (global, shared, or local), but was supplied a memory address not
* belonging to an allowed address space.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case invalidAddressSpace = 717
/**
* While executing a kernel, the device program counter wrapped its address space.
* The context cannot be used, so it must be destroyed (and a new one should be created).
* All existing device memory allocations from this context are invalid
* and must be reconstructed if the program is to continue using CUDA.
*/
case invalidProgramCounter = 718
/**
* An exception occurred on the device while executing a kernel. Common
* causes include dereferencing an invalid device pointer and accessing
* out of bounds shared memory. The context cannot be used, so it must
* be destroyed (and a new one should be created). All existing device
* memory allocations from this context are invalid and must be
* reconstructed if the program is to continue using CUDA.
*/
case launchFailed = 719
/**
* This error indicates that the attempted operation is not permitted.
*/
case notPermitted = 800
/**
* This error indicates that the attempted operation is not supported
* on the current system or device.
*/
case notSupported = 801
/**
* This indicates that an unknown internal error has occurred.
*/
case unknown = 999
init(_ cudaError: cudaError_enum) {
self.init(rawValue: cudaError.rawValue)!
}
}
@inline(__always)
func ensureSuccess(_ result: CUresult) throws {
guard result == CUDA_SUCCESS else {
throw DriverError(result)
}
}
@inline(__always)
func forceSuccess(_ result: CUresult) {
guard result == CUDA_SUCCESS else {
fatalError(String(describing: DriverError(result)))
}
}
prefix operator !!
@inline(__always)
prefix func !!(cudaError: CUresult) {
forceSuccess(cudaError)
}
| mit | 6a4386555d95a1a8917e5cfdb123a499 | 31.805104 | 93 | 0.656199 | 4.741449 | false | false | false | false |
qiuncheng/study-for-swift | learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift | 6 | 3310 | //
// ObserveOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ObserveOn<E> : Producer<E> {
let scheduler: ImmediateSchedulerType
let source: Observable<E>
init(source: Observable<E>, scheduler: ImmediateSchedulerType) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
let _ = AtomicIncrement(&resourceCount)
#endif
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
let sink = ObserveOnSink(scheduler: scheduler, observer: observer)
sink._subscription.disposable = source.subscribe(sink)
return sink
}
#if TRACE_RESOURCES
deinit {
let _ = AtomicDecrement(&resourceCount)
}
#endif
}
enum ObserveOnState : Int32 {
// pump is not running
case stopped = 0
// pump is running
case running = 1
}
class ObserveOnSink<O: ObserverType> : ObserverBase<O.E> {
typealias E = O.E
let _scheduler: ImmediateSchedulerType
var _lock = SpinLock()
// state
var _state = ObserveOnState.stopped
var _observer: O?
var _queue = Queue<Event<E>>(capacity: 10)
let _scheduleDisposable = SerialDisposable()
let _subscription = SingleAssignmentDisposable()
init(scheduler: ImmediateSchedulerType, observer: O) {
_scheduler = scheduler
_observer = observer
}
override func onCore(_ event: Event<E>) {
let shouldStart = _lock.calculateLocked { () -> Bool in
self._queue.enqueue(event)
switch self._state {
case .stopped:
self._state = .running
return true
case .running:
return false
}
}
if shouldStart {
_scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run)
}
}
func run(_ state: Void, recurse: (Void) -> Void) {
let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event<E>?, O?) in
if self._queue.count > 0 {
return (self._queue.dequeue(), self._observer)
}
else {
self._state = .stopped
return (nil, self._observer)
}
}
if let nextEvent = nextEvent {
observer?.on(nextEvent)
if nextEvent.isStopEvent {
dispose()
}
}
else {
return
}
let shouldContinue = _shouldContinue_synchronized()
if shouldContinue {
recurse()
}
}
func _shouldContinue_synchronized() -> Bool {
_lock.lock(); defer { _lock.unlock() } // {
if self._queue.count > 0 {
return true
}
else {
self._state = .stopped
return false
}
// }
}
override func dispose() {
super.dispose()
_subscription.dispose()
_scheduleDisposable.dispose()
_lock.lock(); defer { _lock.unlock() } // {
_observer = nil
// }
}
}
| mit | 1cb888ec9154b3514dd1db88e4e872e1 | 23.879699 | 100 | 0.531581 | 4.713675 | false | false | false | false |
xuzhenguo/LayoutComposer | Example/LayoutComposer/RelativeExampleViewController.swift | 1 | 3082 | //
// VBoxExampleViewController.swift
// LayoutComposer
//
// Created by Yusuke Kawakami on 2015/08/22.
// Copyright (c) 2015年 CocoaPods. All rights reserved.
//
import UIKit
import LayoutComposer
enum RelativeExampleType: Int {
case Example1
case Example2
case Example3
}
class RelativeExampleViewController: ExampleViewController {
let exampleType: RelativeExampleType
init(exampleType: RelativeExampleType, headerTitle: String) {
self.exampleType = exampleType
super.init(headerTitle: headerTitle)
}
required init(coder aDecoder: NSCoder) {
fatalError("not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func loadView() {
super.loadView()
switch exampleType {
case .Example1:
layoutExample1()
case .Example2:
layoutExample2()
case .Example3:
layoutExample3()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func layoutExample1() {
let view1 = makeItemView(title: "view1 halign: .Left, valign: .Top", color: UIColor.redColor())
let view2 = makeItemView(title: "view2 halign: .Right, valign: .Bottom", color: UIColor.greenColor())
let view3 = makeItemView(title: "view3 halign: .Center, valign: .Center", color: UIColor.blueColor())
contentView.applyLayout(Relative(), items: [
$(view1, halign: .Left, valign: .Top, width: 200, height: 100),
$(view2, halign: .Right, valign: .Bottom, width: 200, height: 100),
$(view3, halign: .Center, valign: .Center, width: 200, height: 100)
])
}
private func layoutExample2() {
let view1 = makeItemView(title: "view1 halign: .Left, height is not set", color: UIColor.redColor())
let view2 = makeItemView(title: "view2 halign: .Right height is set", color: UIColor.greenColor())
let view3 = makeItemView(title: "view3 halign: .Center height is set", color: UIColor.blueColor())
contentView.applyLayout(Relative(), items: [
$(view1, halign: .Left, width: 100),
$(view2, halign: .Right, width: 100, height: 100),
$(view3, halign: .Center, width: 100, height: 100)
])
}
private func layoutExample3() {
let view1 = makeItemView(title: "view1 valign: .Top, width is not set", color: UIColor.redColor())
let view2 = makeItemView(title: "view2 valign: .Center width is set", color: UIColor.greenColor())
let view3 = makeItemView(title: "view3 valign: .Bottom width is set", color: UIColor.blueColor())
contentView.applyLayout(Relative(), items: [
$(view1, valign: .Top, height: 150),
$(view2, valign: .Center, height: 150, width: 200),
$(view3, valign: .Bottom, height: 150, width: 200)
])
}
}
| mit | 8f0271ab1b945311306918f22dbf1690 | 34.402299 | 109 | 0.629545 | 4.106667 | false | false | false | false |
jackywpy/AudioKit | Tests/Tests/AKOscillator.swift | 14 | 876 | //
// main.swift
// AudioKit
//
// Created by Aurelius Prochazka on 12/2/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let oscillatingControl = AKOscillator()
oscillatingControl.frequency = 2.ak
let oscillator = AKOscillator()
oscillator.frequency = oscillatingControl.scaledBy(110.ak).plus(440.ak)
setAudioOutput(oscillator)
enableParameterLog(
"Frequency = ",
parameter: oscillator.frequency,
timeInterval:0.1
)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
instrument.play()
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | 3c378a8ef976be8ea41f71ed956b4f32 | 20.9 | 79 | 0.681507 | 4.586387 | false | true | false | false |
wayfindrltd/wayfindr-demo-ios | Wayfindr Demo/Classes/Controller/Developer/GraphValidationViewController.swift | 1 | 16187 | //
// GraphValidationViewController.swift
// Wayfindr Demo
//
// Created by Wayfindr on 17/12/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// 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 SwiftGraph
import SVProgressHUD
/// Checks the `WAYVenue` graph data. Displays possible errors and problems.
final class GraphValidationViewController: BaseViewController<GraphValidationView> {
// MARK: - Properties
/// Interface for gathering information about the venue
fileprivate let venueInterface: VenueInterface
/// Model representation of entire venue.
fileprivate var venue: WAYVenue?
/// Array of words that means the validation check passed.
fileprivate let passWords = ["PASS"]
/// Array of words that means the validation check failed.
fileprivate let failWords = ["ERROR", "FAIL", "INVALID"]
// MARK: - Initializers
/**
Initializes a `GraphValidationViewController`.
- parameter venueInterface: Interface for gathering information about the venue.
*/
init(venueInterface: VenueInterface) {
self.venueInterface = venueInterface
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Validation"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(GraphValidationViewController.actionButtonPressed(_:)))
venueInterface.getVenue(completionHandler: { success, newVenue, error in
if success, let myVenue = newVenue {
self.venue = myVenue
self.underlyingView.headerLabel.text = "Graph: VALID"
self.checkGraph(verbose: false)
} else if let myError = error {
self.underlyingView.headerLabel.text = "Graph: " + myError.description
} else {
self.underlyingView.headerLabel.text = "Graph: " + WAYStrings.ErrorMessages.UnknownError
}
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
SVProgressHUD.dismiss()
}
override func setupView() {
super.setupView()
underlyingView.verboseLabeledSwitch.switchControl.addTarget(self, action: #selector(GraphValidationViewController.verboseSwitchValueChanged(_:)), for: .valueChanged)
}
// MARK: - Graph Checking
/**
Checks the graph.
- parameter verbose: Whether or not to use a verbose output.
*/
fileprivate func checkGraph(verbose: Bool) {
guard let myVenue = venue else {
return
}
SVProgressHUD.show()
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async(execute: { [weak self] in
self?.checkPlatformConnectivity(verbose: verbose)
self?.checkExitConnectivity(verbose: verbose)
self?.checkEdgesWithoutInstructions(myVenue.destinationGraph, verbose: verbose)
self?.checkFullConnectivity(myVenue.destinationGraph, verbose: verbose)
DispatchQueue.main.async(execute: {
SVProgressHUD.dismiss()
})
})
}
/**
Checks whether or not the graph is connected. In other words, that you can route from any node to any other node.
- parameter destinationGraph: `WAYGraph` representation to check.
- parameter verbose: Whether or not to print out details about where the discontinuities are, if they exist.
*/
fileprivate func checkFullConnectivity(_ destinationGraph: WAYGraph, verbose: Bool) {
var newText = ""
let isConnected = destinationGraph.graph.isConnected
let result: String
if isConnected {
result = "PASS"
} else {
result = "FAIL"
}
newText = "Fully Connected Graph: \(result)"
if !isConnected && verbose {
let discontinuities = destinationGraph.graph.discontinuities
for (startIndex, endIndex) in discontinuities {
let startNode = destinationGraph.graph[startIndex]
let endNode = destinationGraph.graph[endIndex]
newText = newText + "\n\n - Missing Path: \(startNode.identifier) to \(endNode.identifier)"
}
}
DispatchQueue.main.async(execute: { [weak self] in
self?.addInformation(newText)
})
}
/**
Checks whether you can get from any node to each platform.
- parameter verbose: Whether or not to print out details about where the discontinuities are, if they exist.
*/
fileprivate func checkPlatformConnectivity(verbose: Bool) {
guard let myVenue = venue else {
return
}
let platformDestinations = myVenue.platforms.map { $0 as WAYDestination }
let exitDestinations = myVenue.exits.map { $0 as WAYDestination }
let ignoreDestinations = [platformDestinations, exitDestinations].flatMap { $0 }
checkDestinationConnectivity(platformDestinations, ignoreDestinations: ignoreDestinations, connectivityTitle: "Platform", verbose: verbose)
}
/**
Checks whether you can get from any node to each exit.
- parameter verbose: Whether or not to print out details about where the discontinuities are, if they exist.
*/
fileprivate func checkExitConnectivity(verbose: Bool) {
guard let myVenue = venue else {
return
}
let platformDestinations = myVenue.platforms.map { $0 as WAYDestination }
let exitDestinations = myVenue.exits.map { $0 as WAYDestination }
let ignoreDestinations = [platformDestinations, exitDestinations].flatMap { $0 }
checkDestinationConnectivity(exitDestinations, ignoreDestinations: ignoreDestinations, connectivityTitle: "Exit", verbose: verbose)
}
/**
Checks whether you can get from any node to each destination.
- parameter destinations: Array of destinations.
- parameter ignoreDestinations: Ignore the `entranceNode` of these destinations if they are different from the `exitNode`.
- parameter connectivityTitle: `String` to use when describing the connectivity in output.
- parameter verbose: Whether or not to print out details about where the discontinuities are, if they exist.
*/
fileprivate func checkDestinationConnectivity(_ destinations: [WAYDestination], ignoreDestinations: [WAYDestination], connectivityTitle: String, verbose: Bool) {
guard let myVenue = venue else {
return
}
let graph = myVenue.destinationGraph.graph
var missingEdges = [(Int, Int)]()
var ignoreEntranceIndices = [Int]()
for destination in ignoreDestinations where destination.entranceNode != destination.exitNode {
let destinationNode = destination.entranceNode
if let destinationNodeIndex = graph.index(of: destinationNode) {
ignoreEntranceIndices.append(destinationNodeIndex)
}
}
for destination in destinations {
let destinationNode = destination.entranceNode
if let destinationNodeIndex = graph.index(of: destinationNode) {
for (index, _) in graph.enumerated() {
if index != destinationNodeIndex && !ignoreEntranceIndices.contains(index) {
let route = graph.bfs(from: index, to: destinationNodeIndex)
if route.isEmpty {
missingEdges.append((index, destinationNodeIndex))
}
}
}
}
}
var newText = ""
let result: String
if missingEdges.isEmpty {
result = "PASS"
} else {
result = "FAIL"
}
newText = "\(connectivityTitle) Connectivity: \(result)"
if !missingEdges.isEmpty && verbose {
for (startIndex, endIndex) in missingEdges {
let startNode = graph[startIndex]
let endNode = graph[endIndex]
var verboseText = " - Missing Path: \(startNode.identifier) to \(endNode.identifier)\n"
verboseText = verboseText + " \(startNode.identifier): \(startNode.name)\n"
verboseText = verboseText + " \(endNode.identifier): \(endNode.name)"
newText = newText + "\n\n" + verboseText
}
}
DispatchQueue.main.async(execute: { [weak self] in
self?.addInformation(newText)
})
}
/**
Checks whether or not there are any edges in the graph that have no instructions.
- parameter destinationGraph: `WAYGraph` representation to check.
- parameter verbose: Whether or not to print out details about which edges lack instructions.
*/
fileprivate func checkEdgesWithoutInstructions(_ destinationGraph: WAYGraph, verbose: Bool) {
var newText = ""
var edgesWithoutInstructions = [WAYGraphEdge]()
for edge in destinationGraph.edges {
if edge.instructions.allInstructions().isEmpty && edge.instructions.startingOnly == nil {
edgesWithoutInstructions.append(edge)
}
}
let result: String
if edgesWithoutInstructions.isEmpty {
result = "PASS"
} else {
result = "FAIL"
}
newText = "Edges Without Instructions: \(result)"
if !edgesWithoutInstructions.isEmpty && verbose {
for edge in edgesWithoutInstructions {
newText = newText + "\n\n - No Instructions: \(edge.identifier)"
}
}
DispatchQueue.main.async(execute: { [weak self] in
self?.addInformation(newText)
})
}
// MARK: - Control Actions
@objc func actionButtonPressed(_ sender: UIBarButtonItem) {
let text = shareableText()
let printableText = UISimpleTextPrintFormatter(attributedText: text)
let viewController = UIActivityViewController(activityItems: [text, printableText], applicationActivities: nil)
let popoverController = viewController.popoverPresentationController
popoverController?.barButtonItem = sender
present(viewController, animated: true, completion: nil)
}
@objc func verboseSwitchValueChanged(_ sender: UISwitch) {
SVProgressHUD.show()
underlyingView.textView.text = ""
sender.isEnabled = false
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async(execute: { [weak self] in
self?.checkGraph(verbose: sender.isOn)
DispatchQueue.main.async(execute: {
SVProgressHUD.dismiss()
sender.isEnabled = true
})
})
}
// MARK: - Text Manipulation
fileprivate func shareableText() -> NSAttributedString {
// Body
let mutableAttributedString = NSMutableAttributedString(attributedString: underlyingView.textView.attributedText)
// Header
if let headerText = underlyingView.headerLabel.text {
let headerAttributedString = NSMutableAttributedString(string: headerText + "\n\n\n")
headerAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title2), range: NSRange(location: 0, length: headerAttributedString.length))
mutableAttributedString.insert(headerAttributedString, at: 0)
}
// Title
if let venueName = venue?.name {
let venueNameAttributedString = NSMutableAttributedString(string: venueName + "\n\n")
venueNameAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1), range: NSRange(location: 0, length: venueNameAttributedString.length))
mutableAttributedString.insert(venueNameAttributedString, at: 0)
}
return mutableAttributedString
}
/**
Appends information to the `UITextView` and highlights key words.
- parameter information: Information to add to the display.
*/
fileprivate func addInformation(_ information: String) {
let text: String
if underlyingView.textView.attributedText.length == 0 {
text = information
} else {
text = underlyingView.textView.attributedText.string + "\n\n" + information
}
// Initialize attributed string
var mutableAttributedString = NSMutableAttributedString(string: text)
// Highlight any pass or fail
for passWord in passWords {
highlightString(passWord, inString: &mutableAttributedString, color: WAYConstants.WAYColors.WayfindrMainColor)
}
for failWord in failWords {
highlightString(failWord, inString: &mutableAttributedString, color: UIColor.red)
}
// Set the font
mutableAttributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body), range: NSRange(location: 0, length: mutableAttributedString.length))
// Display the text
underlyingView.textView.attributedText = mutableAttributedString
}
/**
Highlights a substring within a larger `NSMutableAttributedString`.
- parameter highlightText: Substring to highlight within `fullText`.
- parameter fullText: `NSMutableAttributedString` in which to highlight instances of `highlightText`.
- parameter color: `UIColor` to use for highlighting.
*/
fileprivate func highlightString(_ highlightText: String, inString fullText: inout NSMutableAttributedString, color: UIColor) {
if let regex = try? NSRegularExpression(pattern: highlightText, options: []) {
let ranges = regex.matches(in: fullText.string, options: [], range: NSRange(location: 0, length: fullText.string.count)).map { $0.range }
for range in ranges {
fullText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
}
}
}
| mit | 1e0ec01994ef4917fdd8645448da7c54 | 38.288835 | 218 | 0.627108 | 5.33872 | false | false | false | false |
edragoev1/pdfjet | Sources/PDFjet/PlainText.swift | 1 | 4848 | /**
* PlainText.swift
*
Copyright 2020 Innovatics Inc.
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
///
/// Please see Example_45
///
public class PlainText : Drawable {
private var font: Font
private var textLines: [String]
private var fontSize: Float
private var x: Float = 0.0
private var y: Float = 0.0
private var w: Float = 500.0
private var leading: Float = 0.0
private var backgroundColor = Color.white
private var borderColor = Color.white
private var textColor = Color.black
private var language: String?
private var altDescription: String?
private var actualText: String?
public init(_ font: Font, _ textLines: [String]) {
self.font = font
self.fontSize = font.getSize()
self.textLines = textLines
var buf = String()
for str in textLines {
buf.append(str)
buf.append(" ")
}
self.altDescription = buf
self.actualText = buf
}
public func setFontSize(_ fontSize: Float) -> PlainText {
self.fontSize = fontSize
return self
}
public func setPosition(_ x: Float, _ y: Float) {
setLocation(x, y)
}
@discardableResult
public func setLocation(_ x: Float, _ y: Float) -> PlainText {
self.x = x
self.y = y
return self
}
public func setWidth(_ w: Float) -> PlainText {
self.w = w
return self
}
public func setLeading(_ leading: Float) -> PlainText {
self.leading = leading
return self
}
public func setBackgroundColor(_ backgroundColor: UInt32) -> PlainText {
self.backgroundColor = backgroundColor
return self
}
public func setBorderColor(_ borderColor: UInt32) -> PlainText {
self.borderColor = borderColor
return self
}
public func setTextColor(_ textColor: UInt32) -> PlainText {
self.textColor = textColor
return self
}
///
/// Draws this PlainText on the specified page.
///
/// @param page the page to draw this PlainText on.
/// @return x and y coordinates of the bottom right corner of this component.
/// @throws Exception
///
public func drawOn(_ page: Page?) -> [Float] {
let originalSize = font.getSize()
font.setSize(fontSize)
var yText: Float = y + font.getAscent()
page!.addBMC(StructElem.P, language, Single.space, Single.space)
page!.setBrushColor(backgroundColor)
self.leading = font.getBodyHeight()
let h = font.getBodyHeight() * Float(textLines.count)
page!.fillRect(x, y, w, h)
page!.setPenColor(borderColor)
page!.setPenWidth(0.0)
page!.drawRect(x, y, w, h)
page!.addEMC()
page!.addBMC(StructElem.P, language, actualText!, altDescription!)
page!.setTextStart()
page!.setTextFont(font)
page!.setBrushColor(textColor)
page!.setTextLeading(leading)
page!.setTextLocation(x, yText)
for str in textLines {
if font.skew15 {
setTextSkew(page!, 0.26, x, yText)
}
page!.printString(str)
page!.newLine()
yText += leading
}
page!.setTextEnd()
page!.addEMC()
font.setSize(originalSize)
return [x + w, y + h]
}
private func setTextSkew(
_ page: Page, _ skew: Float, _ x: Float, _ y: Float) {
page.append(1.0)
page.append(" ")
page.append(0.0)
page.append(" ")
page.append(skew)
page.append(" ")
page.append(1.0)
page.append(" ")
page.append(x)
page.append(" ")
page.append(page.height - y)
page.append(" Tm\n")
}
} // End of PlainText.swift
| mit | 031b9b36631f9339e468b59e13d1d907 | 27.517647 | 81 | 0.623969 | 4.271366 | false | false | false | false |
ngageoint/mage-ios | MageTests/Observation/Fields/NumberFieldViewTests.swift | 1 | 25462 | //
// NumberFieldViewTests.swift
// MAGETests
//
// Created by Daniel Barela on 5/26/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import Quick
import Nimble
//import Nimble_Snapshots
@testable import MAGE
extension UITextField {
func setTextAndSendEvent(_ text: String) {
self.sendActions(for: .editingDidBegin)
self.text = text
self.sendActions(for: .editingChanged)
}
func endEditingAndSendEvent() {
self.sendActions(for: .editingDidEnd);
}
}
class NumberFieldViewTests: KIFSpec {
override func spec() {
describe("NumberFieldView") {
var numberFieldView: NumberFieldView!
var field: [String: Any]!
var view: UIView!
var controller: UIViewController!
var window: UIWindow!;
controller = UIViewController();
view = UIView(forAutoLayout: ());
view.autoSetDimension(.width, toSize: 300);
view.backgroundColor = .white;
controller.view.addSubview(view);
beforeEach {
window = TestHelpers.getKeyWindowVisible();
controller = UIViewController();
view = UIView(forAutoLayout: ());
view.autoSetDimension(.width, toSize: 300);
view.backgroundColor = .white;
window.rootViewController = controller;
controller.view.addSubview(view);
field = [
"title": "Number Field",
"name": "field8",
"id": 8
];
// Nimble_Snapshots.setNimbleTolerance(0.0);
// Nimble_Snapshots.recordAllSnapshots()
}
afterEach {
for subview in view.subviews {
subview.removeFromSuperview();
}
}
it("edit mode reference image") {
field[FieldKey.min.key] = 2;
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.textField.placeholder) == "Number Field *"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be greater than 2 "
expect(numberFieldView.titleLabel.text) == "Must be greater than 2 "
// expect(view).to(haveValidSnapshot());
}
it("non edit mode reference image") {
field[FieldKey.min.key] = 2;
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field, editMode: false, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.fieldValue.text) == "2";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
// expect(view).to(haveValidSnapshot());
}
it("non edit mode") {
numberFieldView = NumberFieldView(field: field, editMode: false, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.fieldValue.text) == "2";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
}
it("no initial value") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.fieldValue.text).to(beNil());
expect(numberFieldView.textField.text) == "";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
}
it("initial value set") {
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
}
it("set value via input") {
let delegate = MockFieldDelegate();
numberFieldView = NumberFieldView(field: field, delegate: delegate);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "";
tester().waitForView(withAccessibilityLabel: field[FieldKey.name.key] as? String);
tester().enterText("2", intoViewWithAccessibilityLabel: field[FieldKey.name.key] as? String);
tester().tapView(withAccessibilityLabel: "Done");
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
expect(delegate.fieldChangedCalled).to(beTrue());
}
it("initial value set with min") {
field[FieldKey.min.key] = 2;
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.textField.placeholder) == "Number Field"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be greater than 2 "
expect(numberFieldView.titleLabel.text) == "Must be greater than 2 "
}
it("initial value set with max") {
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.textField.placeholder) == "Number Field"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be less than 8"
expect(numberFieldView.titleLabel.text) == "Must be less than 8"
}
it("initial value set with min and max") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.textField.placeholder) == "Number Field"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be between 2 and 8"
expect(numberFieldView.titleLabel.text) == "Must be between 2 and 8"
}
it("set value later") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "";
numberFieldView.setValue("2")
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.fieldNameLabel.text) == "Number Field"
}
it("set valid false") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.setValid(false);
expect(numberFieldView.textField.text) == "";
expect(numberFieldView.textField.placeholder) == "Number Field"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be a number"
// expect(view).to(haveValidSnapshot());
}
it("set valid true after being invalid") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.text) == "";
expect(numberFieldView.textField.placeholder) == "Number Field"
expect(numberFieldView.textField.leadingAssistiveLabel.text) == " ";
numberFieldView.setValid(false);
expect(numberFieldView.textField.leadingAssistiveLabel.text) == "Must be a number"
numberFieldView.setValid(true);
expect(numberFieldView.textField.leadingAssistiveLabel.text).to(beNil());
}
it("required field is invalid if empty") {
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isEmpty()) == true;
expect(numberFieldView.isValid(enforceRequired: true)) == false;
expect(numberFieldView.textField.text) == "";
expect(numberFieldView.textField.placeholder) == "Number Field *"
}
it("required field is invalid if text is nil") {
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
numberFieldView.textField.text = nil;
expect(numberFieldView.isEmpty()) == true;
expect(numberFieldView.isValid(enforceRequired: true)) == false;
expect(numberFieldView.textField.placeholder) == "Number Field *"
}
it("field is invalid if text is a letter") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
numberFieldView.textField.text = "a";
expect(numberFieldView.isEmpty()) == false;
expect(numberFieldView.isValid(enforceRequired: true)) == false;
expect(numberFieldView.textField.placeholder) == "Number Field"
}
it("field should allow changing text to a valid number") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
numberFieldView.textField.text = "1";
expect(numberFieldView.textField(numberFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 1), replacementString: "2")) == true;
expect(numberFieldView.isEmpty()) == false;
}
it("field should allow changing text to a blank") {
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
numberFieldView.textField.text = "1";
expect(numberFieldView.textField(numberFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 1), replacementString: "")) == true;
}
it("required field is valid if not empty") {
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isEmpty()) == false;
expect(numberFieldView.isValid(enforceRequired: true)) == true;
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.textField.placeholder) == "Number Field *"
}
it("required field has title which indicates required") {
field[FieldKey.required.key] = true;
numberFieldView = NumberFieldView(field: field);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField.placeholder) == "Number Field *"
}
it("field is not valid if value is below min") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "1");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isValid()) == false;
}
it("field is not valid if value is above max") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "9");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isValid()) == false;
}
it("field is valid if value is between min and max") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "5");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isValid()) == true;
}
it("field is valid if value is above min") {
field[FieldKey.min.key] = 2;
numberFieldView = NumberFieldView(field: field, value: "5");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isValid()) == true;
}
it("field is valid if value is below max") {
field[FieldKey.max.key] = 8;
numberFieldView = NumberFieldView(field: field, value: "5");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
expect(numberFieldView.isValid()) == true;
}
it("verify only numbers are allowed") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
expect(numberFieldView.textField(numberFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 1), replacementString: "a")) == false;
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "2";
}
it("verify if a non number is set it will be invalid") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "a";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "a";
expect(numberFieldView.getValue()).to(beNil());
expect(numberFieldView.isValid()).to(beFalse());
}
it("verify setting values on BaseFieldView returns the correct values") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate);
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
(numberFieldView as BaseFieldView).setValue("2");
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.getValue()) == 2;
expect(((numberFieldView as BaseFieldView).getValue() as! NSNumber)) == 2;
}
it("verify if number below min is set it will be invalid") {
field[FieldKey.min.key] = 2;
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "1";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "1";
expect(numberFieldView.getValue()) == 1;
expect(numberFieldView.isValid()).to(beFalse());
}
it("verify if number above max is set it will be invalid") {
field[FieldKey.max.key] = 2;
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "3";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "3";
expect(numberFieldView.getValue()) == 3;
expect(numberFieldView.isValid()).to(beFalse());
}
it("verify if number too low is set it will be invalid") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "1";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "1";
expect(numberFieldView.getValue()) == 1;
expect(numberFieldView.isValid()).to(beFalse());
}
it("verify if number too high is set it will be invalid") {
field[FieldKey.min.key] = 2;
field[FieldKey.max.key] = 8;
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "9";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "9";
expect(numberFieldView.getValue()) == 9;
expect(numberFieldView.isValid()).to(beFalse());
}
it("test delegate") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "5";
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == true;
expect(delegate.newValue as? NSNumber) == 5;
}
it("allow canceling") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "4";
numberFieldView.cancelButtonPressed();
expect(delegate.fieldChangedCalled) == false;
expect(numberFieldView.textField.text) == "2";
expect(numberFieldView.getValue()) == 2;
}
it("done button should change value") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "4";
numberFieldView.doneButtonPressed();
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == true;
expect(numberFieldView.textField.text) == "4";
expect(numberFieldView.getValue()) == 4;
}
it("done button should send nil as new value") {
let delegate = MockFieldDelegate()
numberFieldView = NumberFieldView(field: field, delegate: delegate, value: "2");
numberFieldView.applyTheme(withScheme: MAGEScheme.scheme());
view.addSubview(numberFieldView)
numberFieldView.autoPinEdgesToSuperviewEdges();
numberFieldView.textField.text = "";
numberFieldView.doneButtonPressed();
numberFieldView.textFieldDidEndEditing(numberFieldView.textField);
expect(delegate.fieldChangedCalled) == true;
expect(numberFieldView.textField.text) == "";
expect(numberFieldView.getValue()).to(beNil());
}
}
}
}
| apache-2.0 | 87b7c6b0484e3b627f04d1e4a86a770a | 47.313093 | 169 | 0.555398 | 5.755199 | false | false | false | false |
material-components/material-components-ios-codelabs | MDC-104/Swift/Complete/Shrine/Shrine/HomeViewController.swift | 1 | 6933 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents
class HomeViewController: UICollectionViewController {
var shouldDisplayLogin = false
var appBarViewController = MDCAppBarViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.view.tintColor = .black
self.title = "Shrine"
self.view?.backgroundColor = .white
self.collectionView?.backgroundColor = .clear
// AppBar Setup
//TODO: Remove AppBar Setup in the following six lines
// self.addChildViewController(self.appBarViewController)
// self.view.addSubview(self.appBarViewController.view)
// self.appBarViewController.didMove(toParentViewController: self)
//
// Set the tracking scroll view.
// self.appBarViewController.headerView.trackingScrollView = self.collectionView
// Setup Navigation Items
let menuItemImage = UIImage(named: "MenuItem")
let templatedMenuItemImage = menuItemImage?.withRenderingMode(.alwaysTemplate)
let menuItem = UIBarButtonItem(image: templatedMenuItemImage,
style: .plain,
target: self,
action: #selector(menuItemTapped(sender:)))
self.navigationItem.leftBarButtonItem = menuItem
let searchItemImage = UIImage(named: "SearchItem")
let templatedSearchItemImage = searchItemImage?.withRenderingMode(.alwaysTemplate)
let searchItem = UIBarButtonItem(image: templatedSearchItemImage,
style: .plain,
target: nil,
action: nil)
let tuneItemImage = UIImage(named: "TuneItem")
let templatedTuneItemImage = tuneItemImage?.withRenderingMode(.alwaysTemplate)
let tuneItem = UIBarButtonItem(image: templatedTuneItemImage,
style: .plain,
target: nil,
action: nil)
self.navigationItem.rightBarButtonItems = [ tuneItem, searchItem ]
MDCAppBarColorThemer.applyColorScheme(ApplicationScheme.shared.colorScheme,
to:self.appBarViewController)
MDCAppBarTypographyThemer.applyTypographyScheme(ApplicationScheme.shared.typographyScheme,
to: self.appBarViewController)
self.collectionView!.collectionViewLayout = CustomLayout()
//TODO: Register for the catalog changed notification
NotificationCenter.default.addObserver(self,
selector: #selector(respondToCatalogNotification),
name: Notification.Name(rawValue: "CatalogFilterDidChangeNotification"),
object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (self.collectionViewLayout is UICollectionViewFlowLayout) {
let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let HORIZONTAL_SPACING: CGFloat = 8.0
let itemDimension: CGFloat = (self.view.frame.size.width - 3.0 * HORIZONTAL_SPACING) * 0.5
let itemSize = CGSize(width: itemDimension, height: itemDimension)
flowLayout.itemSize = itemSize
}
if (self.shouldDisplayLogin) {
let loginViewController = LoginViewController(nibName: nil, bundle: nil)
self.present(loginViewController, animated: false, completion: nil)
self.shouldDisplayLogin = false
}
}
//MARK - Methods
@objc func menuItemTapped(sender: Any) {
let loginViewController = LoginViewController(nibName: nil, bundle: nil)
self.present(loginViewController, animated: true, completion: nil)
}
//MARK - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
let count = Catalog.count
return count
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: "ProductCell",
for: indexPath) as! ProductCell
let product = Catalog.productAtIndex(index: indexPath.row)
cell.imageView.image = UIImage(named: product.imageName)
cell.nameLabel.text = product.productName
cell.priceLabel.text = product.price
return cell
}
//TODO: Add notification Handler
// Catalog Update Handler reloads the collection view is the products have changed
@objc func respondToCatalogNotification() {
self.collectionView?.reloadSections([0])
}
}
//MARK: - UIScrollViewDelegate
// The following four methods must be forwarded to the tracking scroll view in order to implement
// the Flexible Header's behavior.
extension HomeViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView == self.appBarViewController.headerView.trackingScrollView) {
self.appBarViewController.headerView.trackingScrollDidScroll()
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if (scrollView == self.appBarViewController.headerView.trackingScrollView) {
self.appBarViewController.headerView.trackingScrollDidEndDecelerating()
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
let headerView = self.appBarViewController.headerView
if (scrollView == headerView.trackingScrollView) {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let headerView = self.appBarViewController.headerView
if (scrollView == headerView.trackingScrollView) {
headerView.trackingScrollWillEndDragging(withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
}
| apache-2.0 | 46a8d7003b92e01250a398d7e840e2e5 | 40.267857 | 115 | 0.677917 | 5.801674 | false | false | false | false |
LeeMZC/MZCWB | MZCWB/MZCWB/Classes/Home-首页/View/MZCHomeImageBrowserCell.swift | 1 | 3238 | //
// MZCHomeImageBrowserCell.swift
// MZCWB
//
// Created by 马纵驰 on 16/8/8.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import QorumLogs
import YYKit
protocol MZCHomeImageBrowserCellDelegate : NSObjectProtocol {
func closeClick()
}
class MZCHomeImageBrowserCell: UICollectionViewCell {
@IBOutlet weak var scrollView: UIScrollView!
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
func setupUI(){
scrollView.minimumZoomScale = 0.5
scrollView.maximumZoomScale = 2.0
}
private lazy var imgView : UIImageView = {
let imgView = UIImageView()
self.scrollView.addSubview(imgView)
return imgView
}()
weak var delegate : MZCHomeImageBrowserCellDelegate?
var url : NSURL? {
didSet {
guard let t_url = url else{
return
}
recoveryFrame()
imgView.setImageWithURL(t_url, placeholder: nil, options: YYWebImageOptions.SetImageWithFadeAnimation) { (img, url, type, stage, error) in
if stage == YYWebImageStage.Finished {
if img?.size.height > MZCScreenSize.height {
let size = img!.mzc_fixedWidthScalingSize()
self.imgView.frame = CGRectMake(0, 0, size.width, size.height)
self.scrollView.contentSize = size
}else{
self.imgView.center = CGPointMake(MZCScreenSize.width / 2, MZCScreenSize.height / 2)
self.imgView.bounds.size = img!.mzc_fixedWidthScalingSize()
}
}
}
}
}
private func recoveryFrame(){
scrollView.contentSize = CGSizeZero
imgView.transform = CGAffineTransformIdentity
}
}
//MARK:- 事件
extension MZCHomeImageBrowserCell {
@IBAction func closeClick(sender: AnyObject) {
QL1("")
delegate?.closeClick()
}
@IBAction func saveClick(sender: AnyObject) {
}
}
//MARK:- 代理
extension MZCHomeImageBrowserCell {
/**
每一次缩放都会调用
- parameter scrollView:
*/
func scrollViewDidZoom(scrollView: UIScrollView) {
}
/**
缩放结束时调用
- parameter scrollView:
- parameter view:
- parameter scale:
*/
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat){
imgView.center = CGPointMake(MZCScreenSize.width / 2, MZCScreenSize.height / 2)
}
/**
缩放即将开始时调用
- parameter scrollView:
- parameter view:
*/
func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?){
}
/**
设置需要被缩放的子控件
- parameter scrollView:
- returns:
*/
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imgView
}
}
| artistic-2.0 | 4f02ded5302e7eda94da77f967942b7f | 22.810606 | 150 | 0.557111 | 5.012759 | false | false | false | false |
insidegui/GRStatusBar | GRStatusBar/GRStatusBar.swift | 1 | 10531 | //
// GRStatusBar.swift
// GRStatusBar
//
// Created by Guilherme Rambo on 27/01/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Cocoa
/// Manages a status bar associated with a particular window
///
/// The status bar is a thin translucent bar displayed on be bottom-left of the window
@objc public class GRStatusBar: NSObject {
/// The style used for the status bar vibrancy (Light or Dark)
public var style = GRStatusBarStyle.light {
didSet {
guard backgroundView != nil else { return }
backgroundView.appearance = style.appearance
}
}
/// The color to use as the status bar's background (will have opacity reduced to keep translucency)
public var backgroundColor: NSColor? {
didSet {
tintView.backgroundColor = backgroundColor?.withAlphaComponent(LayoutConstants.backgroundColorAlpha)
}
}
/// The color for the text (if you want to customize other text properties, use `attributedText`)
public var textColor: NSColor? = LayoutConstants.defaultTextColor {
didSet {
label.textColor = textColor ?? LayoutConstants.defaultTextColor
}
}
/// The text to display in the status bar (if you want to customize text properties, set `attributedText` instead)
///
/// *The status bar is automatically shown for `displayTime` seconds when this property is changed, unless It is set to nil*
public var text: String? {
didSet {
guard label != nil else { return }
label.stringValue = text ?? ""
if text != nil {
show()
}
}
}
/// The attributed text to display in the status bar
///
/// *The status bar is automatically shown for `displayTime` seconds when this property is changed, unless It is set to nil*
public var attributedText: NSAttributedString? {
didSet {
label.attributedStringValue = attributedText ?? NSAttributedString()
if attributedText != nil {
show()
}
}
}
/// How long the status bar should stay on screen by default
public var displayTime: Double = 4.0
/// Whether the status bar is currently being displayed or not
///
/// *This is set to `true` when the show animation starts and `false` when the hide animation starts*
public var isVisible = false
private var window: NSWindow
private var containerView: NSView!
private var tintView: GRStatusBarBackgroundView!
private var backgroundView: NSVisualEffectView!
private var label: NSTextField!
private let windowContentViewObserverContext: UnsafeMutableRawPointer? = nil
init(window: NSWindow) {
self.window = window
super.init()
self.window.addObserver(self, forKeyPath: "contentView", options: [.initial, .new], context: windowContentViewObserverContext)
fixContentViewIfNeeded()
buildViews()
}
/// Shows the status bar for the specified duration.
///
/// If no duration is specified, the status bar is shown for the duration specified in `displayTime`.
/// If the duration specified is `zero`, the status bar is shown until `hide()` is called manually
public func show(forDuration duration: Double? = nil) {
bringToFront()
let duration = duration ?? self.displayTime
isVisible = true
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.4
self.containerView.animator().alphaValue = 1.0
}) {
guard duration > 0.0 else { return }
let delayTime = DispatchTime.now() + Double(Int64(duration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.hide()
}
}
}
/// Hides the status bar after the specified delay
///
/// If no delay is specified, the status bar is hidden immediately
public func hide(afterDelay delay: Double? = 0.0) {
let hideBlock = {
self.isVisible = false
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.4
self.containerView.animator().alphaValue = 0.0
}, completionHandler: nil)
}
guard let delay = delay else { return hideBlock() }
let delayTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
hideBlock()
}
}
private func fixContentViewIfNeeded() {
guard let contentView = window.contentView else { return }
guard !contentView.wantsLayer else { return }
contentView.wantsLayer = true
print("[GRStatusBar] WARNING: Window contentView must have wantsLayer = true")
}
private func buildViews() {
let defaultRect = NSMakeRect(0, 0, LayoutConstants.defaultWidth, LayoutConstants.defaultHeight)
// Container View
containerView = NSView(frame: defaultRect)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: LayoutConstants.defaultHeight))
// Visual Effect View
backgroundView = RoundedVisualEffectView(frame: defaultRect)
backgroundView.blendingMode = .withinWindow
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.material = .appearanceBased
backgroundView.appearance = style.appearance
backgroundView.state = .active
containerView.addSubview(backgroundView)
// Tint View
tintView = GRStatusBarBackgroundView(frame: defaultRect)
tintView.backgroundColor = backgroundColor
tintView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(tintView)
// Label
label = NSTextField(frame: defaultRect)
label.translatesAutoresizingMaskIntoConstraints = false
label.stringValue = text ?? ""
if let attributedText = attributedText {
label.attributedStringValue = attributedText
}
label.isEditable = false
label.isSelectable = false
label.isBezeled = false
label.isBordered = false
label.drawsBackground = false
label.font = NSFont.systemFont(ofSize: LayoutConstants.defaultFontSize)
label.textColor = textColor
label.lineBreakMode = .byTruncatingMiddle
label.sizeToFit()
backgroundView.addSubview(label)
// Configure frames and constraints
containerView.setFrameSize(label.bounds.size)
backgroundView.setFrameSize(label.bounds.size)
tintView.setFrameSize(label.bounds.size)
backgroundView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
backgroundView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
backgroundView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
backgroundView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
tintView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
tintView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
tintView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
tintView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
// Constraint from label to visual effect view, LEFT with padding
let labelLeadingAnchor = label.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor)
labelLeadingAnchor.constant = LayoutConstants.padding
labelLeadingAnchor.isActive = true
// Constraint from label to visual effect view, RIGHT with padding
let labelTrailingAnchor = label.trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor)
labelTrailingAnchor.constant = -LayoutConstants.padding
labelTrailingAnchor.isActive = true
// Constraint to center label vertically inside visual effect view
let labelCenterAnchor = label.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor)
labelCenterAnchor.constant = LayoutConstants.textYOffset
labelCenterAnchor.isActive = true
// Start with the container hidden
containerView.alphaValue = 0.0
if let contentView = window.contentView {
// Start with the best style for the contentView's appearance
style = GRStatusBarStyle(appearance: contentView.appearance)
}
bringToFront()
}
private func bringToFront() {
guard containerView != nil else { return }
if containerView.superview != nil {
containerView.removeFromSuperview()
}
guard let contentView = window.contentView else { return }
contentView.addSubview(containerView)
let leadingConstraint = containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
leadingConstraint.constant = LayoutConstants.margin
leadingConstraint.isActive = true
let bottomConstraint = containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
bottomConstraint.constant = -LayoutConstants.margin
bottomConstraint.isActive = true
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == windowContentViewObserverContext {
bringToFront()
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
deinit {
window.removeObserver(self, forKeyPath: "contentView", context: windowContentViewObserverContext)
}
}
| bsd-2-clause | 011378f40ad3863bc1efdc871e7d69be | 39.038023 | 214 | 0.65831 | 5.616 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/Profiles/ServiceProfilesTableViewController.swift | 1 | 2568 | //
// ServiceProfilesTableViewController.swift
// BlueCap
//
// Created by Troy Stribling on 8/12/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
import BlueCapKit
import CoreBluetooth
class ServiceProfilesTableViewController : UITableViewController {
var serviceProfiles : Dictionary<String, [ServiceProfile]> = [:]
var excludedServices : Array<CBUUID> {
return []
}
var serviceProfileCell : String {
return ""
}
required init(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.sortServiceProfiles()
}
override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
}
func sortServiceProfiles() {
for profile in ProfileManager.sharedInstance.services {
if !contains(self.excludedServices, profile.uuid) {
if let profiles = self.serviceProfiles[profile.tag] {
self.serviceProfiles[profile.tag] = profiles + [profile]
} else {
self.serviceProfiles[profile.tag] = [profile]
}
}
}
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return self.serviceProfiles.count
}
override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int {
let tags = self.serviceProfiles.keys.array
if let profiles = self.serviceProfiles[tags[section]] {
return profiles.count
} else {
return 0
}
}
override func tableView(tableView:UITableView, titleForHeaderInSection section:Int) -> String? {
let tags = self.serviceProfiles.keys.array
return tags[section]
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.serviceProfileCell, forIndexPath: indexPath) as NameUUIDCell
let tags = self.serviceProfiles.keys.array
if let profiles = self.serviceProfiles[tags[indexPath.section]] {
let profile = profiles[indexPath.row]
cell.nameLabel.text = profile.name
cell.uuidLabel.text = profile.uuid.UUIDString
} else {
cell.nameLabel.text = "Unknown"
cell.uuidLabel.text = "Unknown"
}
return cell
}
}
| mit | 4e596fdac474bcc1ffaa05029200fe13 | 29.939759 | 128 | 0.631231 | 4.986408 | false | false | false | false |
furuyan/RadarChartView | RadarChartView/Classes/ChartData.swift | 1 | 519 | //
// ChartData.swift
// RadarChartView
//
// Created by furuyan on 2017/08/18.
// Copyright (c) 2017 furuyan. All rights reserved.
//
import UIKit
public struct ChartDataSet {
public var strokeColor = UIColor.blue
public var fillColor: UIColor? = UIColor(red: 0, green: 0, blue: 1, alpha: 0.5)
public var entries = [ChartDataEntry]()
public init() { }
}
public struct ChartDataEntry {
public var value = CGFloat(0.0)
public init(value: CGFloat) {
self.value = value
}
}
| mit | b9a9d02e60c307b1db0a85e5e10365d4 | 20.625 | 83 | 0.649326 | 3.57931 | false | false | false | false |
wwu-pi/md2-framework | de.wwu.md2.framework/res/resources/ios/lib/view/widget/MD2ImageWidget.swift | 1 | 3607 | //
// MD2ImageWidget.swift
// md2-ios-library
//
// Created by Christoph Rieger on 29.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
import UIKit
/// Image widget outputting an image from a source link.
class MD2ImageWidget: MD2SingleWidget {
/// Unique widget identification.
let widgetId: MD2WidgetMapping
// path relative to /resources/images
var value: MD2Type {
didSet {
updateElement()
}
}
/// Inner dimensions of the screen occupied by the widget.
var dimensions: MD2Dimension?
/// The native UI control.
var widgetElement: UIImageView
/// Height of the widget in pixels.
var height: Float?
/// Width of the widget as specified by the model (percentage of the availale width).
var width: Float?
/**
Default initializer.
:param: widgetId Widget identifier
*/
init(widgetId: MD2WidgetMapping) {
self.widgetId = widgetId
self.value = MD2String()
self.widgetElement = UIImageView()
}
/**
Render the view element, i.e. specifying the position and appearance of the widget.
:param: view The surrounding view element.
:param: controller The responsible view controller.
*/
func render(view: UIView, controller: UIViewController) {
if dimensions == nil {
// Element is not specified in layout. Maybe grid with not enough cells?!
return
}
// Default parameters
widgetElement.contentMode = UIViewContentMode.ScaleAspectFit
// Set value
updateElement()
// Add to surrounding view
view.addSubview(widgetElement)
}
/**
Calculate the dimensions of the widget based on the available bounds. The occupied space of the widget is returned.
*NOTICE* The occupied space may surpass the bounds (and thus the visible screen), if the height of the element is not sufficient. This is not a problem as the screen will scroll automatically.
*NOTICE* The occupied space usually differs from the dimensions property as it refers to the *outer* dimensions in contrast to the dimensions property referring to *inner* dimensions. The difference represents the gutter included in the widget positioning process.
:param: bounds The available screen space.
:returns: The occupied outer dimensions of the widget.
*/
func calculateDimensions(bounds: MD2Dimension) -> MD2Dimension {
let outerDimensions = MD2Dimension(
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: MD2ViewConfig.DIMENSION_IMAGE_HEIGHT)
// Add gutter
self.dimensions = MD2UIUtil.innerDimensionsWithGutter(outerDimensions)
widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!)
return outerDimensions
}
/// Enable the view element.
func enable() {
// Nothing to do on a read-only element
}
/// Disable the view element.
func disable() {
// Nothing to do on a read-only element
}
/**
Update the view element after its value was changed externally.
*/
func updateElement() {
// Image from URL (synchronous call)
if let url = NSURL(string: value.toString()) {
if let data = NSData(contentsOfURL: url) {
widgetElement.image = UIImage(data: data)
}
}
}
} | apache-2.0 | bf5a8a3d43073d076899ee7581dcb4db | 30.373913 | 272 | 0.624619 | 4.995845 | false | false | false | false |
kildevaeld/Sockets | Pod/Classes/DNS/addrinfo.swift | 1 | 1818 | //
// addrinfo.swift
// Sock
//
// Created by Rasmus Kildevæld on 27/07/15.
// Copyright © 2015 Rasmus Kildevæld . All rights reserved.
//
import Foundation
public protocol s_address {
static var domain: Int32 { get }
var socketAddress: SocketAddress { get }
var len: __uint8_t { get }
init()
}
extension s_address {
// Get at empty struct
var empty: s_address {
return self.dynamicType()
}
}
extension addrinfo {
public var canonicalName : String? {
if ai_canonname != nil && ai_canonname[0] != 0 {
return String.fromCString(ai_canonname)
}
return nil
}
public var hasAddress : Bool {
return ai_addr != nil
}
public var isIPv4 : Bool {
return hasAddress &&
(ai_addr.memory.sa_family == sa_family_t(sockaddr_in.domain))
}
public func address<T: s_address>() -> T? {
if ai_addr == nil {
return nil
}
if ai_addr.memory.sa_family != sa_family_t(T.domain) {
return nil
}
let aiptr = UnsafePointer<T>(ai_addr) // cast
return aiptr.memory // copies the address to the return value
}
public func address() -> s_address {
//let addr: s_address
if self.isIPv4 {
let a: sockaddr_in = self.address()!
return a
} else {
let a: sockaddr_in6 = self.address()!
return a
}
//return address
}
public var hasNext : Bool {
return self.ai_next != nil
}
public var next : addrinfo? {
return self.hasNext ? self.ai_next.memory : nil
}
public var family: SocketFamily {
return SocketFamily.fromOption(self.ai_family)
}
}
| mit | 7a2f5359ec433f19774cfa40036d44bc | 20.86747 | 73 | 0.541598 | 3.962882 | false | false | false | false |
cuappdev/eatery | Eatery/Views/Eateries/EateryMenuHeaderView.swift | 1 | 3124 | //
// EateryMenuHeaderView.swift
// Eatery
//
// Created by William Ma on 10/26/19.
// Copyright © 2019 CUAppDev. All rights reserved.
//
import Hero
import UIKit
protocol EateryMenuHeaderViewDelegate: AnyObject {
func favoriteButtonPressed(on sender: EateryMenuHeaderView)
}
class EateryMenuHeaderView: UIView {
private let titleLabel = UILabel()
var titleHero: HeroExtension<UILabel> { return titleLabel.hero }
private let favoriteButton = UIButton()
var favoriteHero: HeroExtension<UIButton> { return favoriteButton.hero }
private let paymentView = PaymentMethodsView()
var paymentHero: HeroExtension<PaymentMethodsView> { return paymentView.hero }
weak var delegate: EateryMenuHeaderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.isOpaque = false
titleLabel.font = .boldSystemFont(ofSize: 34)
titleLabel.textColor = .white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.25
addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.leading.bottom.equalToSuperview().inset(16)
}
favoriteButton.setImage(UIImage(named: "whiteStar"), for: .normal)
favoriteButton.imageEdgeInsets = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0)
favoriteButton.tintColor = .favoriteYellow
favoriteButton.addTarget(self, action: #selector(favoriteButtonPressed(_:)), for: .touchUpInside)
addSubview(favoriteButton)
favoriteButton.snp.makeConstraints { make in
make.centerY.equalTo(titleLabel.snp.centerY)
make.leading.equalTo(titleLabel.snp.trailing).offset(16)
make.width.height.equalTo(28)
}
addSubview(paymentView)
paymentView.snp.makeConstraints { make in
make.leading.greaterThanOrEqualTo(favoriteButton.snp.trailing)
make.trailing.equalToSuperview().inset(16)
make.centerY.equalTo(titleLabel.snp.centerY)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure(title: String,
status: EateryStatus,
isFavorite: Bool,
paymentMethods: [PaymentMethod]) {
titleLabel.text = title
switch status {
case .open, .closingSoon: titleLabel.textColor = .white
case .closed, .openingSoon: titleLabel.textColor = .lightGray
}
favoriteButton.setImage(UIImage(named: isFavorite ? "goldStar" : "whiteStar"),
for: .normal)
paymentView.paymentMethods = paymentMethods
}
func configure(eatery: Eatery) {
configure(title: eatery.displayName,
status: eatery.currentStatus(),
isFavorite: eatery.isFavorite(),
paymentMethods: eatery.paymentMethods)
}
@objc private func favoriteButtonPressed(_ sender: UIButton) {
delegate?.favoriteButtonPressed(on: self)
}
}
| mit | 35241c0da2a274851692def7d1f0556e | 32.223404 | 105 | 0.658021 | 4.910377 | false | false | false | false |
johnno1962d/swift | test/Prototypes/CollectionTransformers.swift | 1 | 39020 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
public enum ApproximateCount {
case Unknown
case Precise(IntMax)
case Underestimate(IntMax)
case Overestimate(IntMax)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<Index : RandomAccessIndex>(
_ range: Range<Index>
) -> [Range<Index>] {
let startIndex = range.startIndex
let endIndex = range.endIndex
let length = startIndex.distance(to: endIndex).toIntMax()
if length < 2 {
return [range]
}
let middle = startIndex.advanced(by: Index.Distance(length / 2))
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
typealias Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C)
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
where
C.Iterator.Element == T
>(contentsOf elements: C) {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.flatten())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: linux
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public var hashValue: Int {
return _value.hashValue
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer(allocatingCapacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize()
_mutex.deallocateCapacity(1)
}
func withLock<Result>(body: @noescape () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer(allocatingCapacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize()
_cond.deallocateCapacity(1)
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: () -> T,
isEquivalent: (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: dispatch_queue_t? = nil
if #available(OSX 10.10, iOS 8.0, *) {
queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
} else {
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
}
dispatch_async(queue!) {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool? = nil
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result? = nil
public init(_task: () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.index { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: @noescape () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = pickRandom(_workDeques.indices)
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
where
C.Iterator.Element == ForkJoinTaskBase
>(_ tasks: C) {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
pickRandom(_submissionQueues).append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
pickRandom(_submissionQueues).append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ predicate: (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ predicate: (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
predicate($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
for i in range {
let e = c[i]
collector.append(e)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.PipelineInputElement == PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, OutputElement> {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ predicate: (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {
(input: InputElement) -> OutputElement? in
if let e = localTransform(input) {
return predicate(e) ? e : nil
}
return nil
}
}
override func reduce<U>(_ initial: U, _ combine: (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
) {
var collectorWrapper =
_ElementCollectorOneToMaybeOne(collector, _transform)
_input.transform(c, range, &collectorWrapper)
collector = collectorWrapper._baseCollector
}
}
struct _ElementCollectorOneToMaybeOne<
BaseCollector : _ElementCollector,
Element_
> : _ElementCollector {
typealias Element = Element_
var _baseCollector: BaseCollector
var _transform: (Element) -> BaseCollector.Element?
init(
_ baseCollector: BaseCollector,
_ transform: (Element) -> BaseCollector.Element?
) {
self._baseCollector = baseCollector
self._transform = transform
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
if let e = _transform(element) {
_baseCollector.append(e)
}
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
for e in elements {
append(e)
}
}
}
protocol _ElementCollector {
associatedtype Element
mutating func sizeHint(_ approximateSize: Int)
mutating func append(_ element: Element)
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C)
}
class _CollectionTransformerFinalizer<PipelineInputElement, Result> {
func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> Result {
fatalError("implement")
}
}
final class _CollectionTransformerFinalizerReduce<
PipelineInputElement,
U,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement
> : _CollectionTransformerFinalizer<PipelineInputElement, U> {
var _input: InputStep
var _initial: U
var _combine: (U, InputElementTy) -> U
init(_ input: InputStep, _ initial: U, _ combine: (U, InputElementTy) -> U) {
self._input = input
self._initial = initial
self._combine = combine
}
override func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> U {
var collector = _ElementCollectorReduce(_initial, _combine)
_input.transform(c, c.indices, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorReduce<Element_, Result> : _ElementCollector {
typealias Element = Element_
var _current: Result
var _combine: (Result, Element) -> Result
init(_ initial: Result, _ combine: (Result, Element) -> Result) {
self._current = initial
self._combine = combine
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
_current = _combine(_current, element)
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
for e in elements {
append(e)
}
}
mutating func takeResult() -> Result {
return _current
}
}
final class _CollectionTransformerFinalizerCollectTo<
PipelineInputElement,
U : BuildableCollectionProtocol,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement,
U.Builder.Destination == U,
U.Builder.Element == U.Iterator.Element,
U.Iterator.Element == InputStep.OutputElement
> : _CollectionTransformerFinalizer<PipelineInputElement, U> {
var _input: InputStep
init(_ input: InputStep, _: U.Type) {
self._input = input
}
override func transform<
InputCollection : Collection
where
InputCollection.Iterator.Element == PipelineInputElement
>(_ c: InputCollection) -> U {
var collector = _ElementCollectorCollectTo<U>()
_input.transform(c, c.indices, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorCollectTo<
BuildableCollection : BuildableCollectionProtocol
where
BuildableCollection.Builder.Destination == BuildableCollection,
BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element
> : _ElementCollector {
typealias Element = BuildableCollection.Iterator.Element
var _builder: BuildableCollection.Builder
init() {
self._builder = BuildableCollection.Builder()
}
mutating func sizeHint(_ approximateSize: Int) {
_builder.sizeHint(approximateSize)
}
mutating func append(_ element: Element) {
_builder.append(element)
}
mutating func append<
C : Collection
where
C.Iterator.Element == Element
>(contentsOf elements: C) {
_builder.append(contentsOf: elements)
}
mutating func takeResult() -> BuildableCollection {
return _builder.takeResult()
}
}
internal func _optimizeCollectionTransformer<PipelineInputElement, Result>(
_ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result>
) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> {
return transformer
}
internal func _runCollectionTransformer<
InputCollection : Collection, Result
>(
_ c: InputCollection,
_ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result>
) -> Result {
dump(transformer)
let optimized = _optimizeCollectionTransformer(transformer)
dump(optimized)
return transformer.transform(c)
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: public interface
//===----------------------------------------------------------------------===//
public struct CollectionTransformerPipeline<
InputCollection : Collection, T
> {
internal var _input: InputCollection
internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T>
public func map<U>(_ transform: (T) -> U)
-> CollectionTransformerPipeline<InputCollection, U> {
return CollectionTransformerPipeline<InputCollection, U>(
_input: _input,
_step: _step.map(transform)
)
}
public func filter(_ predicate: (T) -> Bool)
-> CollectionTransformerPipeline<InputCollection, T> {
return CollectionTransformerPipeline<InputCollection, T>(
_input: _input,
_step: _step.filter(predicate)
)
}
public func reduce<U>(_ initial: U, _ combine: (U, T) -> U) -> U {
return _runCollectionTransformer(_input, _step.reduce(initial, combine))
}
public func collectTo<
C : BuildableCollectionProtocol
where
C.Builder.Destination == C,
C.Iterator.Element == T,
C.Builder.Element == T
>(_ c: C.Type) -> C {
return _runCollectionTransformer(_input, _step.collectTo(c))
}
public func toArray() -> [T] {
return collectTo(Array<T>.self)
}
}
public func transform<C : Collection>(_ c: C)
-> CollectionTransformerPipeline<C, C.Iterator.Element> {
return CollectionTransformerPipeline<C, C.Iterator.Element>(
_input: c,
_step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>())
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: tests
//===----------------------------------------------------------------------===//
import StdlibUnittest
var t = TestSuite("t")
t.test("fusion/map+reduce") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+filter+reduce") {
let xs = [ 1, 2, 3 ]
let result = transform(xs)
.map { $0 * 2 }
.filter { $0 != 0 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+collectTo") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.collectTo(Array<Int>.self)
expectEqual([ 2, 4, 6 ], result)
}
t.test("fusion/map+toArray") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.toArray()
expectEqual([ 2, 4, 6 ], result)
}
t.test("ForkJoinPool.forkTask") {
var tasks: [ForkJoinTask<()>] = []
for i in 0..<100 {
tasks.append(ForkJoinPool.commonPool.forkTask {
() -> () in
var result = 1
for i in 0..<10000 {
result = result &* i
_blackHole(result)
}
return ()
})
}
for t in tasks {
t.wait()
}
}
func fib(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if n == 38 {
print("\(pthread_self()) fib(\(n))")
}
if n < 39 {
let r = fib(n - 1) + fib(n - 2)
_blackHole(r)
return r
}
print("fib(\(n))")
let t1 = ForkJoinTask() { fib(n - 1) }
let t2 = ForkJoinTask() { fib(n - 2) }
ForkJoinPool.invokeAll(t1, t2)
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
t.test("ForkJoinPool.forkTask/Fibonacci") {
let t = ForkJoinPool.commonPool.forkTask { fib(40) }
expectEqual(102334155, t.waitAndGetResult())
}
func _parallelMap(_ input: [Int], transform: (Int) -> Int, range: Range<Int>)
-> Array<Int>.Builder {
var builder = Array<Int>.Builder()
if range.count < 1_000 {
builder.append(contentsOf: input[range].map(transform))
} else {
let tasks = input.split(range).map {
(subRange) in
ForkJoinTask<Array<Int>.Builder> {
_parallelMap(input, transform: transform, range: subRange)
}
}
ForkJoinPool.invokeAll(tasks)
for t in tasks {
var otherBuilder = t.waitAndGetResult()
builder.moveContentsOf(&otherBuilder)
}
}
return builder
}
func parallelMap(_ input: [Int], transform: (Int) -> Int) -> [Int] {
let t = ForkJoinPool.commonPool.forkTask {
_parallelMap(input, transform: transform, range: input.indices)
}
var builder = t.waitAndGetResult()
return builder.takeResult()
}
t.test("ForkJoinPool.forkTask/MapArray") {
expectEqual(
Array(2..<1_001),
parallelMap(Array(1..<1_000)) { $0 + 1 }
)
}
/*
* FIXME: reduce compiler crasher
t.test("ForkJoinPool.forkTask") {
func fib(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 1
}
let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) }
let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) }
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
expectEqual(0, fib(10))
}
*/
/*
Useful links:
http://habrahabr.ru/post/255659/
*/
runAllTests()
| apache-2.0 | 014fd2b7f18c2d8d83a525e798d2713a | 25.966137 | 108 | 0.651076 | 4.534046 | false | false | false | false |
nyin005/Forecast-App | Forecast/Forecast/Class/DashBoard/ChartsViews/BarChartRootView.swift | 1 | 6288 | //
// BarChartRootView.swift
// Forecast
//
// Created by appledev110 on 11/18/16.
// Copyright © 2016 appledev110. All rights reserved.
//
import UIKit
import Charts
class BarChartRootView: UIView {
@IBOutlet weak var radiusView: UIView!
@IBOutlet weak var barChartView: BarChartView!
private var losValueDic = NSMutableDictionary()
private var keys = [String]()
private var responseData = [LosListModel]()
func initChartUI(arr: [LosListModel]) {
responseData = arr
radiusView.layer.cornerRadius = 5
self.convertListToSuitChart(arr: arr)
// self.barChartView.drawValueAboveBarEnabled = false
self.barChartView.xAxis.drawGridLinesEnabled = false
// self.barChartView.leftAxis.drawGridLinesEnabled = false
self.barChartView.leftAxis.axisLineColor = StringUtil.getColorWithRGB(red: 200, green: 200, blue: 200)
self.barChartView.xAxis.axisLineColor = StringUtil.getColorWithRGB(red: 200, green: 200, blue: 200)
self.barChartView.xAxis.labelTextColor = StringUtil.getColorWithRGB(red: 102, green: 102, blue: 102)
self.barChartView.leftAxis.labelTextColor = StringUtil.getColorWithRGB(red: 102, green: 102, blue: 102)
self.barChartView.leftAxis.gridColor = StringUtil.getColorWithRGB(red: 232, green: 232, blue: 232)
self.barChartView.xAxis.centerAxisLabelsEnabled = false
self.barChartView.xAxis.wordWrapEnabled = true
self.barChartView.legend.form = .circle
self.barChartView.legend.textColor = StringUtil.getColorWithRGB(red: 85, green: 85, blue: 85)
self.barChartView.rightAxis.enabled = false
self.barChartView.chartDescription?.enabled = false
self.barChartView.xAxis.labelCount = self.keys.count as Int
self.barChartView.xAxis.labelPosition = .bottom
self.barChartView.leftAxis.axisMinimum = 0.0
self.barChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 8)
// self.barChartView.xAxis.labelFont = UIFont.boldSystemFont(ofSize: 5)
self.configureStackBarChartData()
let xAxis = self.barChartView.xAxis
// set x axis value formatter
unowned let wself = self
xAxis.valueFormatter = DefaultAxisValueFormatter.with(block: { (value, xAis) -> String in
// [unowned self] in
if (value >= 0) && (value < Double(wself.keys.count)) {
var labelString = wself.keys[Int(value)]
labelString = labelString.replacingOccurrences(of: " ", with: "\n")
return labelString
}
return ""
})
let marker: XYMarkerView = XYMarkerView(color: UIColor(white: 180/255.0, alpha: 1.0), font: UIFont.systemFont(ofSize: 10.0), textColor: .white, insets: UIEdgeInsetsMake(2.0, 2.0, 4.0, 2.0), xAxisValueFormatter: self.barChartView.xAxis.valueFormatter!)
marker.chartView = self.barChartView
marker.minimumSize = CGSize(width: 80.0, height: 40.0)
self.barChartView.marker = marker
}
func configureStackBarChartData() {
self.barChartView.xAxis.resetCustomAxisMin()
self.barChartView.xAxis.resetCustomAxisMax()
var dataSets: [BarChartDataSet] = [BarChartDataSet]()
let start = 0.0
let groupCount = self.keys.count as Int
let end = Int(start) + groupCount
var barChartDataSet: BarChartDataSet = BarChartDataSet()
var enties = [BarChartDataEntry]()
for index in Int(start)...end-1 {
// 获取总共多少个x轴的单元格
let strKey = self.keys[index]
var yValues = [Double]()
var entry: BarChartDataEntry?
for losModel in responseData {
// 每个格子合起来的数据
for detailModel in losModel.LosValues! {
if detailModel.label! == strKey {
yValues.append(Double(detailModel.value!)!)
}
}
}
entry = BarChartDataEntry(x: Double(index), yValues: yValues, label: strKey)
enties.append(entry!)
}
barChartDataSet = BarChartDataSet(values: enties, label: "")
// barChartDataSet.drawValuesEnabled = false
let valueTuple = self.getAllKeys()
barChartDataSet.stackLabels = valueTuple.keys
barChartDataSet.colors = valueTuple.colors
dataSets.append(barChartDataSet)
let barChartData = BarChartData(dataSets: dataSets)
// set the value format
let formato: BarChartValueFormatter = BarChartValueFormatter()
barChartData.setValueFormatter(formato)
barChartData.barWidth = 0.5
self.barChartView.fitBars = true
self.barChartView.data = barChartData
}
// 过滤出Stack类型中每个柱子需要的label和颜色
func getAllKeys() -> (keys:[String], colors:[UIColor]) {
var keys = [String]()
var colors = [UIColor]()
for listModel in responseData {
keys.append(listModel.LosKey!)
colors.append(UIColor.init(hexString: listModel.LosColor!))
}
return (keys,colors)
}
// 获取barchart里所有的x轴的数据
func convertListToSuitChart(arr: [LosListModel]) {
var indexCount = 0
for losModel in arr {
if let values = losModel.LosValues {
for index in 0...values.count-1 {
let detailModel = values[index]
if self.losValueDic.allKeys.contains(obj: detailModel.label! as String) {
} else {
self.losValueDic.setObject(indexCount, forKey: String(detailModel.label!) as String as NSCopying)
indexCount += 1
}
}
}
}
self.keys = self.losValueDic.allKeys as! [String]
self.keys = self.keys.sorted(by: { (str1, str2) -> Bool in
return str1.lowercased() < str2.lowercased() ? true : false
})
}
}
| gpl-3.0 | f873970012979ce6b8a8f31fef5efa7b | 40 | 259 | 0.608948 | 4.654887 | false | false | false | false |
yellowei/HWPerfectDemo | Sources/main.swift | 1 | 4813 | //
// main.swift
// PerfectTemplate
//
// Created by Kyle Jessup on 2015-11-05.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
import PerfectMustache
//MARK: - request handler.
// This 'handler' function can be referenced directly in the configuration below.
/// 一般处理句柄
///
/// - Parameter data: 路由参数
/// - Returns: 处理请求的回调闭包
/// - Throws: 异常处理
func normalHandler(data: [String:Any]) throws -> RequestHandler {
guard let uri = data["uri"] as? String else {
return try errorHandler(data: data)
}
switch uri {
case "/login":
return try loginHandler(data: data)
case "/":
return try mustacheHandler(data: data)
default:
return try errorHandler(data: data)
}
}
/// 错误处理句柄
///
/// - Parameter data: 路由参数
/// - Returns: 处理请求的回调闭包
/// - Throws: 异常处理
func errorHandler(data: [String: Any]) throws -> RequestHandler {
return {(request, response)->() in
response.appendBody(string: "请求处理错误")
response.completed()
}
}
/// 登录处理句柄
///
/// - Parameter data: 路由参数
/// - Returns: 处理请求的回调闭包
/// - Throws: 异常处理
func loginHandler(data: [String:Any]) throws -> RequestHandler {
return { request, response in
// Respond with a simple message.
guard let userName = request.param(name: "userName") else {
return
}
guard let password = request.param(name: "password") else {
return
}
let responsDic: [String : Any] = ["response":["userName":userName,
"password":password],
"result":"SUCCESS",
"resultMessage":"请求成功"]
do{
let json = try responsDic.jsonEncodedString()
response.setBody(string: json)
}catch{
response.setBody(string: "json转换错误")
}
response.completed()
}
}
func mustacheHandler(data: [String: Any]) throws -> RequestHandler {
return {(request, response)->() in
let webRoot = request.documentRoot
mustacheRequest(request: request, response: response, handler: BaseHandler(), templatePath: webRoot + "/index.html")
}
}
//MARK: - Configuration data for two servers.
// This configuration shows how to launch one or more servers
// using a configuration dictionary.
let port1 = 8080, port2 = 8181
HTTPServer().documentRoot = "/Users/yellowei/Documents/MyPods/HWPerfectDemo/webroot"
let confData = [
"servers": [
// Configuration data for one server which:
// * Serves the hello world message at <host>:<port>/
// * Serves static files out of the "./webroot"
// directory (which must be located in the current working directory).
// * Performs content compression on outgoing data when appropriate.
[
"name":"localhost",
"port":port1,
"routes":[
["method":"get", "uri":"/", "handler":normalHandler,
"documentRoot":"/Users/yellowei/Documents/MyPods/HWPerfectDemo/webroot",
"allowResponseFilters":true],
["method":"post", "uri":"/login", "handler":normalHandler]
],
"filters":[
[
"type":"response",
"priority":"high",
"name":PerfectHTTPServer.HTTPFilter.contentCompression,
]
]
],
// Configuration data for another server which:
// * Redirects all traffic back to the first server.
[
"name":"localhost",
"port":port2,
"routes":[
["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.redirect,
"base":"http://localhost:\(port1)"]
]
]
]
]
do {
// Launch the servers based on the configuration data.
try HTTPServer.launch(configurationData: confData)
} catch {
fatalError("\(error)") // fatal error launching one of the servers
}
| mit | 67b92a69e67f4900888310674ce70375 | 27.509202 | 124 | 0.548526 | 4.60099 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Models/Movement.swift | 1 | 8240 |
//
// Movement.swift
// Webretail
//
// Created by Gerardo Grisolini on 28/02/17.
//
//
import Foundation
import StORM
struct ItemValue: Codable {
public var value: String
}
class Movement: PostgresSqlORM, Codable {
public var movementId : Int = 0
public var invoiceId : Int = 0
public var movementNumber : Int = 0
public var movementDate : Int = Int.now()
public var movementDesc : String = ""
public var movementNote : String = ""
public var movementStatus : String = ""
public var movementUser : String = ""
public var movementDevice : String = ""
public var movementStore : Store = Store()
public var movementCausal : Causal = Causal()
public var movementRegistry : Registry = Registry()
public var movementTags : [Tag] = [Tag]()
public var movementPayment : String = ""
public var movementShipping : String = ""
public var movementShippingCost : Double = 0
public var movementAmount : Double = 0
public var movementUpdated : Int = Int.now()
public var _movementDate: String {
return movementDate.formatDateShort()
}
public var _items : [MovementArticle] = [MovementArticle]()
private enum CodingKeys: String, CodingKey {
case movementId
case movementNumber
case movementDate
case movementDesc
case movementNote
case movementStatus
case movementUser
case movementDevice
case movementStore
case movementCausal
case movementRegistry
case movementTags
case movementPayment
case movementShipping
case movementShippingCost
case movementAmount
case _items = "movementItems"
case movementUpdated = "updatedAt"
}
open override func table() -> String { return "movements" }
open override func to(_ this: StORMRow) {
movementId = this.data["movementid"] as? Int ?? 0
movementNumber = this.data["movementnumber"] as? Int ?? 0
movementDate = this.data["movementdate"] as? Int ?? 0
movementDesc = this.data["movementdesc"] as? String ?? ""
movementNote = this.data["movementnote"] as? String ?? ""
movementStatus = this.data["movementstatus"] as? String ?? ""
movementUser = this.data["movementuser"] as? String ?? ""
movementDevice = this.data["movementdevice"] as? String ?? ""
let decoder = JSONDecoder()
var jsonData = try! JSONSerialization.data(withJSONObject: this.data["movementstore"]!, options: [])
movementStore = try! decoder.decode(Store.self, from: jsonData)
jsonData = try! JSONSerialization.data(withJSONObject: this.data["movementcausal"]!, options: [])
movementCausal = try! decoder.decode(Causal.self, from: jsonData)
if let json = this.data["movementregistry"] as? [String:Any] {
if json.count > 0 {
jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
movementRegistry = try! decoder.decode(Registry.self, from: jsonData)
}
}
if let json = this.data["movementtags"] as? [[String:Any]] {
if json.count > 0 {
jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
movementTags = try! decoder.decode([Tag].self, from: jsonData)
}
}
movementPayment = this.data["movementpayment"] as? String ?? ""
movementShipping = this.data["movementshipping"] as? String ?? ""
movementShippingCost = Double(this.data["movementshippingcost"] as? Float ?? 0)
movementAmount = Double(this.data["movementamount"] as? Float ?? 0)
movementUpdated = this.data["movementupdated"] as? Int ?? 0
}
func rows() throws -> [Movement] {
var rows = [Movement]()
for i in 0..<self.results.rows.count {
let row = Movement()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
movementId = try container.decodeIfPresent(Int.self, forKey: .movementId) ?? 0
movementNumber = try container.decode(Int.self, forKey: .movementNumber)
movementDate = try container.decode(String.self, forKey: .movementDate).DateToInt()
movementDesc = try container.decodeIfPresent(String.self, forKey: .movementDesc) ?? ""
movementNote = try container.decode(String.self, forKey: .movementNote)
movementStatus = try container.decode(String.self, forKey: .movementStatus)
movementUser = try container.decode(String.self, forKey: .movementUser)
movementDevice = try container.decode(String.self, forKey: .movementDevice)
movementStore = try container.decode(Store.self, forKey: .movementStore)
movementCausal = try container.decode(Causal.self, forKey: .movementCausal)
movementRegistry = try container.decodeIfPresent(Registry.self, forKey: .movementRegistry) ?? Registry()
movementTags = try container.decodeIfPresent([Tag].self, forKey: .movementTags) ?? [Tag]()
movementPayment = try container.decode(String.self, forKey: .movementPayment)
movementShipping = try container.decodeIfPresent(String.self, forKey: .movementShipping) ?? ""
movementShippingCost = try container.decodeIfPresent(Double.self, forKey: .movementShippingCost) ?? 0
movementAmount = try container.decodeIfPresent(Double.self, forKey: .movementAmount) ?? 0
_items = try container.decodeIfPresent([MovementArticle].self, forKey: ._items) ?? [MovementArticle]()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(movementId, forKey: .movementId)
try container.encode(movementNumber, forKey: .movementNumber)
try container.encode(_movementDate, forKey: .movementDate)
try container.encode(movementDesc, forKey: .movementDesc)
try container.encode(movementNote, forKey: .movementNote)
try container.encode(movementStatus, forKey: .movementStatus)
try container.encode(movementUser, forKey: .movementUser)
try container.encode(movementDevice, forKey: .movementDevice)
try container.encode(movementStore, forKey: .movementStore)
try container.encode(movementCausal, forKey: .movementCausal)
try container.encode(movementRegistry, forKey: .movementRegistry)
try container.encode(movementTags, forKey: .movementTags)
try container.encode(movementPayment, forKey: .movementPayment)
try container.encode(movementShipping, forKey: .movementShipping)
try container.encode(movementShippingCost, forKey: .movementShippingCost)
try container.encode(movementAmount, forKey: .movementAmount)
try container.encode(_items, forKey: ._items)
try container.encode(movementUpdated, forKey: .movementUpdated)
}
func newNumber() throws {
var params = [String]()
var sql = "SELECT MAX(movementNumber) AS counter FROM \(table())";
if self.movementCausal.causalIsPos {
sql += " WHERE movementDevice = $1 AND to_char(to_timestamp(movementDate + extract(epoch from timestamp '2001-01-01 00:00:00')), 'YYYY-MM-DD') = $2";
params.append(movementDevice)
params.append(movementDate.formatDate(format: "yyyy-MM-dd"))
}
let getCount = try self.sqlRows(sql, params: params)
self.movementNumber = (getCount.first?.data["counter"] as? Int ?? 0) + (self.movementCausal.causalIsPos ? 1 : 1000)
}
func getAmount() throws {
let sql = "SELECT SUM(movementArticleQuantity * movementArticlePrice) AS amount FROM movementArticles WHERE movementId = $1";
let getCount = try self.sqlRows(sql, params: [String(movementId)])
self.movementAmount = Double(getCount.first?.data["amount"] as? Float ?? 0)
}
}
| apache-2.0 | 5a04cab3acd2ef950ab85c85a9f2be91 | 45.292135 | 161 | 0.657888 | 4.411135 | false | false | false | false |
mownier/photostream | Photostream/UI/Profile Edit/ProfileEditTableCell.swift | 1 | 3147 | //
// ProfileEditTableCell.swift
// Photostream
//
// Created by Mounir Ybanez on 09/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
import UIKit
enum ProfileEditTableCellStyle {
case `default`
case lineEdit
var reuseId: String {
switch self {
case .default:
return "ProfileEditTableCellDefault"
case .lineEdit:
return "ProfileEditTableCellLineEdit"
}
}
}
class ProfileEditTableCell: UITableViewCell {
var style: ProfileEditTableCellStyle = .default
var infoLabel: UILabel!
var infoDetailLabel: UILabel?
var infoTextField: UITextField?
init(style: ProfileEditTableCellStyle) {
super.init(style: .default, reuseIdentifier: style.reuseId)
self.style = style
initSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
func initSetup() {
infoLabel = UILabel()
infoLabel.textColor = UIColor.lightGray
infoLabel.font = UIFont.systemFont(ofSize: 10)
addSubview(infoLabel)
switch style {
case .default:
infoDetailLabel = UILabel()
infoDetailLabel!.font = UIFont.systemFont(ofSize: 14)
infoDetailLabel!.numberOfLines = 0
addSubview(infoDetailLabel!)
case .lineEdit:
infoTextField = UITextField()
infoTextField!.font = UIFont.systemFont(ofSize: 14)
addSubview(infoTextField!)
}
}
override func layoutSubviews() {
var rect = CGRect.zero
infoLabel.sizeToFit()
rect.origin.x = spacing * 2
rect.origin.y = spacing * 2
rect.size.width = frame.width - (spacing * 4)
rect.size.height = infoLabel.frame.height
infoLabel.frame = rect
switch style {
case .default:
infoDetailLabel!.sizeToFit()
rect.origin.y = rect.maxY
if infoDetailLabel!.text == nil || infoDetailLabel!.text!.isEmpty {
rect.size.height = infoDetailLabel!.font!.pointSize
rect.size.height += (spacing * 2)
} else {
rect.size.height = infoDetailLabel!.frame.height
}
infoDetailLabel!.frame = rect
case .lineEdit:
rect.origin.y = rect.maxY
rect.size.height = infoTextField!.font!.pointSize + (spacing * 2)
infoTextField!.frame = rect
}
}
}
extension ProfileEditTableCell {
var spacing: CGFloat {
return 4.0
}
}
extension ProfileEditTableCell {
class func dequeue(from tableView: UITableView, style: ProfileEditTableCellStyle) -> ProfileEditTableCell? {
var cell = tableView.dequeueReusableCell(withIdentifier: style.reuseId)
if cell == nil {
cell = ProfileEditTableCell(style: style)
}
return cell as? ProfileEditTableCell
}
}
| mit | 44e75fe0c51a2441c77f522c31db5402 | 25.888889 | 112 | 0.574062 | 4.954331 | false | false | false | false |
zj-insist/QSImageBucket | QSIMageBucket/AppConfig.swift | 1 | 2125 | //
// AppConfig.swift
// U图床
//
// Created by Pro.chen on 07/02/2017.
// Copyright © 2017 chenxt. All rights reserved.
//
import Cocoa
enum LinkType : Int {
case url = 0
case markdown = 1
static func getLink(path:String,type:LinkType) -> String{
let name = NSString(string: path).lastPathComponent
switch type {
case .markdown:
return ""
// return ""
case .url:
return path
}
}
}
enum UploadType : Int {
case defaultType = 0
case QNType = 1
case AliOSSType = 2
}
class AppConfig: NSObject ,NSCoding ,DiskCache{
var linkType : LinkType = .url //链接模式
var autoUp : Bool = false //是否自动上传
var useDefServer : Bool = true //是否配置好 , true 未配置, false 已配置
var uploadType : UploadType = .defaultType //上传模式
func encode(with aCoder: NSCoder) {
aCoder.encode(linkType.rawValue.description, forKey: "linkType")
aCoder.encode(autoUp.hashValue.description, forKey: "autoUp")
aCoder.encode(useDefServer.hashValue.description, forKey: "useDefServer")
aCoder.encode(uploadType.rawValue.description, forKey: "uploadType")
}
required init?(coder aDecoder: NSCoder) {
guard let _ = aDecoder.decodeObject(forKey: "linkType") else {
return nil
}
guard let _ = aDecoder.decodeObject(forKey: "uploadType") else {
return nil
}
autoUp = Bool(NSNumber(value: Int(aDecoder.decodeObject(forKey: "autoUp") as! String)!))
linkType = LinkType(rawValue: Int(aDecoder.decodeObject(forKey: "linkType") as! String)! )!
useDefServer = Bool(NSNumber(value: Int(aDecoder.decodeObject(forKey: "useDefServer") as! String)!))
uploadType = UploadType(rawValue: Int(aDecoder.decodeObject(forKey: "uploadType") as! String)! )!
super.init()
}
override init() {
super.init();
setInCache("appConfig");
}
}
| mit | 912ff254b5068f9a9624177977cb9c1e | 29.835821 | 108 | 0.601646 | 4.003876 | false | false | false | false |
dmzza/Timepiece | Timepiece.playground/Contents.swift | 2 | 1035 | import Foundation
import Timepiece
//: ### Add durations to date
let now = NSDate()
let nextWeek = now + 1.week
let dayAfterTomorrow = now + 2.days
// shortcuts #1
let today = NSDate.today()
let tomorrow = NSDate.tomorrow()
let yesterday = NSDate.yesterday()
// shortcuts #2
let dayBeforeYesterday = 2.days.ago
let tokyoOlympicYear = 5.years.later
//: ### Initialize by specifying date components
let birthday = NSDate.date(year: 1987, month: 6, day: 2)
let firstCommitDate = NSDate.date(year: 2014, month: 8, day: 15, hour: 20, minute: 25, second: 43)
//: ### Initialize by changing date components
let christmas = now.change(month: 12, day: 25)
let thisSunday = now.change(weekday: 1)
// shortcuts
let newYearDay = now.beginningOfYear
let timeLimit = now.endOfHour
//: ### Time zone
let cst = NSTimeZone(abbreviation: "CST")!
let dateInCST = now.beginningOfDay.change(timeZone: cst)
dateInCST.timeZone
//: ### Format and parse
5.minutes.later.stringFromFormat("yyyy-MM-dd HH:mm:SS")
"1987-06-02".dateFromFormat("yyyy-MM-dd")
| mit | 5d3ebeed834f42abb2a618e3ed97a07f | 26.972973 | 98 | 0.725604 | 3.317308 | false | false | false | false |
semonchan/LearningSwift | Project/Project - 02 - CustomFonts/VC- Project - 02 - CustomFonts/ViewController.swift | 1 | 2331 | //
// ViewController.swift
// VC- Project - 02 - CustomFonts
//
// Created by 程超 on 2017/11/21.
// Copyright © 2017年 程超. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var data = [ "《生活不止眼前的苟且》",
"妈妈坐在门前,哼着花儿与少年",
"虽已时隔多年,记得她泪水涟涟",
"那些幽暗的时光,那些坚持与慌张",
"在临别的门前,妈妈望着我说",
"生活不止眼前的苟且,还有诗和远方的田野",
"你赤手空拳来到人世间,为找到那片海不顾一切",
" --- 许巍"]
// 字体
let fontNames = ["Copperplate-Bold", "Copperplate","Copperplate-Light"]
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var changeFontButton: UIButton!
var fontRowIndex = 0
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
changeFontButton.layer.cornerRadius = 50
changeFontButton.layer.masksToBounds = true
tableView.dataSource = self
tableView.delegate = self
}
@IBAction func changeFontAction(_ sender: Any) {
fontRowIndex = (fontRowIndex + 1) % 3
tableView.reloadData()
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL_IDENTIFIER", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.font = UIFont(name: self.fontNames[fontRowIndex], size: 16)
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
| mit | 4d1f55557c410729059280090ee378d6 | 29.405797 | 100 | 0.622021 | 4.065891 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Main Categories/General/Models/Event.swift | 1 | 750 | //
// Event.swift
// HTWDD
//
// Created by Benjamin Herzog on 05/03/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import Marshal
struct Event: Codable, Hashable {
let name: String
let period: EventPeriod
var hashValue: Int {
var hash = 5381
hash = ((hash << 5) &+ hash) &+ name.hashValue
hash = ((hash << 5) &+ hash) &+ period.hashValue
return hash
}
static func ==(lhs: Event, rhs: Event) -> Bool {
return lhs.name == rhs.name && lhs.period == rhs.period
}
}
extension Event: Unmarshaling {
init(object: MarshaledObject) throws {
self.name = try object <| "name"
self.period = try EventPeriod(object: object)
}
}
| mit | 4b45774e0a90a284201c784bf6507a44 | 20.4 | 63 | 0.598131 | 3.707921 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Components/Settings/Lecture Manager/Views/SwitchCell.swift | 1 | 3699 | //
// SwitchCell.swift
// HTWDD
//
// Created by Fabian Ehlert on 22.12.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
struct SwitchViewModel: ViewModel {
let title: String
let subtitle: String
let hidden: Bool
init(model: AppLecture) {
self.title = model.lecture.name
let begin = Loca.Schedule.Cell.time(model.lecture.begin.hour ?? 0, model.lecture.begin.minute ?? 0)
let end = Loca.Schedule.Cell.time(model.lecture.end.hour ?? 0, model.lecture.end.minute ?? 0)
var s = Loca.Schedule.Settings.Cell.subtitle(model.lecture.week.stringValue, begin, end)
if (model.lecture.weeks?.count ?? 0) == 1 {
s = Loca.Schedule.Settings.Cell.subtitle(Loca.Schedule.Weeks.once, begin, end)
}
self.subtitle = s
self.hidden = model.hidden
}
}
class SwitchCell: TableViewCell, Cell {
enum Const {
static let margin: CGFloat = 15
static let verticalMargin: CGFloat = 10
}
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 17, weight: .medium)
label.numberOfLines = 2
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 15, weight: .medium)
label.textColor = UIColor.htw.grey
label.numberOfLines = 1
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var activeSwitch: UISwitch = {
let s = UISwitch()
s.addTarget(self, action: #selector(hiddenChanges(hiddenSwitch:)), for: .valueChanged)
return s
}()
var onStatusChange: ((Bool) -> Void)?
// MARK: - Init
override func initialSetup() {
super.initialSetup()
self.selectionStyle = .none
let stackView = UIStackView(arrangedSubviews: [self.titleLabel, self.subtitleLabel])
stackView.axis = .vertical
self.contentView.add(stackView,
self.activeSwitch) { v in
v.translatesAutoresizingMaskIntoConstraints = false
}
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor,
constant: Const.margin),
stackView.topAnchor.constraint(equalTo: self.contentView.topAnchor,
constant: Const.verticalMargin),
stackView.trailingAnchor.constraint(equalTo: self.activeSwitch.leadingAnchor,
constant: -Const.margin),
stackView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor,
constant: -Const.verticalMargin),
self.activeSwitch.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor,
constant: -Const.margin),
self.activeSwitch.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor)
])
}
func update(viewModel: SwitchViewModel) {
self.titleLabel.text = viewModel.title
self.subtitleLabel.text = viewModel.subtitle
self.activeSwitch.isOn = !viewModel.hidden
}
// MARK: - Actions
@objc
private func hiddenChanges(hiddenSwitch: UISwitch) {
self.onStatusChange?(hiddenSwitch.isOn)
}
}
| mit | 7614ab04db483cc2ec4851996ef2757d | 33.240741 | 107 | 0.593023 | 5.017639 | false | false | false | false |
CryptoKitten/CryptoEssentials | Sources/Base64.swift | 1 | 6766 | // Base64.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 struct Base64 {
/**
Decodes the base64 encoded string into an array of UInt8 representing
bytes. Throws an Base64DecodingError.invalidCharacter if the input string
is not encoded in valid Base64.
- parameters:
- string: the string to decode
- returns: an array of bytes.
*/
public static func decode(_ string: String) throws -> [UInt8] {
let ascii: [UInt8] = [
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 62, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 63,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
]
var decoded = [UInt8]()
var unreadBytes = 0
for character in string.utf8 {
// If we don't get a valid Base64 Character (excluding =):
if ascii[Int(character)] > 63 {
// If it's '=', which is padding, we are done with the string!
if character == 61 {
break
}
// Otherwise this is not a valid Base64 encoded string
else {
throw Base64DecodingError.invalidCharacter
}
}
unreadBytes += 1
}
func byte(_ index: Int) -> Int {
return Int(Array(string.utf8)[index])
}
var index = 0
while unreadBytes > 4 {
decoded.append(ascii[byte(index + 0)] << 2 | ascii[byte(index + 1)] >> 4)
decoded.append(ascii[byte(index + 1)] << 4 | ascii[byte(index + 2)] >> 2)
decoded.append(ascii[byte(index + 2)] << 6 | ascii[byte(index + 3)])
index += 4
unreadBytes -= 4
}
if unreadBytes > 1 {
decoded.append(ascii[byte(index + 0)] << 2 | ascii[byte(index + 1)] >> 4)
}
if unreadBytes > 2 {
decoded.append(ascii[byte(index + 1)] << 4 | ascii[byte(index + 2)] >> 2)
}
if unreadBytes > 3 {
decoded.append(ascii[byte(index + 2)] << 6 | ascii[byte(index + 3)])
}
return decoded
}
public static func encode(_ data: [UInt8], specialChars: String = "+/", paddingChar: Character? = "=") -> String {
let base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + specialChars
var encoded: String = ""
func appendCharacterFromBase(_ character: Int) {
encoded.append(base64[base64.index(base64.startIndex, offsetBy: character)])
}
func byte(_ index: Int) -> Int {
return Int(data[index])
}
let decodedBytes = data.map { Int($0) }
var i = 0
while i < decodedBytes.count - 2 {
appendCharacterFromBase(( byte(i) >> 2) & 0x3F)
appendCharacterFromBase(((byte(i) & 0x3) << 4) | ((byte(i + 1) & 0xF0) >> 4))
appendCharacterFromBase(((byte(i + 1) & 0xF) << 2) | ((byte(i + 2) & 0xC0) >> 6))
appendCharacterFromBase( byte(i + 2) & 0x3F)
i += 3
}
if i < decodedBytes.count {
appendCharacterFromBase((byte(i) >> 2) & 0x3F)
if i == decodedBytes.count - 1 {
appendCharacterFromBase(((byte(i) & 0x3) << 4))
if let paddingChar = paddingChar {
encoded.append(paddingChar)
}
} else {
appendCharacterFromBase(((byte(i) & 0x3) << 4) | ((byte(i + 1) & 0xF0) >> 4))
appendCharacterFromBase(((byte(i + 1) & 0xF) << 2))
}
if let paddingChar = paddingChar {
encoded.append(paddingChar)
}
}
return encoded
}
public static func urlSafeEncode(_ data: [UInt8]) -> String {
return Base64.encode(data, specialChars: "-_", paddingChar: nil)
}
}
enum Base64DecodingError: Error {
case invalidCharacter
}
| mit | 82f31c1d5ff47055bb9bf2c6cfef850f | 42.095541 | 118 | 0.494531 | 3.936009 | false | false | false | false |
CraigZheng/KomicaViewer | KomicaViewer/KomicaViewer/Util/ProgressHUD.swift | 1 | 901 | //
// ProgressHUD.swift
// Exellency
//
// Created by Craig Zheng on 7/08/2016.
// Copyright © 2016 cz. All rights reserved.
//
import UIKit
import MBProgressHUD
class ProgressHUD: MBProgressHUD {
class func showMessage(_ message: String) {
DispatchQueue.main.async {
if let rootView = UIApplication.topViewController?.view {
let hud = MBProgressHUD.showAdded(to: rootView, animated:true)
// Set the annular determinate mode to show task progress.
hud?.mode = .text
hud?.detailsLabelText = message
hud?.isUserInteractionEnabled = false
// Move to bottm center.
hud?.xOffset = 0
hud?.yOffset = Float(UIScreen.main.bounds.height / 2 - 60)
hud?.hide(true, afterDelay: 2.0)
}
}
}
}
| mit | 91860358c9227bb4606a4c7f270890cd | 27.125 | 78 | 0.56 | 4.663212 | false | false | false | false |
AlexMcArdle/LooseFoot | LooseFoot/Systems/Utilities.swift | 1 | 4744 | //
// Utilities.swift
// LooseFoot
//
// Created by Alexander McArdle on 2/6/17.
// Copyright © 2017 Alexander McArdle. All rights reserved.
//
import UIKit
import Foundation
import AsyncDisplayKit
extension UIColor {
static func darkBlueColor() -> UIColor {
return UIColor(red: 18.0/255.0, green: 86.0/255.0, blue: 136.0/255.0, alpha: 1.0)
}
static func lightBlueColor() -> UIColor {
return UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0)
}
static func duskColor() -> UIColor {
return UIColor(red: 255/255.0, green: 181/255.0, blue: 68/255.0, alpha: 1.0)
}
static func customOrangeColor() -> UIColor {
return UIColor(red: 40/255.0, green: 43/255.0, blue: 53/255.0, alpha: 1.0)
}
}
extension Int {
func getFancyNumber() -> String? {
let number: Double = (Double(self) / 1000.0)
let numberFormater = NumberFormatter()
numberFormater.numberStyle = .decimal
numberFormater.maximumFractionDigits = 1
numberFormater.minimumFractionDigits = 1
let numberString = numberFormater.string(from: NSNumber(value: number))
return "\(numberString!)k"
}
}
extension UIView {
func makeRoundedView(size: CGSize?, borderWidth width: CGFloat, color: UIColor? = .white) -> UIView {
let rect = CGRect(origin: .zero, size: bounds.size)
let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 10, height: 10))
maskPath.addClip()
UIColor.flatWhite.set()
maskPath.fill()
self.draw(rect)
UIColor.flatWhite.set()
maskPath.stroke()
return self
}
}
extension UIImage {
func makeRoundedImage(size: CGSize, borderWidth width: CGFloat, color: UIColor? = .white) -> UIImage {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 10, height: 10))
maskPath.addClip()
UIColor.white.set()
maskPath.fill()
self.draw(in: rect)
if(width > 0) {
maskPath.lineWidth = width
color?.set()
maskPath.stroke()
}
let modifiedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return modifiedImage ?? self
}
func makeCircularImage(size: CGSize, borderWidth width: CGFloat, color: UIColor? = .white) -> UIImage {
// make a CGRect with the image's size
let circleRect = CGRect(origin: .zero, size: size)
// begin the image context since we're not in a drawRect:
UIGraphicsBeginImageContextWithOptions(circleRect.size, false, 0)
// create a UIBezierPath circle
let circle = UIBezierPath(roundedRect: circleRect, cornerRadius: circleRect.size.width * 0.5)
// clip to the circle
circle.addClip()
UIColor.white.set()
circle.fill()
// draw the image in the circleRect *AFTER* the context is clipped
self.draw(in: circleRect)
// create a border (for white background pictures)
if width > 0 {
circle.lineWidth = width;
color?.set()
circle.stroke()
}
// get an image from the image context
let roundedImage = UIGraphicsGetImageFromCurrentImageContext();
// end the image context since we're not in a drawRect:
UIGraphicsEndImageContext();
return roundedImage ?? self
}
}
extension String {
func checkForBrackets() -> String {
var mystring = String(self)!
let prefix = mystring.hasPrefix("[")
let suffix = mystring.hasSuffix("]")
if(prefix && suffix) {
mystring.remove(at: mystring.startIndex)
mystring.remove(at: mystring.index(before: mystring.endIndex))
return mystring
} else { return self }
}
}
extension NSAttributedString {
static func attributedString(string: String?, fontSize size: CGFloat, color: UIColor?) -> NSAttributedString? {
guard let string = string else { return nil }
let attributes = [NSForegroundColorAttributeName: color ?? UIColor.black,
NSFontAttributeName: AppFont(size: size, bold: true)]
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
return attributedString
}
}
| gpl-3.0 | 901622c6fce7bb34d74b94ff8beb26e4 | 31.047297 | 130 | 0.60953 | 4.631836 | false | false | false | false |
buyiyang/iosstar | iOSStar/Scenes/Discover/Controllers/BuyStarTimeViewController.swift | 3 | 6529 | //
// BuyStarTimeViewController.swift
// iOSStar
//
// Created by J-bb on 17/7/6.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import RealmSwift
class BuyStarTimeViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
lazy var backView: UIView = {
let view = UIView(frame: self.collectionView.frame)
let effect = UIBlurEffect(style: .light)
let effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: view.frame.size.height)
view.addSubview(effectView)
return view
}()
lazy var backImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "blank"))
imageView.frame = CGRect(x: 50, y: 50
, width: kScreenWidth - 100, height: kScreenHeight - 240)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
var dataSouce:[StarSortListModel]?
override func viewDidLoad() {
super.viewDidLoad()
backView.addSubview(backImageView)
backView.sendSubview(toBack: backImageView)
collectionView.backgroundView = backView
collectionView.register(StarCardView.self, forCellWithReuseIdentifier: StarCardView.className())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let _ = UserDefaults.standard.value(forKey: AppConst.guideKey.feedBack.rawValue) as? String {
}else{
showGuideVC(.feedBack, handle: { (vc)in
if let guideVC = vc as? GuideVC{
if guideVC.guideType == AppConst.guideKey.feedBack{
guideVC.setGuideContent(.leftRight)
return
}
guideVC.dismiss(animated: true, completion: nil)
UserDefaults.standard.set("ok", forKey: AppConst.guideKey.feedBack.rawValue)
}
})
}
requestStarList()
}
func requestConfigData() {
// AppAPIHelper.user().configRequest(param_code: "HOME_LAST_PIC", complete: { (response) in
// if let model = response as? ConfigReusltValue {
// let starModel = StarSortListModel()
// starModel.home_pic_tail = model.param_value
// starModel.pushlish_type = 4
// if self.dataSouce != nil {
// self.dataSouce?.append(starModel)
// self.collectionView.reloadData()
// }
// self.collectionView.reloadData()
// }
//
// }) { (error) in
//
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func requestStarList() {
let requestModel = StarSortListRequestModel()
AppAPIHelper.discoverAPI().requestScrollStarList(requestModel: requestModel, complete: { (response) in
if let model = response as? DiscoverListModel{
self.dataSouce = model.symbol_info
let starModel = StarSortListModel()
starModel.home_pic_tail = model.home_last_pic_tail
starModel.pushlish_type = -1
self.dataSouce?.append(starModel)
self.collectionView.reloadData()
self.perform(#selector(self.replaceBackImage(index:)), with: nil, afterDelay: 0.5)
}
}) { (error) in
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = sender as? IndexPath {
let model = dataSouce![indexPath.item]
let vc = segue.destination
if segue.identifier == "ToSelling" {
if let sellingVC = vc as? SellingViewController {
sellingVC.starModel = model
}
} else {
if let introVC = vc as? StarIntroduceViewController {
introVC.starModel = model
}
}
}
}
}
extension BuyStarTimeViewController:UICollectionViewDataSource, UICollectionViewDelegate {
func replaceBackImage(index:Int = 0) {
let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? StarCardView
backImageView.image = cell?.backImage
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x - 6) / Int(kScreenWidth - 88)
replaceBackImage(index: index)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSouce?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StarCardView.className(), for: indexPath)
if let card = cell as? StarCardView {
card.setStarModel(starModel: dataSouce![indexPath.row])
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if checkLogin(){
let starModel = dataSouce![indexPath.row]
// var segueString = "ToSelling"
var segueString = "StarNewsVC"
switch starModel.pushlish_type {
case 0:
segueString = "ToSelling"
case 1:
segueString = "ToSelling"
// segueString = "ToIntroduce"
case 2:
if let dealVC = UIStoryboard.init(name: "Heat", bundle: nil).instantiateViewController(withIdentifier: HeatDetailViewController.className()) as? HeatDetailViewController{
let model = dataSouce?[indexPath.row]
dealVC.starListModel = model
_ = navigationController?.pushViewController(dealVC, animated: true)
return
}
default:
ShareDataModel.share().selectStarCode = ""
segueString = StarNewsVC.className()
break
}
performSegue(withIdentifier: segueString, sender: indexPath)
}
}
}
| gpl-3.0 | bf6764da58363d27dbbe92784ca7f709 | 35.662921 | 186 | 0.583665 | 5.039382 | false | false | false | false |
Zerounodue/splinxsChat | splinxsChat/AppDelegate.swift | 1 | 6225 | //
// AppDelegate.swift
// splinxsChat
//
// Created by Elia Kocher on 17.05.16.
// Copyright © 2016 BFH. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
socketIOcontroller.sharedInstance.closeConnection()
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
socketIOcontroller.sharedInstance.establishConnection()
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
self.saveContext()
socketIOcontroller.sharedInstance.closeConnection()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "ch.bfh.dasdasdas" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("chatDataMode", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("splinxsChat.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 6e78f3dc22d9f8519f1c23f7792e8d78 | 51.302521 | 291 | 0.712886 | 5.899526 | false | false | false | false |
nbkey/DouYuTV | DouYu/DouYu/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 1336 | //
// UIBarButtonItem-Extension.swift
// DouYu
//
// Created by 吉冠坤 on 2017/7/21.
// Copyright © 2017年 吉冠坤. All rights reserved.
//
import Foundation
import UIKit
//对系统类做扩展
extension UIBarButtonItem {
/*
class func creatItem (imaged:String, highImageNamed: String, size: CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named:imaged), for: .normal)
btn.setImage(UIImage(named:highImageNamed), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
//扩充构造函数(便利构造函数)
//1>convenience开头
//2>在构造函数中必须明确的调用一个设计的构造函数(self), 赋初始化的值可以被选择
convenience init(imaged:String, highImageNamed: String = "", size: CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named:imaged), for: .normal)
if highImageNamed != "" {
btn.setImage(UIImage(named:highImageNamed), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView: btn)
}
}
| mit | 9c7436686dabc05792e316e4e4c2a7fe | 27.209302 | 99 | 0.610058 | 3.814465 | false | false | false | false |
vgorloff/AUHost | Sources/Common/ControlIcon.swift | 1 | 683 | //
// ControlIcon.swift
// Attenuator
//
// Created by Vlad Gorlov on 14.10.18.
// Copyright © 2018 WaveLabs. All rights reserved.
//
import Foundation
import AppKit
enum ControlIcon {
case library, play, pause, effect, reload
var image: NSImage {
let name: String
switch self {
case .library:
name = "Control-Library"
case .play:
name = "Control-Play"
case .pause:
name = "Control-Pause"
case .effect:
name = "Control-Effect"
case .reload:
name = "Control-Reload"
}
guard let image = NSImage(named: name) else {
fatalError()
}
return image
}
}
| mit | 3ada053dcbe2ae3f1dd02acb793c7a38 | 18.485714 | 51 | 0.570381 | 3.853107 | false | false | false | false |
rushabh55/NaviTag-iOS | iOS/SwiftExample/TableViewController.swift | 1 | 3186 |
import UIKit
class TableViewController: UITableViewController {
var tableArray:NSMutableArray = ["Siddesh joined the Game", "Rushabh found the hint at Crossroads", "Rushabh dropped a hint", "Tresure still unclaimed", "15 active players in the hunt"]
override init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Ongoing Game"
}
override func viewDidAppear(animated: Bool)
{
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//#pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return tableArray.count;
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true;
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if(editingStyle == UITableViewCellEditingStyle.Delete)
{
tableArray.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = tableArray.objectAtIndex(indexPath.row) as NSString
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.textColor = UIColor.greenColor()
cell.textLabel?.font = UIFont.systemFontOfSize(15)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.showAlert(tableArray.objectAtIndex(indexPath.row) as NSString, rowToUseInAlert: indexPath.row)
}
//#pragma mark - UIAlertView delegate methods
func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {
NSLog("Did dismiss button: %d", buttonIndex)
}
// Function to init a UIAlertView and show it
func showAlert(rowTitle:NSString, rowToUseInAlert: Int) {
var alert = UIAlertView()
alert.delegate = self
alert.title = rowTitle
// alert.message = "You selected row \(rowToUseInAlert)"
alert.addButtonWithTitle("OK")
alert.show()
}
}
| apache-2.0 | aaab994195b85d5a3029fe289503bbd2 | 33.258065 | 189 | 0.663842 | 5.455479 | false | false | false | false |
yokoe/tabata | Tabata/Classes/GaussianBlurOperation.swift | 1 | 1300 | import Cocoa
import CoreImage
class GaussianBlurOperation {
var radius: Float
init(radius: Float) {
self.radius = radius
}
}
extension GaussianBlurOperation: ImageProcessOperation {
func process(_ image: CIImage) -> CIImage {
guard let blurFilter = CIFilter(name: "CIGaussianBlur") else {
print("Failed to instantiate filter")
return image
}
blurFilter.setValue(image, forKey: "inputImage")
blurFilter.setValue(radius, forKey: "inputRadius")
guard let blurImage = blurFilter.outputImage else {
print("Filter ouput error.")
return image
}
guard let cropFilter = CIFilter(name: "CICrop") else {
print("Failed to instantiate crop filter")
return image
}
let sourceImageExtent = image.extent
cropFilter.setValue(blurImage, forKey: "inputImage")
cropFilter.setValue(CIVector(x: 0, y: 0, z: sourceImageExtent.size.width, w: sourceImageExtent.size.height), forKey: "inputRectangle")
guard let outputImage = cropFilter.outputImage else {
print("Crop filter output error.")
return image
}
return outputImage
}
}
| mit | 650f54241cac850553a51c7f1e6772df | 29.232558 | 142 | 0.602308 | 4.942966 | false | false | false | false |
cozkurt/coframework | COFramework/COFramework/Swift/Extentions/UIView+Border.swift | 1 | 2194 | //
// UIView+Border.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import UIKit
extension UIView {
public func addBorderTop(_ size: CGFloat, color: UIColor) {
addBorder(0, y: 0, width: frame.width, height: size, color: color)
}
public func addBorderBottom(_ size: CGFloat, color: UIColor) {
addBorder(0, y: frame.height - size, width: frame.width, height: size, color: color)
}
public func addBorderLeft(_ size: CGFloat, color: UIColor) {
addBorder(0, y: 0, width: size, height: frame.height, color: color)
}
public func addBorderRight(_ size: CGFloat, color: UIColor) {
addBorder(frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
fileprivate func addBorder(_ x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
public func addDashedLine(_ y: CGFloat, color: UIColor = UIColor.black) {
let shapeLayer = CAShapeLayer()
shapeLayer.bounds = self.bounds
shapeLayer.position = CGPoint(x: frame.width / 2, y: y)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = 1
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineDashPattern = [2, 2] // lenght, gap
let path: CGMutablePath = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
shapeLayer.path = path
layer.addSublayer(shapeLayer)
}
public func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.2
layer.shadowOffset = .zero
layer.shadowRadius = 1
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
| gpl-3.0 | 25477612f2a9eaf2716f93e43220d885 | 33.265625 | 107 | 0.632467 | 4.129944 | false | false | false | false |
ahoppen/swift | test/Constraints/argument_matching.swift | 6 | 78435 | // RUN: %target-typecheck-verify-swift
// Single extraneous keyword argument (tuple-to-scalar)
func f1(_ a: Int) { }
f1(a: 5) // expected-error{{extraneous argument label 'a:' in call}}{{4-7=}}
struct X1 {
init(_ a: Int) { }
func f1(_ a: Int) {}
}
X1(a: 5).f1(b: 5)
// expected-error@-1 {{extraneous argument label 'a:' in call}} {{4-7=}}
// expected-error@-2 {{extraneous argument label 'b:' in call}} {{13-16=}}
// <rdar://problem/16801056>
enum Policy {
case Head(Int)
}
func extra2(x: Int, y: Int) { }
func testExtra2(_ policy : Policy) {
switch (policy)
{
case .Head(let count):
extra2(x: 0, y: count)
}
}
// Single missing keyword argument (scalar-to-tuple)
func f2(a: Int) { }
f2(5) // expected-error{{missing argument label 'a:' in call}}{{4-4=a: }}
struct X2 {
init(a: Int) { }
func f2(b: Int) { }
}
X2(5).f2(5)
// expected-error@-1 {{missing argument label 'a:' in call}} {{4-4=a: }}
// expected-error@-2 {{missing argument label 'b:' in call}} {{10-10=b: }}
// -------------------------------------------
// Missing keywords
// -------------------------------------------
func allkeywords1(x: Int, y: Int) { }
// Missing keywords.
allkeywords1(1, 2) // expected-error{{missing argument labels}} {{14-14=x: }} {{17-17=y: }}
allkeywords1(x: 1, 2) // expected-error{{missing argument label 'y:' in call}} {{20-20=y: }}
allkeywords1(1, y: 2) // expected-error{{missing argument label 'x:' in call}} {{14-14=x: }}
// If keyword is reserved, make sure to quote it. rdar://problem/21392294
func reservedLabel(_ x: Int, `repeat`: Bool) {}
reservedLabel(1, true) // expected-error{{missing argument label 'repeat:' in call}}{{18-18=repeat: }}
// Insert missing keyword before initial backtick. rdar://problem/21392294 part 2
func reservedExpr(_ x: Int, y: Int) {}
let `do` = 2
reservedExpr(1, `do`) // expected-error{{missing argument label 'y:' in call}}{{17-17=y: }}
reservedExpr(1, y: `do`)
class GenericCtor<U> {
init<T>(t : T) {} // expected-note {{'init(t:)' declared here}}
}
GenericCtor<Int>() // expected-error{{missing argument for parameter 't' in call}}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
// -------------------------------------------
// Extraneous keywords
// -------------------------------------------
func nokeywords1(_ x: Int, _ y: Int) { }
nokeywords1(x: 1, y: 1) // expected-error{{extraneous argument labels 'x:y:' in call}}{{13-16=}}{{19-22=}}
// -------------------------------------------
// Some missing, some extraneous keywords
// -------------------------------------------
func somekeywords1(_ x: Int, y: Int, z: Int) { }
somekeywords1(x: 1, y: 2, z: 3) // expected-error{{extraneous argument label 'x:' in call}}{{15-18=}}
somekeywords1(1, 2, 3) // expected-error{{missing argument labels 'y:z:' in call}}{{18-18=y: }}{{21-21=z: }}
somekeywords1(x: 1, 2, z: 3) // expected-error{{incorrect argument labels in call (have 'x:_:z:', expected '_:y:z:')}}{{15-18=}}{{21-21=y: }}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// -------------------------------------------
// Out-of-order keywords
// -------------------------------------------
allkeywords1(y: 1, x: 2) // expected-error{{argument 'x' must precede argument 'y'}} {{14-14=x: 2, }} {{18-24=}}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
struct ReorderAndAllLabels {
func f(aa: Int, bb: Int, cc: Int, dd: Int) {}
func test() {
f(bb: 1, ccx: 2, ddx: 3, aa: 0) // expected-error {{argument 'aa' must precede argument 'bb'}} {{28-35=}} {{7-7=aa: 0, }} {{none}}
f(bbx: 1, ccx: 2, ddx: 3, aa: 0) // expected-error {{incorrect argument labels in call (have 'bbx:ccx:ddx:aa:', expected 'aa:bb:cc:dd:')}} {{7-10=aa}} {{15-18=bb}} {{23-26=cc}} {{31-33=dd}} {{none}}
}
}
// -------------------------------------------
// Default arguments
// -------------------------------------------
func defargs1(x: Int = 1, y: Int = 2, z: Int = 3) {}
// Using defaults (in-order)
defargs1()
defargs1(x: 1)
defargs1(x: 1, y: 2)
// Using defaults (in-order, some missing)
defargs1(y: 2)
defargs1(y: 2, z: 3)
defargs1(z: 3)
defargs1(x: 1, z: 3)
// Using defaults (out-of-order, error by SE-0060)
defargs1(z: 3, y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{10-10=x: 1, }} {{20-26=}}
defargs1(x: 1, z: 3, y: 2) // expected-error{{argument 'y' must precede argument 'z'}} {{16-16=y: 2, }} {{20-26=}}
defargs1(y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'y'}} {{10-10=x: 1, }} {{14-20=}}
// Default arguments "boxed in".
func defargs2(first: Int, x: Int = 1, y: Int = 2, z: Int = 3, last: Int) { }
// Using defaults in the middle (in-order, some missing)
defargs2(first: 1, x: 1, z: 3, last: 4)
defargs2(first: 1, x: 1, last: 4)
defargs2(first: 1, y: 2, z: 3, last: 4)
defargs2(first: 1, last: 4)
// Using defaults in the middle (out-of-order, error by SE-0060)
defargs2(first: 1, z: 3, x: 1, last: 4) // expected-error{{argument 'x' must precede argument 'z'}} {{20-20=x: 1, }} {{24-30=}}
defargs2(first: 1, z: 3, y: 2, last: 4) // expected-error{{argument 'y' must precede argument 'z'}} {{20-20=y: 2, }} {{24-30=}}
// Using defaults that have moved past a non-defaulted parameter
defargs2(x: 1, first: 1, last: 4) // expected-error{{argument 'first' must precede argument 'x'}} {{10-10=first: 1, }} {{14-24=}}
defargs2(first: 1, last: 4, x: 1) // expected-error{{argument 'x' must precede argument 'last'}} {{20-20=x: 1, }} {{27-33=}}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
func testLabelErrorDefault() {
func f(aa: Int, bb: Int, cc: Int = 0) {}
f(aax: 0, bbx: 1, cc: 2)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:cc:', expected 'aa:bb:cc:')}}
f(aax: 0, bbx: 1)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}}
}
// -------------------------------------------
// Variadics
// -------------------------------------------
func variadics1(x: Int, y: Int, _ z: Int...) { }
// Using variadics (in-order, complete)
variadics1(x: 1, y: 2)
variadics1(x: 1, y: 2, 1)
variadics1(x: 1, y: 2, 1, 2)
variadics1(x: 1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics1(1, 2, 3, 4, 5, x: 6, y: 7) // expected-error {{incorrect argument labels in call (have '_:_:_:_:_:x:y:', expected 'x:y:_:')}} {{12-12=x: }} {{15-15=y: }} {{27-30=}} {{33-36=}}
func variadics2(x: Int, y: Int = 2, z: Int...) { } // expected-note {{'variadics2(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics2(x: 1, y: 2, z: 1)
variadics2(x: 1, y: 2, z: 1, 2)
variadics2(x: 1, y: 2, z: 1, 2, 3)
// Using variadics (in-order, some missing)
variadics2(x: 1, z: 1, 2, 3)
variadics2(x: 1)
// Using variadics (out-of-order)
variadics2(z: 1, 2, 3, y: 2) // expected-error{{missing argument for parameter 'x' in call}}
variadics2(z: 1, 2, 3, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{22-28=}}
func variadics3(_ x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics3(1, 2, 3, y: 0, z: 1)
variadics3(1, y: 0, z: 1)
variadics3(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics3(1, 2, 3, y: 0)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3, z: 1)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3)
variadics3(1)
variadics3()
// Using variadics (out-of-order)
variadics3(y: 0, 1, 2, 3) // expected-error{{unnamed argument #2 must precede argument 'y'}} {{12-12=1, 2, 3, }} {{16-25=}}
variadics3(z: 1, 1) // expected-error{{unnamed argument #2 must precede argument 'z'}} {{12-12=1, }} {{16-19=}}
func variadics4(x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics4(x: 1, 2, 3, y: 0, z: 1)
variadics4(x: 1, y: 0, z: 1)
variadics4(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics4(x: 1, 2, 3, y: 0)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3, z: 1)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3)
variadics4(x: 1)
variadics4()
// Using variadics (in-order, some missing)
variadics4(y: 0, x: 1, 2, 3) // expected-error{{argument 'x' must precede argument 'y'}} {{12-12=x: 1, 2, 3, }} {{16-28=}}
variadics4(z: 1, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{16-22=}}
func variadics5(_ x: Int, y: Int, _ z: Int...) { } // expected-note {{declared here}}
// Using variadics (in-order, complete)
variadics5(1, y: 2)
variadics5(1, y: 2, 1)
variadics5(1, y: 2, 1, 2)
variadics5(1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics5(1, 2, 3, 4, 5, 6, y: 7) // expected-error{{argument 'y' must precede unnamed argument #2}} {{15-15=y: 7, }} {{28-34=}}
variadics5(y: 1, 2, 3, 4, 5, 6, 7) // expected-error{{missing argument for parameter #1 in call}}
func variadics6(x: Int..., y: Int = 2, z: Int) { } // expected-note 4 {{'variadics6(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics6(x: 1, 2, 3, y: 0, z: 1)
variadics6(x: 1, y: 0, z: 1)
variadics6(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics6(x: 1, 2, 3, y: 0) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3, z: 1)
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1) // expected-error{{missing argument for parameter 'z' in call}}
variadics6() // expected-error{{missing argument for parameter 'z' in call}}
func variadics7(_ x: Int..., y: Int...) { }
// Using multiple variadics (in order, complete)
variadics7(1, y: 2)
variadics7(1, 2, 3, y: 4, 5, 6)
variadics7(1, 2, y: 2)
variadics7(1, y: 2, 1)
// multiple variadics, in order, some missing
variadics7(y: 1)
variadics7(1)
variadics7(y: 4, 5, 6)
variadics7(1, 2, 3)
func variadics8(x: Int..., y: Int...) { }
// multiple variadics, out of order
variadics8(y: 1, x: 2) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 2, }} {{16-22=}}
variadics8(y: 1, 2, 3, x: 4) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 4, }} {{22-28=}}
variadics8(y: 1, x: 2, 3, 4) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 2, 3, 4, }} {{16-28=}}
variadics8(y: 1, 2, 3, x: 4, 5, 6) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 4, 5, 6, }} {{22-34=}}
func variadics9(_ a: Int..., b: Int, _ c: Int...) { } // expected-note {{'variadics9(_:b:_:)' declared here}}
// multiple split variadics, in order, complete
variadics9(1, b: 2, 3)
variadics9(1, 2, 3, b: 2, 3)
variadics9(1, b: 2, 3, 2, 1)
variadics9(1, 2, 3, b: 2, 3, 2, 1)
// multiple split variadics, in order, some missing
variadics9(b: 2, 3)
variadics9(1, b: 2)
variadics9(1, 2, b: 2)
variadics9(b: 2, 3, 2, 1)
// multiple split variadics, required missing
variadics9(1) // expected-error {{missing argument for parameter 'b' in call}}
func variadics10(_ a: Int..., b: Int = 2, _ c: Int...) { }
// multiple unlabeled variadics split by defaulted param, in order, complete
variadics10(1, b: 2, 3)
variadics10(1, 2, 3, b: 2, 3)
variadics10(1, b: 2, 3, 2, 1)
variadics10(1, 2, 3, b: 2, 3, 2, 1)
// multiple unlabeled variadics split by defaulted param, in order, some missing
variadics10(1, 2, 3)
variadics10(1, 2, 3, b: 3)
variadics10(b: 3)
func variadics11(_ a: Int..., b: Bool = false, _ c: String...) { }
variadics11(1, 2, 3, b: true, "hello", "world")
variadics11(b: true, "hello", "world")
variadics11(1, 2, 3, b: true)
variadics11(b: true)
variadics11()
variadics11(1, 2, 3, "hello", "world") // expected-error 2 {{cannot convert value of type 'String' to expected argument type 'Int'}}
func variadics12(a: Int..., b: Int, c: Int...) { }
variadics12(a: 1, 2, 3, b: 4, c: 5, 6, 7)
variadics12(b: 4, c: 5, 6, 7)
variadics12(a: 1, 2, 3, b: 4)
variadics12(c: 5, 6, 7, b: 4, a: 1, 2, 3) // expected-error {{incorrect argument labels in call (have 'c:_:_:b:a:_:_:', expected 'a:b:c:')}} {{13-14=a}} {{19-19=b: }} {{22-22=c: }} {{25-28=}} {{31-34=}}
// Edge cases involving multiple trailing closures and forward matching.
func variadics13(a: Int..., b: (()->Void)...) {}
variadics13()
variadics13(a: 1, 2, 3) {} _: {} _: {}
variadics13() {} _: {} _: {}
variadics13(a: 1, 2, 3)
variadics13(a: 1, 2, 3) {}
func variadics14(a: (()->Void)..., b: (()->Void)...) {} // expected-note {{'variadics14(a:b:)' declared here}}
variadics14(a: {}, {}, b: {}, {})
variadics14(a: {}, {}) {} _: {}
variadics14 {} _: {} b: {} _: {}
variadics14 {} b: {}
variadics14 {} // expected-warning {{backward matching of the unlabeled trailing closure is deprecated; label the argument with 'b' to suppress this warning}}
func outOfOrder(_ a : Int, b: Int) {
outOfOrder(b: 42, 52) // expected-error {{unnamed argument #2 must precede argument 'b'}} {{14-14=52, }} {{19-23=}}
}
struct Variadics7 {
func f(alpha: Int..., bravo: Int) {} // expected-note {{'f(alpha:bravo:)' declared here}}
// expected-note@-1 {{'f(alpha:bravo:)' declared here}}
func test() {
// no error
f(bravo: 0)
f(alpha: 0, bravo: 3)
f(alpha: 0, 1, bravo: 3)
f(alpha: 0, 1, 2, bravo: 3)
// OoO
f(bravo: 0, alpha: 1) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// typo A
f(alphax: 0, bravo: 3) // expected-error {{incorrect argument label in call (have 'alphax:bravo:', expected 'alpha:bravo:')}}
f(alphax: 0, 1, bravo: 3) // expected-error {{extra argument in call}}
f(alphax: 0, 1, 2, bravo: 3) // expected-error {{extra arguments at positions #2, #3 in call}}
// typo B
f(bravox: 0) // expected-error {{incorrect argument label in call (have 'bravox:', expected 'bravo:')}}
f(alpha: 0, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:bravox:', expected 'alpha:bravo:')}}
f(alpha: 0, 1, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:_:bravox:', expected 'alpha:_:bravo:')}}
f(alpha: 0, 1, 2, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravox:', expected 'alpha:_:_:bravo:')}}
// OoO + typo A B
f(bravox: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alphax:', expected 'alpha:bravo:')}}
f(bravox: 0, alphax: 1, 2) // expected-error {{extra argument in call}}
f(bravox: 0, alphax: 1, 2, 3) // expected-error {{extra arguments at positions #3, #4 in call}}
}
}
struct Variadics8 {
func f(alpha: Int..., bravo: Int, charlie: Int) {} // expected-note {{'f(alpha:bravo:charlie:)' declared here}}
func test() {
// no error
f(bravo: 3, charlie: 4)
f(alpha: 0, bravo: 3, charlie: 4)
f(alpha: 0, 1, bravo: 3, charlie: 4)
f(alpha: 0, 1, 2, bravo: 3, charlie: 4)
// OoO ACB
f(charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, 1, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, 1, 2, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
// OoO CAB
f(charlie: 0, alpha: 1, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f(charlie: 0, alpha: 1, 2, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:_:bravo:', expected 'alpha:bravo:charlie:')}}
f(charlie: 0, alpha: 1, 2, 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:_:_:bravo:', expected 'alpha:bravo:charlie:')}}
// OoO BAC
f(bravo: 0, alpha: 1, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// typo A
f(alphax: 0, bravo: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alphax:bravo:charlie:', expected 'alpha:bravo:charlie:')}}
f(alphax: 0, 1, bravo: 3, charlie: 4) // expected-error {{extra argument in call}}
f(alphax: 0, 1, 2, bravo: 3, charlie: 4) // expected-error {{extra arguments at positions #2, #3 in call}}
// typo B
f(bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'bravox:charlie:', expected 'bravo:charlie:')}}
f(alpha: 0, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:bravox:charlie:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:bravox:charlie:', expected 'alpha:_:bravo:charlie:')}}
f(alpha: 0, 1, 2, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravox:charlie:', expected 'alpha:_:_:bravo:charlie:')}}
// typo C
f(bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'bravo:charliex:', expected 'bravo:charlie:')}}
f(alpha: 0, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:bravo:charliex:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:bravo:charliex:', expected 'alpha:_:bravo:charlie:')}}
f(alpha: 0, 1, 2, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravo:charliex:', expected 'alpha:_:_:bravo:charlie:')}}
// OoO ACB + typo B
f(alpha: 0, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, 2, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:_:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
// OoO ACB + typo C
f(charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, 2, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:_:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
// OoO BAC + typo B
f(bravox: 0, alpha: 1, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f(bravox: 0, alpha: 1, 2, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:_:charlie:', expected 'alpha:bravo:charlie:')}}
f(bravox: 0, alpha: 1, 2, 3, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:_:_:charlie:', expected 'alpha:bravo:charlie:')}}
// OoO BAC + typo C
f(bravo: 0, alpha: 1, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
}
}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func testLabelErrorVariadic() {
func f(aa: Int, bb: Int, cc: Int...) {}
f(aax: 0, bbx: 1, cc: 2, 3, 4)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:cc:_:_:', expected 'aa:bb:cc:_:_:')}}
f(aax: 0, bbx: 1)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}}
}
// -------------------------------------------
// Positions around defaults and variadics
// -------------------------------------------
struct PositionsAroundDefaultsAndVariadics {
// unlabeled defaulted around labeled parameter
func f1(_ a: Bool = false, _ b: Int = 0, c: String = "", _ d: [Int] = []) {}
func test_f1() {
f1(true, 2, c: "3", [4])
f1(true, c: "3", 2, [4]) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f1(true, c: "3", [4], 2) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f1(true, c: "3", 2) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f1(true, c: "3", [4])
f1(c: "3", 2, [4]) // expected-error {{unnamed argument #3 must precede argument 'c'}}
f1(c: "3", [4], 2) // expected-error {{unnamed argument #3 must precede argument 'c'}}
f1(c: "3", 2) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f1(c: "3", [4])
f1(b: "2", [3]) // expected-error {{incorrect argument labels in call (have 'b:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f1(b: "2", 1) // expected-error {{incorrect argument labels in call (have 'b:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f1(b: "2", [3], 1) // expected-error {{incorrect argument labels in call (have 'b:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f1(b: "2", 1, [3]) // expected-error {{incorrect argument labels in call (have 'b:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-2 {{cannot convert value of type '[Int]' to expected argument type 'Int'}}
}
// unlabeled variadics before labeled parameter
func f2(_ a: Bool = false, _ b: Int..., c: String = "", _ d: [Int] = []) {}
func test_f2() {
f2(true, 21, 22, 23, c: "3", [4])
f2(true, "21", 22, 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, "22", 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, 22, "23", c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, 22, c: "3", [4])
f2(true, 21, c: "3", [4])
f2(true, c: "3", [4])
f2(true, c: "3", 21) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f2(true, c: "3", 21, [4]) // expected-error {{unnamed argument #4 must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f2(true, c: "3", [4], 21) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f2(true, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(true, 21, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(true, 21, 22, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(21, 22, 23, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(21, 22, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(21, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(c: "3", [4])
f2(c: "3")
f2()
f2(c: "3", 21) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f2(c: "3", 21, [4]) // expected-error {{incorrect argument labels in call (have 'c:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
// expected-error@-2 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f2(c: "3", [4], 21) // expected-error {{incorrect argument labels in call (have 'c:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2([4]) // expected-error {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f2(21, [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f2(21, 22, [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
}
// labeled variadics before labeled parameter
func f3(_ a: Bool = false, b: Int..., c: String = "", _ d: [Int] = []) {}
func test_f3() {
f3(true, b: 21, 22, 23, c: "3", [4])
f3(true, b: "21", 22, 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, "22", 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, 22, "23", c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, 22, c: "3", [4])
f3(true, b: 21, c: "3", [4])
f3(true, c: "3", [4])
f3(true, c: "3", b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(true, c: "3", b: 21, [4]) // expected-error {{argument 'b' must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f3(true, c: "3", [4], b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(true, b: 21, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f3(b: 21, 22, 23, c: "3", [4])
f3(b: 21, 22, c: "3", [4])
f3(b: 21, c: "3", [4])
f3(c: "3", [4])
f3([4]) // expected-error {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f3()
f3(c: "3", b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(c: "3", b: 21, [4]) // expected-error {{argument 'b' must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f3(c: "3", [4], b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
}
// unlabeled variadics after labeled parameter
func f4(_ a: Bool = false, b: String = "", _ c: Int..., d: [Int] = []) {}
func test_f4() {
f4(true, b: "2", 31, 32, 33, d: [4])
f4(true, b: "2", "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, 32, d: [4])
f4(true, b: "2", 31, d: [4])
f4(true, b: "2", d: [4])
f4(true, 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede unnamed argument #2}}
f4(true, b: "2", d: [4], 31) // expected-error {{unnamed argument #4 must precede argument 'd'}}
f4(true, b: "2", 31)
f4(true, b: "2")
f4(true)
f4(true, 31)
f4(true, 31, d: [4])
f4(true, 31, 32)
f4(true, 31, 32, d: [4])
f4(b: "2", 31, 32, 33, d: [4])
f4(b: "2", "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, 32, d: [4])
f4(b: "2", 31, d: [4])
f4(b: "2", d: [4])
f4(31, b: "2", d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(b: "2", d: [4], 31) // expected-error {{unnamed argument #3 must precede argument 'b'}}
f4(b: "2", 31)
f4(b: "2", 31, 32)
f4(b: "2")
f4()
f4(31) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, 32) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, 32, d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
}
// labeled variadics after labeled parameter
func f5(_ a: Bool = false, b: String = "", c: Int..., d: [Int] = []) {}
func test_f5() {
f5(true, b: "2", c: 31, 32, 33, d: [4])
f5(true, b: "2", c: "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, 32, d: [4])
f5(true, b: "2", c: 31, d: [4])
f5(true, b: "2", d: [4])
f5(true, c: 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede argument 'c'}}
f5(true, b: "2", d: [4], 31) // expected-error {{incorrect argument labels in call (have '_:b:d:_:', expected '_:b:c:d:')}}
f5(true, b: "2", c: 31)
f5(true, b: "2")
f5(true)
f5(true, c: 31)
f5(true, c: 31, d: [4])
f5(true, c: 31, 32)
f5(true, c: 31, 32, d: [4])
f5(b: "2", c: 31, 32, 33, d: [4])
f5(b: "2", c: "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, 32, d: [4])
f5(b: "2", c: 31, d: [4])
f5(b: "2", d: [4])
f5(c: 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede argument 'c'}}
f5(b: "2", d: [4], c: 31) // expected-error {{argument 'c' must precede argument 'd'}}
f5(b: "2", c: 31)
f5(b: "2", c: 31, 32)
f5(b: "2")
f5()
f5(c: 31)
f5(c: 31, d: [4])
f5(c: 31, 32)
f5(c: 31, 32, d: [4])
}
}
// -------------------------------------------
// Matching position of unlabeled parameters
// -------------------------------------------
func testUnlabeledParameterBindingPosition() {
do {
func f(_ aa: Int) {}
f(1) // ok
f(xx: 1)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(0, 1)
// expected-error@-1:10 {{extra argument in call}}
f(xx: 1, 2)
// expected-error@-1:14 {{extra argument in call}}
f(1, xx: 2)
// expected-error@-1:14 {{extra argument 'xx' in call}}
f(xx: 1, yy: 2)
// expected-error@-1:18 {{extra argument 'yy' in call}}
}
do {
func f(aa: Int) { }
f(1)
// expected-error@-1:7 {{missing argument label 'aa:' in call}}
f(aa: 1) // ok
f(xx: 1)
// expected-error@-1 {{incorrect argument label in call (have 'xx:', expected 'aa:')}}
}
do {
func f(_ aa: Int, _ bb: Int) { }
// expected-note@-1 3 {{'f' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter #2 in call}}
f(xx: 1)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:12 {{missing argument for parameter #2 in call}}
f(1, 2) // ok
f(1, xx: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(xx: 1, 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(xx: 1, yy: 2)
// expected-error@-1 {{extraneous argument labels 'xx:yy:' in call}}
f(xx: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
f(xx: 1, yy: 2, 3)
// expected-error@-1:21 {{extra argument in call}}
f(xx: 1, yy: 2, 3, 4)
// expected-error@-1:6 {{extra arguments at positions #3, #4 in call}}
}
do {
func f(_ aa: Int = 0, _ bb: Int) { }
// expected-note@-1 {{'f' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter #2 in call}}
f(1, 2) // ok
}
do {
func f(_ aa: Int, bb: Int) { }
// expected-note@-1 3 {{'f(_:bb:)' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
f(1, 2)
// expected-error@-1 {{missing argument label 'bb:' in call}}
f(1, bb: 2) // ok
f(xx: 1, 2)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:', expected '_:bb:')}}
f(xx: 1, bb: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(bb: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, bb: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, 2, bb: 3)
// expected-error@-1:10 {{extra argument in call}}
f(xx: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
}
do {
// expected-note@+1 *{{'f(aa:_:)' declared here}}
func f(aa: Int, _ bb: Int) { }
f(1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(0, 1)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(0, xx: 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:14 {{extra argument 'xx' in call}}
f(xx: 0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:14 {{extra argument in call}}
f(0, 1, 9)
// expected-error@-1:13 {{extra argument in call}}
f(0, 1, xx: 9)
// expected-error@-1:17 {{extra argument 'xx' in call}}
f(xx: 91, 1, 92)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:7 {{missing argument for parameter 'aa' in call}}
f(1, xx: 2, 3)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:7 {{missing argument for parameter 'aa' in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
}
do {
func f(_ aa: Int, _ bb: Int = 82, _ cc: Int) { }
// expected-note@-1 {{'f' declared here}}
f(1, 2)
// expected-error@-1:11 {{missing argument for parameter #3 in call}}
f(1, 2, 3) // ok
}
do {
func f(_ aa: Int, _ bb: Int, cc: Int) { }
f(1, 2, cc: 3) // ok
f(1, 2, xx: 3)
// expected-error@-1 {{incorrect argument label in call (have '_:_:xx:', expected '_:_:cc:')}}
f(1, cc: 2, 3)
// expected-error@-1 {{unnamed argument #3 must precede argument 'cc'}}
f(1, xx: 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:xx:_:', expected '_:_:cc:')}}
f(cc: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'cc:_:_:', expected '_:_:cc:')}}
f(xx: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:_:', expected '_:_:cc:')}}
f(xx: 1, yy: 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:yy:_:', expected '_:_:cc:')}}
f(xx: 1, 2, yy: 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:yy:', expected '_:_:cc:')}}
f(1, xx: 2, yy: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:xx:yy:', expected '_:_:cc:')}}
}
do {
func f(_ aa: Int, bb: Int, _ cc: Int) { }
// expected-note@-1 4 {{'f(_:bb:_:)' declared here}}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'bb', #3 in call}}
f(1, 2)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, 3)
// expected-error@-1 {{missing argument label 'bb:' in call}}
f(1, 2, bb: 3)
// expected-error@-1 {{argument 'bb' must precede unnamed argument #2}}
f(1, bb: 2, 3) // ok
f(bb: 1, 0, 2)
// expected-error@-1 {{unnamed argument #3 must precede argument 'bb'}}
f(xx: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:_:', expected '_:bb:_:')}}
f(1, xx: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, xx: 3)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
// expected-error@-2:17 {{extra argument 'xx' in call}}
}
do {
func f(_ aa: Int = 80, bb: Int, _ cc: Int) {}
f(bb: 1, 2) // ok
}
do {
// expected-note@+1 *{{'f(_:bb:_:)' declared here}}
func f(_ aa: Int, bb: Int, _ cc: Int...) { }
f(bb: 1, 2, 3, 4)
// expected-error@-1:7 {{missing argument for parameter #1 in call}}
}
do {
func f(_ aa: Int, bb: Int = 81, _ cc: Int...) {}
f(0, 2, 3) // ok
}
do {
// expected-note@+1 *{{'f(aa:_:_:)' declared here}}
func f(aa: Int, _ bb: Int, _ cc: Int) {}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'aa', #3 in call}}
f(0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(1, 2, 3)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(1, aa: 2, 3)
// expected-error@-1:10 {{argument 'aa' must precede unnamed argument #1}}
f(1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(aa: 1, 2, 3) // ok
f(xx: 1, 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(xx: 1, 2, yy: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument 'yy' in call}}
f(xx: 1, yy: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument in call}}
f(1, xx: 2, yy: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument 'yy' in call}}
f(1, 2, 3, 4)
// expected-error@-1:16 {{extra argument in call}}
f(1, aa: 2, 3, 4)
// expected-error@-1:20 {{extra argument in call}}
f(1, aa: 2, 3, xx: 4)
// expected-error@-1:24 {{extra argument 'xx' in call}}
f(1, aa: 2, xx: 3, 4)
// expected-error@-1:24 {{extra argument in call}}
}
do {
// expected-note@+1 *{{'f(aa:_:_:)' declared here}}
func f(aa: Int, _ bb: Int = 81, _ cc: Int) {}
f(0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
}
do {
// expected-note@+1 *{{'f(aa:bb:_:)' declared here}}
func f(aa: Int, bb: Int, _ cc: Int) {}
f(0, 2)
// expected-error@-1:6 {{missing argument labels 'aa:bb::' in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(0, bb: 1, 2)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(xx: 1, 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(1, 2, xx: 3)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
// expected-error@-2:17 {{extra argument 'xx' in call}}
}
do {
func f(aa: Int, bb: Int, cc: Int) { }
f(1, aa: 2, bb: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:aa:bb:', expected 'aa:bb:cc:')}}
f(1, bb: 2, aa: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:bb:aa:', expected 'aa:bb:cc:')}}
f(aa: 1, 2, bb: 3)
// expected-error@-1 {{incorrect argument labels in call (have 'aa:_:bb:', expected 'aa:bb:cc:')}}
f(aa: 1, bb: 2, 3)
// expected-error@-1 {{missing argument label 'cc:' in call}}
}
do {
func f(_ aa: Int, _ bb: Int = 81, cc: Int, _ dd: Int) {}
f(0, cc: 2, 3) // ok
}
do {
func f(_ aa: Int, _ bb: Int = 81, cc: Int = 82, _ dd: Int) {}
f(0, cc: 2, 3) // ok
f(cc: 1, 2, 3, 4)
// expected-error@-1 {{unnamed argument #3 must precede argument 'cc'}}
}
do {
func f(_ aa: Int, _ bb: Int, cc: Int, dd: Int) { }
// expected-note@-1 6 {{'f(_:_:cc:dd:)' declared here}}
f(1, xx: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:6 {{missing arguments for parameters 'cc', 'dd' in call}}
f(xx: 1, 2)
// expected-error@-1:6 {{missing arguments for parameters 'cc', 'dd' in call}}
// expected-error@-2 {{extraneous argument label 'xx:' in call}}
f(1, xx: 2, cc: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:22 {{missing argument for parameter 'dd' in call}}
f(1, xx: 2, dd: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:15 {{missing argument for parameter 'cc' in call}}
f(xx: 1, 2, cc: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:22 {{missing argument for parameter 'dd' in call}}
f(xx: 1, 2, dd: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:15 {{missing argument for parameter 'cc' in call}}
f(1, xx: 2, cc: 3, dd: 4)
// expected-error@-1:6 {{extraneous argument label 'xx:' in call}}
f(xx: 1, 2, cc: 3, dd: 4)
// expected-error@-1:6 {{extraneous argument label 'xx:' in call}}
}
do {
func f(_ aa: Int, bb: Int = 82, _ cc: Int, _ dd: Int) { }
f(1, bb: 2, 3, 4) // ok
f(1, 2, bb: 3, 4)
// expected-error@-1 {{argument 'bb' must precede unnamed argument #2}}
}
do {
func f(aa: Int, _ bb: Int, cc: Int, _ dd: Int) { }
// expected-note@-1 3 {{'f(aa:_:cc:_:)' declared here}}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'aa', 'cc', #4 in call}}
f(1, 2)
// expected-error@-1:6 {{missing arguments for parameters 'aa', 'cc' in call}}
f(1, 2, 3)
// expected-error@-1 {{missing argument labels 'aa:cc::' in call}}
// expected-error@-2:11 {{missing argument for parameter 'cc' in call}}
f(1, 2, 3, 4)
// expected-error@-1:6 {{missing argument labels 'aa:cc:' in call}}
f(1, 2, 3, 4, 5)
// expected-error@-1:19 {{extra argument in call}}
}
do {
func f(aa: Int, bb: Int, _ cc: Int, _ dd: Int) { }
// expected-note@-1 6 {{'f(aa:bb:_:_:)' declared here}}
f(1, xx: 2)
// expected-error@-1:6 {{missing arguments for parameters 'aa', 'bb' in call}}
// expected-error@-2 {{extraneous argument label 'xx:' in call}}
f(xx: 1, 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:6 {{missing arguments for parameters 'aa', 'bb' in call}}
f(bb: 1, 2, xx: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:6 {{extraneous argument label 'xx:' in call}}
f(bb: 1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:6 {{extraneous argument label 'xx:' in call}}
f(aa: 1, 2, xx: 3)
// expected-error@-1:12 {{missing argument for parameter 'bb' in call}}
// expected-error@-2:6 {{extraneous argument label 'xx:' in call}}
f(aa: 1, xx: 2, 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:12 {{missing argument for parameter 'bb' in call}}
f(aa: 1, bb: 2, 3, xx: 4)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(aa: 1, bb: 2, xx: 3, 4)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
}
do {
func f(_ aa: Int, bb: Int, _ cc: Int, dd: Int, _ ee: Int) { }
f(1, bb: 2, 3, 4, dd: 5)
// expected-error@-1:23 {{argument 'dd' must precede unnamed argument #4}}
f(1, dd: 2, 3, 4, bb: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:dd:_:_:bb:', expected '_:bb:_:dd:_:')}}
f(1, bb: 2, 3, dd: 4, 5) // ok
f(1, dd: 2, 3, bb: 4, 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:dd:_:bb:_:', expected '_:bb:_:dd:_:')}}
f(1, 2, bb: 3, 4, dd: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
f(1, bb: 2, 3, 4, dd: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
f(1, dd: 2, 3, 4, bb: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
}
}
// -------------------------------------------
// Missing arguments
// -------------------------------------------
// FIXME: Diagnostics could be improved with all missing names, or
// simply # of arguments required.
func missingargs1(x: Int, y: Int, z: Int) {} // expected-note {{'missingargs1(x:y:z:)' declared here}}
missingargs1(x: 1, y: 2) // expected-error{{missing argument for parameter 'z' in call}}
func missingargs2(x: Int, y: Int, _ z: Int) {} // expected-note {{'missingargs2(x:y:_:)' declared here}}
missingargs2(x: 1, y: 2) // expected-error{{missing argument for parameter #3 in call}}
// -------------------------------------------
// Extra arguments
// -------------------------------------------
func extraargs1(x: Int) {} // expected-note {{'extraargs1(x:)' declared here}}
extraargs1(x: 1, y: 2) // expected-error{{extra argument 'y' in call}}
extraargs1(x: 1, 2, 3) // expected-error{{extra arguments at positions #2, #3 in call}}
// -------------------------------------------
// Argument name mismatch
// -------------------------------------------
func mismatch1(thisFoo: Int = 0, bar: Int = 0, wibble: Int = 0) { } // expected-note {{'mismatch1(thisFoo:bar:wibble:)' declared here}}
mismatch1(foo: 5) // expected-error {{extra argument 'foo' in call}}
mismatch1(baz: 1, wobble: 2) // expected-error{{incorrect argument labels in call (have 'baz:wobble:', expected 'bar:wibble:')}} {{11-14=bar}} {{19-25=wibble}}
mismatch1(food: 1, zap: 2) // expected-error{{extra arguments at positions #1, #2 in call}}
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{incorrect argument label in call (have 'contentsOfURL:usedEncoding:', expected 'contentsOf:usedEncoding:')}}
// expected-error@-2 {{'nil' is not compatible with expected argument type 'String'}}
// expected-error@-3 {{'nil' is not compatible with expected argument type 'String'}}
// -------------------------------------------
// Out of order and default
// -------------------------------------------
struct OutOfOrderAndDefault {
func f11(alpha: Int, bravo: Int) {}
func f12(alpha: Int = -1, bravo: Int) {}
func f13(alpha: Int, bravo: Int = -1) {}
func f14(alpha: Int = -1, bravo: Int = -1) {}
func test1() {
// typo
f11(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f11(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f12(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f12(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f13(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f13(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f14(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f14(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
}
func f21(alpha: Int, bravo: Int, charlie: Int) {}
func f22(alpha: Int = -1, bravo: Int, charlie: Int) {}
func f23(alpha: Int = -1, bravo: Int = -1, charlie: Int) {}
func test2() {
// BAC
f21(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f21(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f21(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f22(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f22(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f22(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f23(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f23(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f23(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
// BCA
f21(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f21(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f21(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f22(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f22(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f22(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f23(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f23(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f23(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
// CAB
f21(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f21(charlie: 0, alpha: 1, bravox: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravox:', expected 'alpha:bravo:charlie:')}}
f21(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f22(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f22(charlie: 0, alpha: 1, bravox: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravox:', expected 'alpha:bravo:charlie:')}}
f22(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f23(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f23(charlie: 0, alpha: 1, bravox: 2) // expected-error {{argument 'alpha' must precede argument 'charlie'}}
f23(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
}
func f31(alpha: Int, bravo: Int, charlie: Int, delta: Int) {}
func f32(alpha: Int = -1, bravo: Int = -1, charlie: Int, delta: Int) {}
func f33(alpha: Int = -1, bravo: Int = -1, charlie: Int, delta: Int = -1) {}
func test3() {
// BACD
f31(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f31(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// BCAD
f31(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f31(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
}
}
// -------------------------------------------
// Subscript keyword arguments
// -------------------------------------------
struct Sub1 {
subscript (i: Int) -> Int {
get { return i }
}
}
var sub1 = Sub1()
var i: Int = 0
i = sub1[i]
i = sub1[i: i] // expected-error{{extraneous argument label 'i:' in subscript}} {{10-13=}}
struct Sub2 {
subscript (d d: Double) -> Double {
get { return d }
}
}
var sub2 = Sub2()
var d: Double = 0.0
d = sub2[d] // expected-error{{missing argument label 'd:' in subscript}} {{10-10=d: }}
d = sub2[d: d]
d = sub2[f: d] // expected-error{{incorrect argument label in subscript (have 'f:', expected 'd:')}} {{10-11=d}}
struct Sub3 {
subscript (a: Int..., b b: Int...) -> Int { 42 }
}
let sub3 = Sub3()
_ = sub3[1, 2, 3, b: 4, 5, 6]
_ = sub3[b: 4, 5, 6]
_ = sub3[1, 2, 3]
_ = sub3[1, c: 4] // expected-error {{incorrect argument label in subscript (have '_:c:', expected '_:b:')}}
struct Sub4 {
subscript (a: Int..., b b: Int = 0, c: Int...) -> Int { 42 }
}
let sub4 = Sub4()
_ = sub4[1, 2, 3, b: 2, 1, 2, 3]
_ = sub4[1, 2, 3, b: 2]
_ = sub4[1, 2, 3]
_ = sub4[]
// -------------------------------------------
// Closures
// -------------------------------------------
func intToInt(_ i: Int) -> Int { return i }
func testClosures() {
let c0 = { (x: Int, y: Int) in x + y }
_ = c0(1, 2)
let c1 = { x, y in intToInt(x + y) }
_ = c1(1, 2)
let c2 = { intToInt($0 + $1) }
_ = c2(1, 2)
}
func acceptAutoclosure(f: @autoclosure () -> Int) { }
func produceInt() -> Int { }
acceptAutoclosure(f: produceInt) // expected-error{{add () to forward @autoclosure parameter}} {{32-32=()}}
// -------------------------------------------
// Trailing closures
// -------------------------------------------
func trailingclosure1(x: Int, f: () -> Int) {}
trailingclosure1(x: 1) { return 5 }
trailingclosure1(1) { return 5 } // expected-error{{missing argument label 'x:' in call}}{{18-18=x: }}
trailingclosure1(x: 1, { return 5 }) // expected-error{{missing argument label 'f:' in call}} {{24-24=f: }}
func trailingclosure2(x: Int, f: (() -> Int)?...) {}
trailingclosure2(x: 5) { return 5 }
func trailingclosure3(x: Int, f: (() -> Int)!) {
var f = f
f = nil
_ = f
}
trailingclosure3(x: 5) { return 5 }
func trailingclosure4(f: () -> Int) {}
trailingclosure4 { 5 }
func trailingClosure5<T>(_ file: String = #file, line: UInt = #line, expression: () -> T?) { }
func trailingClosure6<T>(value: Int, expression: () -> T?) { }
trailingClosure5(file: "hello", line: 17) { // expected-error{{extraneous argument label 'file:' in call}}{{18-24=}}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
trailingClosure6(5) { // expected-error{{missing argument label 'value:' in call}}{{18-18=value: }}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
class MismatchOverloaded1 {
func method1(_ x: Int!, arg: ((Int) -> Int)!) { }
func method1(_ x: Int!, secondArg: ((Int) -> Int)!) { }
@available(*, unavailable)
func method2(_ x: Int!, arg: ((Int) -> Int)!) { }
func method2(_ x: Int!, secondArg: ((Int) -> Int)!) { }
}
var mismatchOverloaded1 = MismatchOverloaded1()
mismatchOverloaded1.method1(5, arg: nil)
mismatchOverloaded1.method1(5, secondArg: nil)
// Prefer available to unavailable declaration, if it comes up.
mismatchOverloaded1.method2(5) { $0 }
struct RelabelAndTrailingClosure {
func f1(aa: Int, bb: Int, cc: () -> Void = {}) {}
func f2(aa: Int, bb: Int, _ cc: () -> Void = {}) {}
func test() {
f1(aax: 1, bbx: 2) {} // expected-error {{incorrect argument labels in call (have 'aax:bbx:_:', expected 'aa:bb:_:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f2(aax: 1, bbx: 2) {} // expected-error {{incorrect argument labels in call (have 'aax:bbx:_:', expected 'aa:bb:_:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f1(aax: 1, bbx: 2) // expected-error {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f2(aax: 1, bbx: 2) // expected-error {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
}
}
// -------------------------------------------
// Values of function type
// -------------------------------------------
func testValuesOfFunctionType(_ f1: (_: Int, _ arg: Int) -> () ) {
f1(3, arg: 5) // expected-error{{extraneous argument label 'arg:' in call}}{{9-14=}}
f1(x: 3, 5) // expected-error{{extraneous argument label 'x:' in call}} {{6-9=}}
f1(3, 5)
}
// -------------------------------------------
// Literals
// -------------------------------------------
func string_literals1(x: String) { }
string_literals1(x: "hello")
func int_literals1(x: Int) { }
int_literals1(x: 1)
func float_literals1(x: Double) { }
float_literals1(x: 5)
// -------------------------------------------
// Tuples as arguments
// -------------------------------------------
func produceTuple1() -> (Int, Bool) { return (1, true) }
func acceptTuple1<T>(_ x: (T, Bool)) { }
acceptTuple1(produceTuple1())
acceptTuple1((1, false))
acceptTuple1(1, false) // expected-error {{global function 'acceptTuple1' expects a single parameter of type '(T, Bool)' [with T = Int]}} {{14-14=(}} {{22-22=)}}
func acceptTuple2<T>(_ input : T) -> T { return input }
var tuple1 = (1, "hello")
_ = acceptTuple2(tuple1)
_ = acceptTuple2((1, "hello", 3.14159))
func generic_and_missing_label(x: Int) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
func generic_and_missing_label<T>(x: T) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
generic_and_missing_label(42)
// expected-error@-1 {{no exact matches in call to global function 'generic_and_missing_label'}}
// -------------------------------------------
// Curried functions
// -------------------------------------------
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let f10 = f7(2)
_ = f10(1)
f10(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f10(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f10(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 3 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'CurriedClass'}}
// expected-error@-1:27 {{argument passed to call that takes no arguments}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{extra argument in call}}
// expected-error@-1 {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{extraneous argument label 'b:' in call}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// expected-error@-1 {{missing argument label 'b:' in call}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-2 {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing arguments for parameters #1, 'b' in call}} {{13-13=<#Int#>, b: <#Int#>}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self)
// expected-error@-1:13 {{cannot convert value of type 'CurriedClass' to expected argument type 'Int'}}
// expected-error@-2:17 {{missing argument for parameter 'b' in call}} {{17-17=, b: <#Int#>}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// -------------------------------------------
// Multiple label errors
// -------------------------------------------
func testLabelErrorsBasic() {
func f(_ aa: Int, _ bb: Int, cc: Int, dd: Int, ee: Int, ff: Int) {}
// 1 wrong
f(0, 1, ccx: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument label in call (have '_:_:ccx:dd:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{none}}
// 1 missing
f(0, 1, 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{missing argument label 'cc:' in call}} {{11-11=cc: }} {{none}}
// 1 extra
f(aa: 0, 1, cc: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{extraneous argument label 'aa:' in call}} {{5-9=}} {{none}}
// 1 ooo
f(0, 1, dd: 3, cc: 2, ee: 4, ff: 5)
// expected-error@-1 {{argument 'cc' must precede argument 'dd'}} {{16-23=}} {{11-11=cc: 2, }} {{none}}
// 2 wrong
f(0, 1, ccx: 2, ddx: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:ddx:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{19-22=dd}} {{none}}
// 2 missing
f(0, 1, 2, 3, ee: 4, ff: 5)
// expected-error@-1 {{missing argument labels 'cc:dd:' in call}} {{11-11=cc: }} {{14-14=dd: }} {{none}}
// 2 extra
f(aa: 0, bb: 1, cc: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{extraneous argument labels 'aa:bb:' in call}} {{5-9=}} {{12-16=}} {{none}}
// 2 ooo
f(0, 1, dd: 3, cc: 2, ff: 5, ee: 4)
// expected-error@-1 {{argument 'cc' must precede argument 'dd'}} {{16-23=}} {{11-11=cc: 2, }} {{none}}
// 1 wrong + 1 missing
f(0, 1, ccx: 2, 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:_:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{19-19=dd: }} {{none}}
// 1 wrong + 1 extra
f(aa: 0, 1, ccx: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have 'aa:_:ccx:dd:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{5-9=}} {{15-18=cc}} {{none}}
// 1 wrong + 1 ooo
f(0, 1, ccx: 2, dd: 3, ff: 5, ee: 4)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:dd:ff:ee:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{26-28=ee}} {{33-35=ff}} {{none}}
}
struct DiagnoseAllLabels {
func f(aa: Int, bb: Int, cc: Int..., dd: Int, ee: Int = 0, ff: Int = 0) {}
func test() {
f(aax: 0, bbx: 1, cc: 21, 22, 23, dd: 3, ff: 5) // expected-error {{incorrect argument labels in call (have 'aax:bbx:cc:_:_:dd:ff:', expected 'aa:bb:cc:_:_:dd:ff:')}} {{7-10=aa}} {{15-18=bb}} {{none}}
f(aax: 0, bbx: 1, dd: 3, ff: 5) // expected-error {{incorrect argument labels in call (have 'aax:bbx:dd:ff:', expected 'aa:bb:dd:ff:')}} {{7-10=aa}} {{15-18=bb}} {{none}}
}
}
// SR-13135: Type inference regression in Swift 5.3 - can't infer a type of @autoclosure result.
func sr13135() {
struct Foo {
var bar: [Int] = []
}
let baz: Int? = nil
func foo<T: Equatable>(
_ a: @autoclosure () throws -> T,
_ b: @autoclosure () throws -> T
) {}
foo(Foo().bar, [baz])
}
// SR-13240
func twoargs(_ x: String, _ y: String) {}
func test() {
let x = 1
twoargs(x, x) // expected-error 2 {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
infix operator ---
func --- (_ lhs: String, _ rhs: String) -> Bool { true }
let x = 1
x --- x // expected-error 2 {{cannot convert value of type 'Int' to expected argument type 'String'}}
// rdar://problem/70764991 - out-of-order diagnostic crashes the compiler
func rdar70764991() {
struct S {
static var foo: S { get { S() } }
}
func bar(_: Any, _: String) {
}
func test(_ str: String) {
bar(str, S.foo) // expected-error {{unnamed argument #1 must precede unnamed argument #2}} {{9-12=}} {{14-14=str}}
}
}
func testExtraTrailingClosure() {
func foo() {}
foo() {} // expected-error@:9 {{extra trailing closure passed in call}}
foo {} // expected-error@:7 {{extra trailing closure passed in call}}
foo {} x: {} // expected-error@:7 {{argument passed to call that takes no arguments}}
func bar(_ x: Int) {} // expected-note 2{{'bar' declared here}}
bar(5) {} // expected-error@:10 {{extra trailing closure passed in call}}
bar(0) {} x: {} // expected-error@:6 {{extra trailing closures at positions #2, #3 in call}}
bar(5, "") {} // expected-error@:6 {{extra arguments at positions #2, #3 in call}}
func baz(_ fn: () -> Void) {} // expected-note {{'baz' declared here}}
baz {} x: {} // expected-error@:13 {{extra trailing closure passed in call}}
baz({}) {} // expected-error@:11 {{extra trailing closure passed in call}}
baz({}) {} y: {} // expected-error@:6 {{extra trailing closures at positions #2, #3 in call}}
func qux(x: () -> Void, y: () -> Void, z: () -> Void) {} // expected-note {{'qux(x:y:z:)' declared here}}
qux() {} m: {} y: {} n: {} z: {} o: {} // expected-error@:6 {{extra trailing closures at positions #2, #4, #6 in call}}
}
| apache-2.0 | 41d046da0b94efdda4d6d47913045dfb | 42.965807 | 204 | 0.596073 | 3.037644 | false | false | false | false |
tripleCC/GanHuoCode | GanHuo/Extension/CALayer+Extension.swift | 1 | 1831 | //
// CALayer+Extension.swift
// WKCC
//
// Created by tripleCC on 15/12/14.
// Copyright © 2015年 tripleCC. All rights reserved.
//
import UIKit
extension CALayer {
func saveImageWithName(name: String) {
let data = UIImagePNGRepresentation(UIImage(layer: self))
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] + "/\(name).png"
debugPrint(path)
data?.writeToFile(path, atomically: false)
}
}
func addRotateAnimationWithDuration(duration: Float, forKey key: String? = nil) {
let transformAnimation = CABasicAnimation(keyPath: "transform")
transformAnimation.removedOnCompletion = false
transformAnimation.repeatCount = MAXFLOAT
transformAnimation.duration = CFTimeInterval(duration)
transformAnimation.beginTime = CACurrentMediaTime()
transformAnimation.fromValue = NSValue(CATransform3D: CATransform3DMakeRotation(0, 0, 0, 1.0))
transformAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeRotation(CGFloat(M_PI_2 * 2.0), 0, 0, 1.0))
addAnimation(transformAnimation, forKey: key)
}
// 好像没用
func pausingAnimation() {
guard let _ = animationKeys() else { return }
speed = 0.0;
timeOffset = convertTime(CACurrentMediaTime(), fromLayer: nil)
}
func resumeAniamtion() {
guard let _ = animationKeys() else { return }
speed = 1.0;
let pausedTime = timeOffset;
timeOffset = 0.0;
beginTime = 0.0;
let timeSincePause = convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
beginTime = timeSincePause;
}
} | mit | 8c82d0b96b65b1150e48dfd04f398140 | 37.744681 | 162 | 0.665385 | 4.739583 | false | false | false | false |
dvogt23/KartApp-iOS | karteikarten/DraggableView.swift | 1 | 8507 | //
// DraggableView.swift
//
// Erstellt einen View (Karteikarte) mit den Funktionen zum Karte bewegen, sowie die Aktionen
// für "gewusst" und "nicht gewusst"
//
//
import Foundation
import UIKit
let ACTION_MARGIN: Float = 120
let SCALE_STRENGTH: Float = 4
let SCALE_MAX:Float = 0.93
let ROTATION_MAX: Float = 1
let ROTATION_STRENGTH: Float = 320
let ROTATION_ANGLE: Float = 3.14/8
protocol DraggableViewDelegate {
func cardSwipedLeft(card: UIView) -> Void
func cardSwipedRight(card: UIView) -> Void
func flip(card: DraggableView) -> Void
}
class DraggableView: UIView {
var delegate: DraggableViewDelegate!
var panGestureRecognizer: UIPanGestureRecognizer!
var tapGestureRecognizer: UITapGestureRecognizer!
var originPoint: CGPoint!
var overlayView: OverlayView!
var information: UITextView!
var answer: UITextView!
var xFromCenter: Float!
var yFromCenter: Float!
var cardID: Int!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// init: erstelle View (Karteikate) mit subview der Rückseite;
// gestureRecognizer: erkennt Interaktion mit Touch-Display: pan : ziehen; tap: tippen;
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
information = UITextView(frame: CGRectMake(self.frame.size.width * 0.1, 50, self.frame.size.width * 0.8, self.frame.size.height*0.8))
information.text = "no info given"
information.textAlignment = NSTextAlignment.Center
information.textColor = UIColor.blackColor()
information.font = UIFont.systemFontOfSize(14)
information.editable = false
information.selectable = false
information.hidden = false
answer = UITextView(frame: CGRectMake(self.frame.size.width * 0.1, 50, self.frame.size.width * 0.8, self.frame.size.height*0.8))
answer.text = "no info given"
answer.textAlignment = NSTextAlignment.Center
answer.textColor = UIColor.blackColor()
answer.font = UIFont.systemFontOfSize(14)
answer.editable = false
answer.selectable = false
answer.hidden = true
self.backgroundColor = UIColor.whiteColor()
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "beingDragged:")
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("flipCard:"))
tapGestureRecognizer.numberOfTapsRequired = 1
self.addGestureRecognizer(panGestureRecognizer)
self.addGestureRecognizer(tapGestureRecognizer)
self.addSubview(information)
self.addSubview(answer)
overlayView = OverlayView(frame: CGRectMake(self.frame.size.width/2-100, 0, 100, 100))
overlayView.alpha = 0
self.addSubview(overlayView)
xFromCenter = 0
yFromCenter = 0
}
func setupView() -> Void {
self.layer.cornerRadius = 4;
self.layer.shadowRadius = 3;
self.layer.shadowOpacity = 0.2;
self.layer.shadowOffset = CGSizeMake(1, 1);
}
// Animation "Karte wird bewegt"
func beingDragged(gestureRecognizer: UIPanGestureRecognizer) -> Void {
xFromCenter = Float(gestureRecognizer.translationInView(self).x)
yFromCenter = Float(gestureRecognizer.translationInView(self).y)
switch gestureRecognizer.state {
case UIGestureRecognizerState.Began:
self.originPoint = self.center
case UIGestureRecognizerState.Changed:
let rotationStrength: Float = min(xFromCenter/ROTATION_STRENGTH, ROTATION_MAX)
let rotationAngle = ROTATION_ANGLE * rotationStrength
let scale = max(1 - fabsf(rotationStrength) / SCALE_STRENGTH, SCALE_MAX)
self.center = CGPointMake(self.originPoint.x + CGFloat(xFromCenter), self.originPoint.y + CGFloat(yFromCenter))
let transform = CGAffineTransformMakeRotation(CGFloat(rotationAngle))
let scaleTransform = CGAffineTransformScale(transform, CGFloat(scale), CGFloat(scale))
self.transform = scaleTransform
self.updateOverlay(CGFloat(xFromCenter))
case UIGestureRecognizerState.Ended:
self.afterSwipeAction()
case UIGestureRecognizerState.Possible:
fallthrough
case UIGestureRecognizerState.Cancelled:
fallthrough
case UIGestureRecognizerState.Failed:
fallthrough
default:
break
}
}
// update View beim Bewegen der Karte
func updateOverlay(distance: CGFloat) -> Void {
if distance > 0 {
overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeRight)
} else {
overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeLeft)
}
overlayView.alpha = CGFloat(min(fabsf(Float(distance))/100, 0.4))
}
// Aktion nach loslassen der Karte
// Karte wieder zurück zum Zentrum des Displays oder, wenn weit genug bewegt: Karte wir vom Display entfernt; nächste Karte laden
func afterSwipeAction() -> Void {
let floatXFromCenter = Float(xFromCenter)
if floatXFromCenter > ACTION_MARGIN {
self.rightAction()
} else if floatXFromCenter < -ACTION_MARGIN {
self.leftAction()
} else {
UIView.animateWithDuration(0.3, animations: {() -> Void in
self.center = self.originPoint
self.transform = CGAffineTransformMakeRotation(0)
self.overlayView.alpha = 0
})
}
}
// Aktion "gewusst"
// Karte wird vom Display entfernt --> "gewusst"; nächste Karte laden
func rightAction() -> Void {
let finishPoint: CGPoint = CGPointMake(500, 2 * CGFloat(yFromCenter) + self.originPoint.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
if examMode == false {
Stats.writeStats(self.cardID, known: 1)
Cards.boxUP(self.cardID)
}
delegate.cardSwipedRight(self)
}
// Aktion "nicht gewusst"
// Karte wird vom Display entfernt --> "nicht gewusst"; nächste Karte laden
func leftAction() -> Void {
let finishPoint: CGPoint = CGPointMake(-500, 2 * CGFloat(yFromCenter) + self.originPoint.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
if examMode == false {
Stats.writeStats(self.cardID, known: 0)
Cards.boxDOWN(self.cardID)
}
delegate.cardSwipedLeft(self)
}
// Button "gewusst" gedückt
// Karte wird vom Display entfernt --> "gewusst"; nächste Karte laden
func rightClickAction() -> Void {
let finishPoint = CGPointMake(600, self.center.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
self.transform = CGAffineTransformMakeRotation(1)
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
if examMode == false {
Stats.writeStats(self.cardID, known: 1)
Cards.boxUP(self.cardID)
}
delegate.cardSwipedRight(self)
}
// Button "nicht gewusst" gedückt
// Karte wird vom Display entfernt --> "nicht gewusst"; nächste Karte laden
func leftClickAction() -> Void {
let finishPoint: CGPoint = CGPointMake(-600, self.center.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
self.transform = CGAffineTransformMakeRotation(1)
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
if examMode == false {
Stats.writeStats(self.cardID, known: 0)
Cards.boxDOWN(self.cardID)
}
delegate.cardSwipedLeft(self)
}
// tippen zum Karte drehen
func flipCard(sender: UITapGestureRecognizer) -> Void {
if (sender.state == .Ended){
delegate.flip(self)
}
}
} | mit | a1f3e52fdaba8c5859fd8c3d4ac1b237 | 34.705882 | 141 | 0.624456 | 4.43476 | false | false | false | false |
zhouxj6112/ARKit | ARHome/ARHome/Additional View Controllers/VirtualObjectSelection.swift | 1 | 6680 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Popover view controller for choosing virtual objects to place in the AR scene.
*/
import UIKit
// MARK: - ObjectCell
class ObjectCell: UITableViewCell {
static let reuseIdentifier = "ObjectCell"
@IBOutlet weak var objectTitleLabel: UILabel!
@IBOutlet weak var objectImageView: UIImageView!
var modelName = "" {
didSet {
objectTitleLabel.text = modelName
}
}
var modelImage = "" {
didSet {
objectImageView.loadImageWithUrl(imageUrl: modelImage)
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - VirtualObjectSelectionViewControllerDelegate
/// A protocol for reporting which objects have been selected.
protocol VirtualObjectSelectionViewControllerDelegate: class {
func virtualObjectSelectionViewController(_ selectionViewController: UIViewController, didSelectObjectUrl: URL, didSelectObjectID: String)
func virtualObjectSelectionViewController(_ selectionViewController: UIViewController, didDeselectObjectUrl: URL, didDeselectObjectID: String)
}
/// A custom table view controller to allow users to select `VirtualObject`s for placement in the scene.
class VirtualObjectSelectionViewController: UITableViewController {
/// The collection of `VirtualObject`s to select from.
var virtualObjects = [VirtualObject]()
var modelList:NSArray = []
/// The rows of the currently selected `VirtualObject`s.
private var selectedVirtualObjectRows = IndexSet()
weak var selectionDelegate: VirtualObjectSelectionViewControllerDelegate?
override func loadView() {
super.loadView()
debugPrint("\(self.view.frame)")
}
override func viewDidLoad() {
super.viewDidLoad()
let urls = VirtualObjectLoader.availableObjectUrls;
for url in urls {
let dic = NSDictionary.init();
dic.setValue(url, forKey: "fileUrl");
modelList.adding(dic);
}
tableView.separatorEffect = UIVibrancyEffect(blurEffect: UIBlurEffect(style: .light))
}
override func viewWillLayoutSubviews() {
//
preferredContentSize = CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-180)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let object = virtualObjects[indexPath.row]
let dic = modelList[indexPath.section] as! Dictionary<String, Any>
let list = dic["list"] as! NSArray
var data = list[indexPath.row] as! Dictionary<String, Any>
// 初始化模型
let fileUrl = data["fileUrl"] as! String // 注意中文问题
let encodedUrl = fileUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL.init(string: encodedUrl!)
let modelId = data["modelId"] as! String
var isIn = false
if data.keys.contains("isIn") && data["isIn"] as! Bool == true {
isIn = true
}
// Check if the current row is already selected, then deselect it.
if isIn {
selectionDelegate?.virtualObjectSelectionViewController(self, didDeselectObjectUrl: url!, didDeselectObjectID: modelId)
data["isIn"] = false
} else {
selectionDelegate?.virtualObjectSelectionViewController(self, didSelectObjectUrl: url!, didSelectObjectID: modelId)
data["isIn"] = true
}
// debugPrint("data: \(data)")
dismiss(animated: true, completion: nil)
// let vc = SelectionHomeViewController.init(nibName: nil, bundle: nil)
// self.navigationController?.pushViewController(vc, animated: true)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let dic = modelList[section] as! Dictionary<String, Any>
let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
view.backgroundColor = UIColor.lightGray
let label = UILabel.init(frame: CGRect.init(x: 5, y: 0, width: 120, height: 40));
label.text = dic["typeName"] as? String;
view.addSubview(label)
return view
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return modelList.count;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dic = modelList[section] as! Dictionary<String, Any>
let list = dic["list"] as! NSArray
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ObjectCell.reuseIdentifier, for: indexPath) as? ObjectCell else {
fatalError("Expected `\(ObjectCell.self)` type for reuseIdentifier \(ObjectCell.reuseIdentifier). Check the configuration in Main.storyboard.")
}
let dic = modelList[indexPath.section] as! Dictionary<String, Any>
let list = dic["list"] as! NSArray
let data = list[indexPath.row] as! Dictionary<String, Any>
cell.modelName = data["modelName"] as! String
cell.modelImage = data["compressImage"] as! String // 使用压缩图
// debugPrint("data: \(data)")
// 是否被选中
if data.keys.contains("isIn") && data["isIn"] as! Bool == true {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .clear
}
}
| apache-2.0 | ddeafe58b57d073e61d6c2c31b6a13f1 | 36.92 | 155 | 0.658831 | 4.955937 | false | false | false | false |
ben-ng/swift | test/decl/var/variables.swift | 1 | 4001 | // RUN: %target-typecheck-verify-swift
var t1 : Int
var t2 = 10
var t3 = 10, t4 = 20.0
var (t5, t6) = (10, 20.0)
var t7, t8 : Int
var t9, t10 = 20 // expected-error {{type annotation missing in pattern}}
var t11, t12 : Int = 20 // expected-error {{type annotation missing in pattern}}
var t13 = 2.0, t14 : Int
var (x = 123, // expected-error {{expected ',' separator}} {{7-7=,}} expected-error {{expected pattern}}
y = 456) : (Int,Int)
var bfx : Int, bfy : Int
_ = 10
func _(_ x: Int) {} // expected-error {{keyword '_' cannot be used as an identifier here}}
// expected-note @-1 {{if this name is unavoidable, use backticks to escape it}}
var self1 = self1 // expected-error {{variable used within its own initial value}}
var self2 : Int = self2 // expected-error {{variable used within its own initial value}}
var (self3) : Int = self3 // expected-error {{variable used within its own initial value}}
var (self4) : Int = self4 // expected-error {{variable used within its own initial value}}
var self5 = self5 + self5 // expected-error 2 {{variable used within its own initial value}}
var self6 = !self6 // expected-error {{variable used within its own initial value}}
var (self7a, self7b) = (self7b, self7a) // expected-error 2 {{variable used within its own initial value}}
var self8 = 0
func testShadowing() {
var self8 = self8 // expected-error {{variable used within its own initial value}}
}
var (paren) = 0
var paren2: Int = paren
struct Broken {
var b : Bool = True // expected-error{{use of unresolved identifier 'True'}}
}
// rdar://16252090 - Warning when inferring empty tuple type for declarations
var emptyTuple = testShadowing() // expected-warning {{variable 'emptyTuple' inferred to have type '()'}} \
// expected-note {{add an explicit type annotation to silence this warning}}
// rdar://15263687 - Diagnose variables inferenced to 'AnyObject'
var ao1 : AnyObject
var ao2 = ao1
var aot1 : AnyObject.Type
var aot2 = aot1 // expected-warning {{variable 'aot2' inferred to have type 'AnyObject.Type', which may be unexpected}} \
// expected-note {{add an explicit type annotation to silence this warning}}
for item in [AnyObject]() { // No warning in for-each loop.
}
// <rdar://problem/16574105> Type inference of _Nil very coherent but kind of useless
var ptr = nil // expected-error {{'nil' requires a contextual type}}
func testAnyObjectOptional() -> AnyObject? {
let x = testAnyObjectOptional()
return x
}
class SomeClass {}
// <rdar://problem/16877304> weak let's should be rejected
weak let V = SomeClass() // expected-error {{'weak' must be a mutable variable, because it may change at runtime}}
let a = b ; let b = a // expected-error{{could not infer type for 'a'}}
// expected-error@-1 {{'a' used within its own type}}
// FIXME: That second error is bogus.
// <rdar://problem/17501765> Swift should warn about immutable default initialized values
let uselessValue : String?
func tuplePatternDestructuring(_ x : Int, y : Int) {
let (b: _, a: h) = (b: x, a: y)
_ = h
// <rdar://problem/20392122> Destructuring tuple with labels doesn't work
let (i, j) = (b: x, a: y)
_ = i+j
// <rdar://problem/20395243> QoI: type variable reconstruction failing for tuple types
let (x: g1, a: h1) = (b: x, a: y) // expected-error {{tuple type '(b: Int, a: Int)' is not convertible to tuple '(x: _, a: _)'}}
}
// <rdar://problem/21057425> Crash while compiling attached test-app.
func test21057425() -> (Int, Int) {
let x: Int = "not an int!", y = 0 // expected-error{{cannot convert value of type 'String' to specified type 'Int'}}
return (x, y)
}
// rdar://problem/21081340
func test21081340() {
let (x: a, y: b): () = foo() // expected-error{{tuple pattern has the wrong length for tuple type '()'}}
}
// <rdar://problem/22322266> Swift let late initialization in top level control flow statements
if true {
let s : Int
s = 42 // should be valid.
}
| apache-2.0 | 5c553963104dc9c88cece74cf63382ab | 36.046296 | 131 | 0.667333 | 3.470078 | false | true | false | false |
igroomgrim/RBQFetchedResultsController | Swift/FetchedResultsController.swift | 1 | 16873 | //
// FetchedResultsController.swift
// RBQFRCSwiftExample
//
// Created by Adam Fish on 7/23/15.
// Copyright (c) 2015 Adam Fish. All rights reserved.
//
import Realm
import RealmSwift
/**
This class is used by the FetchedResultsController to pass along section info.
*/
public class FetchResultsSectionInfo<T: Object> {
// MARK: Properties
/**
The number of objects in the section.
*/
public var numberOfObjects: UInt {
return self.rbqFetchedResultsSectionInfo.numberOfObjects
}
/**
The objects in the section (generated on-demand and not thread-safe).
*/
public var objects: Results<T> {
if self.sectionNameKeyPath != nil {
return self.fetchRequest.fetchObjects().filter("%K == %@", self.sectionNameKeyPath!,self.rbqFetchedResultsSectionInfo.name)
}
return self.fetchRequest.fetchObjects()
}
/**
The name of the section.
*/
public var name: String {
return self.rbqFetchedResultsSectionInfo.name
}
// MARK: Private functions/properties
internal let rbqFetchedResultsSectionInfo: RBQFetchedResultsSectionInfo
internal let fetchRequest: FetchRequest<T>
internal let sectionNameKeyPath: String?
internal init(rbqFetchedResultsSectionInfo: RBQFetchedResultsSectionInfo, fetchRequest: FetchRequest<T>, sectionNameKeyPath: String?) {
self.rbqFetchedResultsSectionInfo = rbqFetchedResultsSectionInfo
self.fetchRequest = fetchRequest
self.sectionNameKeyPath = sectionNameKeyPath
}
}
/**
Delegate to pass along the changes identified by the FetchedResultsController.
*/
public protocol FetchedResultsControllerDelegate {
/**
Indicates that the controller has started identifying changes.
:param: controller controller instance that noticed the change on its fetched objects
*/
func controllerWillChangeContent<T: Object>(controller: FetchedResultsController<T>)
/**
Notifies the delegate that a fetched object has been changed due to an add, remove, move, or update. Enables FetchedResultsController change tracking.
Changes are reported with the following heuristics:
On add and remove operations, only the added/removed object is reported. It’s assumed that all objects that come after the affected object are also moved, but these moves are not reported.
A move is reported when the changed attribute on the object is one of the sort descriptors used in the fetch request. An update of the object is assumed in this case, but no separate update message is sent to the delegate.
An update is reported when an object’s state changes, but the changed attributes aren’t part of the sort keys.
:param: controller controller instance that noticed the change on its fetched objects
:param: anObject changed object represented as a SafeObject for thread safety
:param: indexPath indexPath of changed object (nil for inserts)
:param: type indicates if the change was an insert, delete, move, or update
:param: newIndexPath the destination path for inserted or moved objects, nil otherwise
*/
func controllerDidChangeObject<T: Object>(controller: FetchedResultsController<T>, anObject: SafeObject<T>, indexPath: NSIndexPath?, changeType: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
/**
The fetched results controller reports changes to its section before changes to the fetched result objects.
:param: controller controller controller instance that noticed the change on its fetched objects
:param: section changed section represented as a FetchedResultsSectionInfo object
:param: sectionIndex the section index of the changed section
:param: type indicates if the change was an insert or delete
*/
func controllerDidChangeSection<T:Object>(controller: FetchedResultsController<T>, section: FetchResultsSectionInfo<T>, sectionIndex: UInt, changeType: NSFetchedResultsChangeType)
/**
This method is called at the end of processing changes by the controller
:param: controller controller instance that noticed the change on its fetched objects
*/
func controllerDidChangeContent<T: Object>(controller: FetchedResultsController<T>)
}
/**
The class is used to monitor changes from a RBQRealmNotificationManager to convert these changes into specific index path or section index changes. Typically this is used to back a UITableView and support animations when items are inserted, deleted, or changed.
*/
public class FetchedResultsController<T: Object> {
// MARK: Class Functions
/**
Deletes the cached section information with the given name
If name is not nil, then the cache will be cleaned, but not deleted from disk.
If name is nil, then all caches will be deleted by removing the files from disk.
:warning: If clearing all caches (name is nil), it is recommended to do this in didFinishLaunchingWithOptions: in AppDelegate because Realm files cannot be deleted from disk safely, if there are strong references to them.
:param: name The name of the cache file to delete. If name is nil, deletes all cache files.
*/
public class func deleteCache(cacheName: String) {
RBQFetchedResultsController.deleteCacheWithName(cacheName)
}
/**
Retrieves all the paths for the Realm files being used as FRC caches on disk.
The typical use case for this method is to use the paths to perform migrations in AppDelegate. The FRC cache files need to be migrated along with your other Realm files because by default Realm includes all of the properties defined in your model in all Realm files. Thus the FRC cache files will throw an exception if they are not migrated. Call setSchemaVersion:forRealmAtPath:withMigrationBlock: for each path returned in the array.
:returns: NSArray of NSStrings representing the paths on disk for all FRC cache Realm files
*/
public class func allCacheRealmPaths() -> [String] {
var paths = [String]()
let allPaths = RBQFetchedResultsController.allCacheRealmPaths()
for aPath: AnyObject in allPaths {
if let path = aPath as? String {
paths.append(path)
}
}
return paths
}
// MARK: Initializer
/**
Constructor method to initialize the controller
:warning: Specify a cache name if deletion of the cache later on is necessary
:param: fetchRequest the FetchRequest for the controller
:param: sectionNameKeyPath A key path on result objects that returns the section name. Pass nil to indicate that the controller should generate a single section. If this key path is not the same as that specified by the first sort descriptor in fetchRequest, they must generate the same relative orderings.
:param: name the cache name (if nil, cache will not be persisted and built using an in-memory Realm)
:returns: A new instance of FetchedResultsController
*/
public init(fetchRequest: FetchRequest<T>, sectionNameKeyPath: String?, cacheName: String?) {
self.fetchRequest = fetchRequest
self.rbqFetchedResultsController = RBQFetchedResultsController(fetchRequest: fetchRequest.rbqFetchRequest, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName)
self.delegateProxy = DelegateProxy(delegate: self)
self.rbqFetchedResultsController.delegate = self.delegateProxy!
}
// MARK: Properties
/// The fetch request for the controller
public let fetchRequest: FetchRequest<T>
/// The section name key path used to create the sections. Can be nil if no sections.
public var sectionNameKeyPath: String? {
return self.rbqFetchedResultsController.sectionNameKeyPath
}
/// The delegate to pass the index path and section changes to.
public var delegate: FetchedResultsControllerDelegate?
/// The name of the cache used internally to represent the tableview structure.
public var cacheName: String? {
return self.rbqFetchedResultsController.cacheName
}
/// All the objects that match the fetch request.
public var fetchedObjects: Results<T> {
return self.fetchRequest.fetchObjects()
}
// MARK: Functions
/**
Method to tell the controller to perform the fetch
:returns: Indicates if the fetch was successful
*/
public func performFetch() -> Bool {
return self.rbqFetchedResultsController.performFetch()
}
/**
Call this method to force the cache to be rebuilt.
A potential use case would be to call this in a @catch after trying to call endUpdates for the table view. If an exception is thrown, then the cache will be rebuilt and you can call reloadData on the table view.
*/
public func reset() {
self.rbqFetchedResultsController.reset()
}
/**
Method to retrieve the number of rows for a given section index
:param: index section index
:returns: number of rows in the section
*/
public func numberOfRowsForSectionIndex(index: Int) -> Int {
return self.rbqFetchedResultsController.numberOfRowsForSectionIndex(index)
}
/**
Method to retrieve the number of sections represented by the fetch request
:returns: number of sections
*/
public func numberOfSections() -> Int {
return self.rbqFetchedResultsController.numberOfSections()
}
/**
Method to retrieve the title for a given section index
:param: section section index
*
:returns: The title of the section
*/
public func titleForHeaderInSection(section: Int) -> String {
return self.rbqFetchedResultsController.titleForHeaderInSection(section)
}
/**
Method to retrieve the section index given a section name
:warning: Returns NSNotFound if there is not a section with the given name
:param: sectionName the name of the section
:returns: the index of the section (returns NSNotFound if no section with the given name)
*/
public func sectionIndexForSectionName(sectionName: String) -> UInt {
return self.rbqFetchedResultsController.sectionIndexForSectionName(sectionName)
}
/**
Retrieve the SafeObject for a given index path
:param: indexPath the index path of the object
:returns: SafeObject
*/
public func safeObjectAtIndexPath(indexPath: NSIndexPath) -> SafeObject<T>? {
let rbqSafeObject = self.rbqFetchedResultsController.safeObjectAtIndexPath(indexPath)
let safeObject = SafeObject<T>(rbqSafeRealmObject: rbqSafeObject)
return safeObject
}
/**
Retrieve the Object for a given index path
:warning: Returned object is not thread-safe.
:param: indexPath the index path of the object
:returns: Object
*/
public func objectAtIndexPath(indexPath: NSIndexPath) -> T? {
if let rlmObject: AnyObject = self.rbqFetchedResultsController.objectAtIndexPath(indexPath) {
return unsafeBitCast(rlmObject, T.self)
}
return nil
}
/**
Retrieve the index path for a safe object in the fetch request
:param: safeObject an instance of SafeObject
:returns: index path of the object
*/
public func indexPathForSafeObject(safeObject: SafeObject<T>) -> NSIndexPath? {
return self.rbqFetchedResultsController.indexPathForSafeObject(safeObject.rbqSafeRealmObject)
}
/**
Retrieve the index path for a Object in the fetch request
:param: object an instance of Object
:returns: index path of the object
*/
public func indexPathForObject(object: T) -> NSIndexPath? {
return self.rbqFetchedResultsController.indexPathForObject(object)
}
/**
Convenience method to safely update the fetch request for an existing FetchResultsController
:param: fetchRequest a new instance of FetchRequest
:param: sectionNameKeyPath the section name key path for this fetch request (if nil, no sections will be shown)
:param: performFetch indicates whether you want to immediately performFetch using the new fetch request to rebuild the cache
*/
public func updateFetchRequest(fetchRequest: FetchRequest<T>, sectionNameKeyPath: String, performFetch: Bool) {
self.rbqFetchedResultsController.updateFetchRequest(fetchRequest.rbqFetchRequest, sectionNameKeyPath: sectionNameKeyPath, andPeformFetch: performFetch)
}
// MARK: Private functions/properties
internal let rbqFetchedResultsController: RBQFetchedResultsController
internal var delegateProxy: DelegateProxy?
}
// Internal Proxy To Manage Converting The Objc Delegate
extension FetchedResultsController: DelegateProxyProtocol {
func controllerWillChangeContent(controller: RBQFetchedResultsController!) {
if let delegate = self.delegate {
delegate.controllerWillChangeContent(self)
}
}
func controller(controller: RBQFetchedResultsController!, didChangeObject anObject: RBQSafeRealmObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
if let delegate = self.delegate {
let safeObject = SafeObject<T>(rbqSafeRealmObject: anObject)
delegate.controllerDidChangeObject(self, anObject: safeObject, indexPath: indexPath, changeType: type, newIndexPath: newIndexPath)
}
}
func controller(controller: RBQFetchedResultsController!, didChangeSection section: RBQFetchedResultsSectionInfo!, atIndex sectionIndex: UInt, forChangeType type: NSFetchedResultsChangeType) {
if let delegate = self.delegate {
let sectionInfo = FetchResultsSectionInfo<T>(rbqFetchedResultsSectionInfo: section, fetchRequest: self.fetchRequest, sectionNameKeyPath: self.sectionNameKeyPath)
delegate.controllerDidChangeSection(self, section: sectionInfo, sectionIndex: sectionIndex, changeType: type)
}
}
func controllerDidChangeContent(controller: RBQFetchedResultsController!) {
if let delegate = self.delegate {
delegate.controllerDidChangeContent(self)
}
}
}
// Internal Proxy To Manage Converting The Objc Delegate
internal protocol DelegateProxyProtocol {
func controllerWillChangeContent(controller: RBQFetchedResultsController!)
func controller(controller: RBQFetchedResultsController!, didChangeObject anObject: RBQSafeRealmObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!)
func controller(controller: RBQFetchedResultsController!, didChangeSection section: RBQFetchedResultsSectionInfo!, atIndex sectionIndex: UInt, forChangeType type: NSFetchedResultsChangeType)
func controllerDidChangeContent(controller: RBQFetchedResultsController!)
}
// Internal Proxy To Manage Converting The Objc Delegate
internal class DelegateProxy: NSObject, RBQFetchedResultsControllerDelegate {
internal let delegate: DelegateProxyProtocol
init(delegate: DelegateProxyProtocol) {
self.delegate = delegate
}
// <RBQFetchedResultsControllerDelegate>
@objc func controllerWillChangeContent(controller: RBQFetchedResultsController!) {
self.delegate.controllerWillChangeContent(controller)
}
@objc func controller(controller: RBQFetchedResultsController!, didChangeObject anObject: RBQSafeRealmObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
self.delegate.controller(controller, didChangeObject: anObject, atIndexPath: indexPath, forChangeType: type, newIndexPath: newIndexPath)
}
@objc func controller(controller: RBQFetchedResultsController!, didChangeSection section: RBQFetchedResultsSectionInfo!, atIndex sectionIndex: UInt, forChangeType type: NSFetchedResultsChangeType) {
self.delegate.controller(controller, didChangeSection: section, atIndex: sectionIndex, forChangeType: type)
}
@objc func controllerDidChangeContent(controller: RBQFetchedResultsController!) {
self.delegate.controllerDidChangeContent(controller)
}
} | mit | bc6f9f6a7494aac0407b9947fdb7f435 | 39.257757 | 439 | 0.713701 | 5.552008 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/AssetManager+Asset.swift | 1 | 2460 | //
// AssetManager+Asset.swift
// HXPHPickerExample
//
// Created by Slience on 2020/12/29.
// Copyright © 2020 Silence. All rights reserved.
//
import UIKit
import Photos
public extension AssetManager {
/// 根据 Asset 的本地唯一标识符获取 Asset
/// - Parameter withLocalIdentifiers: 本地唯一标识符
/// - Returns: 对应获取的 PHAsset
static func fetchAssets(
withLocalIdentifiers: [String]
) -> PHFetchResult<PHAsset> {
PHAsset.fetchAssets(
withLocalIdentifiers: withLocalIdentifiers,
options: nil
)
}
/// 根据 Asset 的本地唯一标识符获取 Asset
/// - Parameter withLocalIdentifiers: 本地唯一标识符
/// - Returns: 对应获取的 PHAsset
static func fetchAsset
(withLocalIdentifier: String
) -> PHAsset? {
return fetchAssets(
withLocalIdentifiers: [withLocalIdentifier]
).firstObject
}
/// 根据下载获取的信息判断资源是否存在iCloud上
/// - Parameter info: 下载获取的信息
static func assetIsInCloud(
for info: [AnyHashable: Any]?
) -> Bool {
if let info = info, info.inICloud {
return true
}
return false
}
/// 判断资源是否取消了下载
/// - Parameter info: 下载获取的信息
static func assetCancelDownload(
for info: [AnyHashable: Any]?
) -> Bool {
if let info = info, info.isCancel {
return true
}
return false
}
/// 判断资源是否下载错误
/// - Parameter info: 下载获取的信息
static func assetDownloadError(
for info: [AnyHashable: Any]?
) -> Bool {
if let info = info, info.isError {
return true
}
return false
}
/// 判断资源下载得到的是否为退化的
/// - Parameter info: 下载获取的信息
static func assetIsDegraded(
for info: [AnyHashable: Any]?
) -> Bool {
if let info = info, info.isDegraded {
return true
}
return false
}
/// 判断资源是否下载完成
/// - Parameter info: 下载获取的信息
static func assetDownloadFinined(
for info: [AnyHashable: Any]?
) -> Bool {
if let info = info, info.downloadFinined {
return true
}
return false
}
}
| mit | 03ead7e1e3e4bf64ab7c31dc1f6b726d | 22.791209 | 55 | 0.567667 | 4.373737 | false | false | false | false |
XWebView/XWebView | XWebViewTests/XWVTestCase.swift | 2 | 3364 | /*
Copyright 2015 XWebView
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 WebKit
import XCTest
import XWebView
extension XCTestExpectation : XWVScripting {
public class func isSelectorExcludedFromScript(selector: Selector) -> Bool {
return selector != #selector(XCTestExpectation.fulfill) &&
selector != #selector(NSObject.description as () -> String)
}
public class func isKeyExcludedFromScript(name: UnsafePointer<Int8>) -> Bool {
return true
}
}
class XWVTestCase : XCTestCase, WKNavigationDelegate {
var webview: WKWebView!
private let namespaceForExpectation = "xwvexpectations"
private var onReady: ((WKWebView)->Void)?
override func setUp() {
super.setUp()
let source = "function fulfill(name){\(namespaceForExpectation)[name].fulfill();}\n" +
"function expectation(name){return \(namespaceForExpectation)[name];}\n"
let script = WKUserScript(
source: source,
injectionTime: WKUserScriptInjectionTime.atDocumentStart,
forMainFrameOnly: true)
webview = WKWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
webview.configuration.userContentController.addUserScript(script)
webview.navigationDelegate = self
}
override func tearDown() {
webview = nil
super.tearDown()
}
override func expectation(description: String) -> XCTestExpectation {
let e = super.expectation(description: description)
webview.loadPlugin(e, namespace: "\(namespaceForExpectation).\(description)")
return e
}
override func waitForExpectations(timeout: TimeInterval = 15, handler: XCWaitCompletionHandler? = nil) {
super.waitForExpectations(timeout: timeout, handler: handler)
}
func loadPlugin(_ object: NSObject, namespace: String, script: String) {
loadPlugin(object, namespace: namespace, script: script, onReady: nil)
}
func loadPlugin(_ object: NSObject, namespace: String, script: String, onReady: ((WKWebView)->Void)?) {
webview.loadPlugin(object, namespace: namespace)
let html = "<html><script type='text/javascript'>\(script)</script></html>"
loadHTML(html, onReady: onReady);
}
func loadHTML(_ content: String, onReady: ((WKWebView)->Void)?) {
self.onReady = onReady
webview.loadHTMLString(content, baseURL: nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
onReady?(webView)
}
}
class XWVTestCaseTest : XWVTestCase {
class Plugin : NSObject {
}
func testXWVTestCase() {
let desc = "selftest"
_ = expectation(description: desc)
loadPlugin(Plugin(), namespace: "xwvtest", script: "fulfill('\(desc)');")
waitForExpectations()
}
}
| apache-2.0 | bbe405e2c18bb1f416cb53fe2c152a20 | 36.377778 | 108 | 0.685791 | 4.833333 | false | true | false | false |
jregnauld/SwiftyInstagram | Example/Tests/Manager/LoginManagerTests.swift | 1 | 3325 | //
// LoginManagerTests.swift
// SwiftyInstagram
//
// Created by Julien Regnauld on 8/11/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import SwiftyInstagram
import Quick
import Nimble
class LoginManagerTests: QuickSpec {
override func spec() {
beforeEach {
let client = Client(clientID: "toto", redirectURL: "http://toto.com/titi")
let configuration = Configuration(client: client)
MockSession.setupSharedSessionWithConfiguration(configuration)
}
afterEach{
MockSession.destroy()
}
describe("Login manager Tests") {
it("will log in to Instagram with success") {
let authorizationViewController = MockAuthorizationViewController(authorizationURL: MockSession.sharedSession().authorizationURL, redirectURL: MockSession.sharedSession().redirectURL)
let loginManager = LoginManager(session: MockSession.sharedSession(), authorizationViewController: authorizationViewController)
var isSuccess = false
loginManager.loginFromViewController(UIViewController(), completed: { (result) in
switch result {
case .success():
isSuccess = true
case .failure(_):
fail()
}
})
authorizationViewController.successAnswer()
expect(isSuccess) == true
expect(MockSession.sharedSession().getAccessToken()) != nil
}
it("will fail to log in") {
let authorizationViewController = MockAuthorizationViewController(authorizationURL: MockSession.sharedSession().authorizationURL, redirectURL: MockSession.sharedSession().redirectURL)
let loginManager = LoginManager(session: MockSession.sharedSession(), authorizationViewController: authorizationViewController)
var isFailure = false
loginManager.loginFromViewController(UIViewController(), completed: { (result) in
switch result {
case .success():
fail()
case .failure(let error):
expect(error.type) == "access_denied"
expect(error.reason) == "user_denied"
expect(error.description) == "The+user+denied+your+request."
isFailure = true
}
})
authorizationViewController.failureAnswer()
expect(isFailure) == true
expect(MockSession.sharedSession().getAccessToken()).to(beNil())
}
it("will ignore webview answer when it's the same that the authorization url") {
let authorizationViewController = MockAuthorizationViewController(authorizationURL: MockSession.sharedSession().authorizationURL, redirectURL: MockSession.sharedSession().redirectURL)
let loginManager = LoginManager(session: MockSession.sharedSession(), authorizationViewController: authorizationViewController)
var hasCheckURL = false
loginManager.loginFromViewController(UIViewController(), completed: { (result) in
hasCheckURL = true
switch result {
case .success():
fail()
case .failure(_):
fail()
}
})
authorizationViewController.authorizationURLAnswer()
expect(hasCheckURL) == false
expect(MockSession.sharedSession().getAccessToken()).to(beNil())
}
}
}
}
| mit | f1a2ae3818921cafe9c7cb51f9d42add | 40.55 | 192 | 0.669976 | 5.567839 | false | false | false | false |
FuzzyHobbit/bitcoin-swift | BitcoinSwiftTests/SecureDataTests.swift | 2 | 727 | //
// SecureDataTests.swift
// BitcoinSwift
//
// Created by Kevin Greene on 1/3/15.
// Copyright (c) 2015 DoubleSha. All rights reserved.
//
import BitcoinSwift
import XCTest
class SecureDataTests: XCTestCase {
func testSubRange() {
let bytes: [UInt8] = [0x1, 0x2, 0x3, 0x4]
let leftBytes: [UInt8] = [0x1, 0x2]
let rightBytes: [UInt8] = [0x3, 0x4]
let data = SecureData(bytes: bytes, length: UInt(bytes.count))
let leftData = SecureData(bytes: leftBytes, length: UInt(leftBytes.count))
let rightData = SecureData(bytes: rightBytes, length: UInt(rightBytes.count))
XCTAssertEqual(data[0..<2], leftData)
XCTAssertEqual(data[2..<4], rightData)
XCTAssertEqual(data[0..<4], data)
}
}
| apache-2.0 | 55788d0531711a30b8334cab196828c4 | 28.08 | 81 | 0.68088 | 3.231111 | false | true | false | false |
corchwll/amos-ss15-proj5_ios | MobileTimeAccounting/UserInterface/Projects/NewProjectTableViewController.swift | 1 | 7175 | /*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import MapKit
protocol NewProjectDelegate
{
func didAddNewProject()
}
class NewProjectTableViewController: UITableViewController, CLLocationManagerDelegate
{
@IBOutlet weak var projectIdTextField: UITextField!
@IBOutlet weak var projectNameTextField: UITextField!
@IBOutlet weak var projectFinalDateTextField: UITextField!
@IBOutlet weak var projectLatitudeTextField: UITextField!
@IBOutlet weak var projectLongitudeTextField: UITextField!
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var locationProcessIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var findLocationButton: UIButton!
var validProjectId = false
var delegate: NewProjectDelegate!
let datePicker = UIDatePicker()
let dateFormatter = NSDateFormatter()
let locationManager = CLLocationManager()
/*
iOS life-cycle function, called when view did load. Sets up date formatter and input view for date picker.
@methodtype Hook
@pre -
@post -
*/
override func viewDidLoad()
{
super.viewDidLoad()
setUpDateFormatter()
setUpDatePickerInputView()
setUpLocationManager()
refreshDoneButtonState()
}
/*
Function is called to set up date formatter.
@methodtype Command
@pre -
@post Date formatter has been set up
*/
func setUpDateFormatter()
{
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
}
/*
Function is called to set up date picker input view.
@methodtype Command
@pre -
@post Input view has been set up
*/
func setUpDatePickerInputView()
{
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: Selector("datePickerDidChange"), forControlEvents: UIControlEvents.ValueChanged)
projectFinalDateTextField.inputView = datePicker
}
/*
@methodtype
@pre
@post
*/
func setUpLocationManager()
{
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
/*
Function is called when date picker has changed. Sets text field to selected date.
@methodtype Hook
@pre -
@post Final date text field has been set to selected date
*/
func datePickerDidChange()
{
projectFinalDateTextField.text = dateFormatter.stringFromDate(datePicker.date)
}
/*
iOS listener function. Called when editing project id, refreshes 'done'-button state.
@methodtype Command
@pre -
@post -
*/
@IBAction func projectIdTimeChanged(sender: AnyObject)
{
if Project.isValidId(projectIdTextField.text)
{
projectIdTextField.textColor = UIColor.blackColor()
validProjectId = true
}
else
{
projectIdTextField.textColor = UIColor.redColor()
validProjectId = false
}
refreshDoneButtonState()
}
/*
iOS listener function. Called when editing project name, refreshes 'done'-button state.
@methodtype Command
@pre -
@post -
*/
@IBAction func projectNameChanged(sender: AnyObject)
{
refreshDoneButtonState()
}
/*
Function for enabling 'done'-button. Button will be enabled when all mandatory text fiels are filled.
@methodtype Command
@pre Text field are not empty
@post Button will be enabled
*/
func refreshDoneButtonState()
{
var isValid = true
isValid = isValid && validProjectId
isValid = isValid && !projectNameTextField.text.isEmpty
doneButton.enabled = isValid
}
/*
Determines current location and fills in coordinates into ui. Start process indicator animation and hides button.
@methodtype Command
@pre Location manager has been initialized
@post Finding location process is triggered
*/
@IBAction func getCurrentLocation(sender: AnyObject)
{
locationManager.startUpdatingLocation()
findLocationButton.hidden = true
locationProcessIndicatorView.startAnimating()
}
/*
Function is called when location is found. Updated coordinates text fields and stops process indicator animation.
Also stops the process of finding new locations.
@methodtype Command
@pre Location was found
@post Coordinates has been printed
*/
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
let location = locations.last as! CLLocation
projectLatitudeTextField.text = "\(location.coordinate.latitude)"
projectLongitudeTextField.text = "\(location.coordinate.longitude)"
locationManager.stopUpdatingLocation()
locationProcessIndicatorView.stopAnimating()
findLocationButton.hidden = false
}
/*
Called when new project should be added. Stores new project into sqlite database by using
project data access object.
@methodtype Command
@pre Valid user input
@post New project added and current view dismissed
*/
@IBAction func addProject(sender: AnyObject)
{
let newProject = Project(id: projectIdTextField.text, name: projectNameTextField.text, finalDate: dateFormatter.dateFromString(projectFinalDateTextField.text), latitude: projectLatitudeTextField.text.toDouble(), longitude: projectLongitudeTextField.text.toDouble())
projectDAO.addProject(newProject)
delegate.didAddNewProject()
dismissViewControllerAnimated(true, completion: {})
}
/*
iOS listener function. Called when pressing 'cancel'-button, dismissing current view.
@methodtype Command
@pre -
@post -
*/
@IBAction func cancel(sender: AnyObject)
{
self.dismissViewControllerAnimated(true, completion: {})
}
}
| agpl-3.0 | 0a21ecc8d8dc6ece7769efbabb51bfcd | 28.771784 | 273 | 0.653937 | 5.694444 | false | false | false | false |
royratcliffe/Snippets | Sources/UIColor+Snippets.swift | 1 | 3381 | // Snippets UIColor+Snippets.swift
//
// Copyright © 2015, 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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
extension UIColor {
/// - returns: a UIColor based on a HTML colour string. Answers `nil` if the
/// given string cannot convert to a colour because there are not enough, or
/// too many, hexadecimal digits.
///
/// Implementation uses a regular expression to extract all the hexadecimal
/// digits, ignoring hash prefixes and whitespace if any. Aborts if the
/// regular expression for a hexadecimal digit fails to compile, logging the
/// expression compilation error to the system log.
public class func from(html string: String) -> UIColor? {
var expression: NSRegularExpression
do {
expression = try NSRegularExpression(pattern: "[0-9a-f]", options: .caseInsensitive)
} catch {
(error as NSError).log()
abort()
}
let range = NSRange(location: 0, length: string.characters.count)
let matches = expression.matches(in: string, options: [], range: range)
let digits = matches.map { (match) -> String in
(string as NSString).substring(with: match.range)
}
var digitPairs: [String]
switch digits.count {
case 3, 4:
// rgb, argb
digitPairs = digits.map { (digit) -> String in
digit + digit
}
case 6, 8:
// rrggbb, aarrggbb
digitPairs = (0..<(digits.count >> 1)).map({ (index) -> String in
digits[index << 1] + digits[(index << 1) + 1]
})
default:
return nil
}
let components = digitPairs.map { (digitPair) -> CGFloat in
var result: UInt32 = 0
// Ignore the fact that the scanner can answer false. It never will
// because we already know that the scanner will always see hexadecimal,
// nothing more, nothing less.
Scanner(string: digitPair).scanHexInt32(&result)
return CGFloat(result) / 255.0
}
var floats = components.makeIterator()
let alpha = components.count == 4 ? floats.next()! : 1.0
let red = floats.next()!
let green = floats.next()!
let blue = floats.next()!
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
| mit | 51c5779cfb8f307478e7129380695ac3 | 40.62963 | 90 | 0.669336 | 4.362225 | false | false | false | false |
Rag0n/QuNotes | iOS-UI.playground/Pages/Note.xcplaygroundpage/Contents.swift | 1 | 2410 | import UIKit
import PlaygroundSupport
import QuNotesUI
AppEnvironment.push(environment: Environment(language: .en))
let controller = NoteViewController { (event) in print(event) }
let navigationController = UINavigationController(rootViewController: controller)
ThemeExecuter.applyTheme(forView: navigationController.view)
let (parent, _) = playgroundControllers(device: .phone4inch,
orientation: .portrait,
child: navigationController)
let frame = parent.view.frame
PlaygroundPage.current.liveView = parent
parent.view.frame = frame
controller.perform(effect: .updateTitle("Title"))
controller.perform(effect: .addTag("first tag"))
controller.perform(effect: .addTag("second tag"))
controller.perform(effect: .updateCells(["cell1", "cell2"]))
//delay(for: .seconds(1)) {
// controller.perform(effect: .addCell(index: 1, cells: ["cell1", "cell3", "cell2"]))
//}
//
//delay(for: .seconds(2)) {
// controller.perform(effect: .removeCell(index: 1, cells: ["cell1", "cell2"]))
//}
//
//delay(for: .seconds(3)) {
// let cell1 = """
// Lorem Ipsum - это текст-рыба, часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной рыбой для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.
// """
// controller.perform(effect: .updateCell(index: 0, cells: [cell1, "cell2"]))
//}
//
//delay(for: .seconds(4)) {
// controller.perform(effect: .updateCell(index: 0, cells: ["cell1", "cell2"]))
//}
| gpl-3.0 | 25ac9e307939c2af51ecf3f574a97324 | 47.170732 | 639 | 0.714937 | 2.969925 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Repository/BFRepoListController.swift | 1 | 5839 | //
// BFRepoListController.swift
// BeeFun
//
// Created by wenghengcong on 16/1/30.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import UIKit
import Moya
import Foundation
import MJRefresh
class BFRepoListController: BFBaseViewController {
//incoming var
var dic: [String: String]?
var username: String? //用户login,必须有
var viewType: String? //有myrepositories,就是用户创建维护仓库,另外,forked表示,fork的仓库
var reposData: [ObjRepos] = []
var reposPageVal = 1
var reposPerpage = 15
var typeVal: String = "all"
var sortVal: String = "created"
var directionVal: String = "desc"
override func viewDidLoad() {
self.title = "Repositories".localized
super.viewDidLoad()
rvc_addNaviBarButtonItem()
rvc_setupTableView()
rvc_selectDataSource()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func leftItemAction(_ sender: UIButton?) {
_ = self.navigationController?.popViewController(animated: true)
}
func rvc_addNaviBarButtonItem() {
/*
let btnName = UIButton()
btnName.setImage(UIImage(named: "bubble_consulting_chat-512"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("tvc_rightButtonTouch"), forControlEvents: .TouchUpInside)
//.... Set Right/Left Bar Button item
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = btnName
self.navigationItem.rightBarButtonItem = rightBarButton
*/
}
func rvc_rightButtonTouch() {
}
func rvc_setupTableView() {
self.view.addSubview(tableView)
self.tableView.frame = CGRect(x: 0, y: uiTopBarHeight, width: ScreenSize.width, height: ScreenSize.height-uiTopBarHeight)
self.automaticallyAdjustsScrollViewInsets = false
}
// 顶部刷新
override func headerRefresh() {
super.headerRefresh()
reposPageVal = 1
rvc_selectDataSource()
}
// 底部刷新
override func footerRefresh() {
super.footerRefresh()
reposPageVal += 1
rvc_selectDataSource()
}
func rvc_updateViewContent() {
self.tableView.reloadData()
}
// MARK: - request for repos
override func reconnect() {
super.reconnect()
rvc_selectDataSource()
}
func rvc_selectDataSource() {
if self.viewType == "myrepositories" {
rvc_getMyReposRequest()
} else if self.viewType == "forked" {
rvc_getForkedReposRequst()
} else {
rvc_getMyReposRequest()
}
}
func rvc_getMyReposRequest() {
if username == nil {
return
}
let hud = JSMBHUDBridge.showHud(view: self.view)
Provider.sharedProvider.request(.userRepos(username: username! ,page:self.reposPageVal, perpage:self.reposPerpage, type:self.typeVal, sort:self.sortVal, direction:self.directionVal ) ) { (result) -> Void in
hud.hide(animated: true)
switch result {
case let .success(response):
do {
let repos: [ObjRepos] = try response.mapArray(ObjRepos.self)
if self.reposPageVal == 1 {
self.reposData.removeAll()
self.reposData = repos
} else {
self.reposData += repos
}
self.rvc_updateViewContent()
} catch {
}
case .failure:
break
}
}
}
func rvc_getForkedReposRequst() {
}
}
extension BFRepoListController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.reposData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
var cellId = ""
if self.viewType == "myrepositories" {
cellId = "BFRepositoryTypeSecCellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFRepositoryTypeSecCell
if cell == nil {
cell = (BFRepositoryTypeSecCell.cellFromNibNamed("BFRepositoryTypeSecCell") as? BFRepositoryTypeSecCell)
}
cell?.setBothEndsLines(row, all:reposData.count)
let repos = self.reposData[row]
cell!.objRepos = repos
return cell!
}
cellId = "BFRepositoryTypeThirdCellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFRepositoryTypeThirdCell
if cell == nil {
cell = (BFRepositoryTypeThirdCell.cellFromNibNamed("BFRepositoryTypeThirdCell") as? BFRepositoryTypeThirdCell)
}
cell?.setBothEndsLines(row, all: reposData.count)
let repos = self.reposData[row]
cell!.objRepos = repos
return cell!
}
}
extension BFRepoListController {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let repos = self.reposData[indexPath.row]
JumpManager.shared.jumpReposDetailView(repos: repos, from: .other)
}
}
| mit | bf66c471f198b3ec2f21d0235466555f | 26.980583 | 214 | 0.615198 | 4.626003 | false | false | false | false |
encero/heurary | heurary/BookList/UserBooksViewController.swift | 1 | 3203 | //
// UserBooksViewController.swift
// heurary
//
// Created by vojtech on 25/05/16.
//
//
import UIKit
import SnapKit
import Font_Awesome_Swift
class UserBooksViewController: UIViewController {
init() {
manager = BookManager.sharedInstance()
storage = manager.getStorage()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Initializer not supported")
}
var arrayOfBooks = [Book]()
let storage: BookStorage
let manager: BookManager
override func loadView() {
super.loadView()
title = "Moje pujcene"
view.backgroundColor = .whiteColor()
// TableView
let tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(BookTableCell.self, forCellReuseIdentifier: BookTableCell.identifier)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80
view.addSubview(tableView)
tableView.snp_makeConstraints { (make) in
make.edges.equalTo(view)
}
// // SearchController
// let searchController = UISearchController(searchResultsController: nil)
//
// searchController.searchResultsUpdater = self
// searchController.searchBar.sizeToFit() // http://useyourloaf.com/blog/search-bar-not-showing-without-a-scope-bar/
//
// tableView.tableHeaderView = searchController.searchBar
// History Button
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: self, action: #selector(UserBooksViewController.actionUserHistory))
navigationItem.rightBarButtonItem?.setFAIcon(.FAHistory, iconSize: 20)
let userName = GIDSignIn.sharedInstance().currentUser.profile.name
manager.loadBooks { [weak self] in
guard let `self` = self else { return /* Controller is gone, return */ }
self.arrayOfBooks = [Book]()
for book in self.storage.books
{
for holder in book.holders {
if (holder.user == userName) {
self.arrayOfBooks.append(book)
}
}
}
tableView.reloadData()
}
}
func actionUserHistory() {
manager.loadUserHistory { [weak self] in
guard let `self` = self else { return }
self.navigationController?.pushViewController(BookHistoryController(withStorage: self.storage), animated: true)
}
}
}
extension UserBooksViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfBooks.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(BookTableCell.identifier, forIndexPath: indexPath) as! BookTableCell
cell.loadBook(arrayOfBooks[indexPath.row])
cell.setNeedsLayout()
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
navigationController?.pushViewController(BookDetailViewController(withBook: arrayOfBooks[indexPath.row]), animated: true)
}
}
extension UserBooksViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
// TOOD: implement search
}
} | mit | 169d0dc84c17ea5a1aa732b05d38f5e7 | 26.384615 | 155 | 0.758352 | 4.122265 | false | false | false | false |
garricn/CopyPaste | CopyPasteUITests/AppLaunchUITestCase.swift | 1 | 2238 | //
// Copyright © 2017 SwiftCoders. All rights reserved.
//
@testable import CopyPaste
import XCTest
final class AppLaunchUITestCase: UITestCase {
func test_Fresh_Install_Launch() {
resetDefaultsContext()
resetItemsContext()
app.launch()
app.buttons["Get Started"].tap()
assertAppIsDisplayingAllItems()
assertAppIsDisplayingAddItemCell()
app.terminate()
removeDefaultsEnvironmentVariable()
removeItemsEnvironmentVariable()
app.launch()
assertAppIsDisplayingAllItems()
assertAppIsDisplayingAddItemCell()
}
func testSecondAppLaunch() {
addCodableEnvironmentVariable(Defaults(showWelcome: false), forName: Globals.EnvironmentVariables.defaults)
resetItemsContext()
app.launch()
assertAppIsDisplayingAllItems()
assertAppIsDisplayingAddItemCell()
removeDefaultsEnvironmentVariable()
removeItemsEnvironmentVariable()
}
func testLaunchWithData() {
let defaults = Defaults(showWelcome: false)
addCodableEnvironmentVariable(defaults, forName: Globals.EnvironmentVariables.defaults)
let items = [Item(body: "Body", copyCount: 0, title: "Title")]
addCodableEnvironmentVariable(items, forName: Globals.EnvironmentVariables.items)
app.launch()
assertAppIsDisplayingAllItems()
assertApp(isDisplaying: app.cells.staticTexts["Body"])
removeDefaultsEnvironmentVariable()
removeItemsEnvironmentVariable()
}
func test_NewItem_ShortcutItem_Launch() {
let defaults = Defaults(showWelcome: false)
addCodableEnvironmentVariable(defaults, forName: Globals.EnvironmentVariables.defaults)
let key = Globals.EnvironmentVariables.shortcutItemKey
app.launchEnvironment[key] = Globals.ShortcutItemTypes.newItem
app.launch()
let element = app.navigationBars["Add Item"]
assertApp(isDisplaying: element)
app.launchEnvironment.removeValue(forKey: key)
removeDefaultsEnvironmentVariable()
removeItemsEnvironmentVariable()
}
}
| mit | 9bfaa8a3de02ba7552daaed147ea26e8 | 29.643836 | 115 | 0.670988 | 5.442822 | false | true | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/svg/SVGConstants.swift | 1 | 5717 | open class SVGConstants {
open static let colorList = [
"aliceblue": 0xf0f8ff,
"antiquewhite": 0xfaebd7,
"aqua": 0x00ffff,
"aquamarine": 0x7fffd4,
"azure": 0xf0ffff,
"beige": 0xf5f5dc,
"bisque": 0xffe4c4,
"black": 0x000000,
"blanchedalmond": 0xffebcd,
"blue": 0x0000ff,
"blueviolet": 0x8a2be2,
"brown": 0xa52a2a,
"burlywood": 0xdeb887,
"cadetblue": 0x5f9ea0,
"chartreuse": 0x7fff00,
"chocolate": 0xd2691e,
"coral": 0xff7f50,
"cornflowerblue": 0x6495ed,
"cornsilk": 0xfff8dc,
"crimson": 0xdc143c,
"cyan": 0x00ffff,
"darkblue": 0x00008b,
"darkcyan": 0x008b8b,
"darkgoldenrod": 0xb8860b,
"darkgray": 0xa9a9a9,
"darkgreen": 0x006400,
"darkgrey": 0xa9a9a9,
"darkkhaki": 0xbdb76b,
"darkmagenta": 0x8b008b,
"darkolivegreen": 0x556b2f,
"darkorange": 0xff8c00,
"darkorchid": 0x9932cc,
"darkred": 0x8b0000,
"darksalmon": 0xe9967a,
"darkseagreen": 0x8fbc8f,
"darkslateblue": 0x483d8b,
"darkslategray": 0x2f4f4f,
"darkslategrey": 0x2f4f4f,
"darkturquoise": 0x00ced1,
"darkviolet": 0x9400d3,
"deeppink": 0xff1493,
"deepskyblue": 0x00bfff,
"dimgray": 0x696969,
"dimgrey": 0x696969,
"dodgerblue": 0x1e90ff,
"firebrick": 0xb22222,
"floralwhite": 0xfffaf0,
"forestgreen": 0x228b22,
"fuchsia": 0xff00ff,
"gainsboro": 0xdcdcdc,
"ghostwhite": 0xf8f8ff,
"gold": 0xffd700,
"goldenrod": 0xdaa520,
"gray": 0x808080,
"green": 0x008000,
"greenyellow": 0xadff2f,
"grey": 0x808080,
"honeydew": 0xf0fff0,
"hotpink": 0xff69b4,
"indianred": 0xcd5c5c,
"indigo": 0x4b0082,
"ivory": 0xfffff0,
"khaki": 0xf0e68c,
"lavender": 0xe6e6fa,
"lavenderblush": 0xfff0f5,
"lawngreen": 0x7cfc00,
"lemonchiffon": 0xfffacd,
"lightblue": 0xadd8e6,
"lightcoral": 0xf08080,
"lightcyan": 0xe0ffff,
"lightgoldenrodyellow": 0xfafad2,
"lightgray": 0xd3d3d3,
"lightgreen": 0x90ee90,
"lightgrey": 0xd3d3d3,
"lightpink": 0xffb6c1,
"lightsalmon": 0xffa07a,
"lightseagreen": 0x20b2aa,
"lightskyblue": 0x87cefa,
"lightslategray": 0x778899,
"lightslategrey": 0x778899,
"lightsteelblue": 0xb0c4de,
"lightyellow": 0xffffe0,
"lime": 0x00ff00,
"limegreen": 0x32cd32,
"linen": 0xfaf0e6,
"magenta": 0xff00ff,
"maroon": 0x800000,
"mediumaquamarine": 0x66cdaa,
"mediumblue": 0x0000cd,
"mediumorchid": 0xba55d3,
"mediumpurple": 0x9370db,
"mediumseagreen": 0x3cb371,
"mediumslateblue": 0x7b68ee,
"mediumspringgreen": 0x00fa9a,
"mediumturquoise": 0x48d1cc,
"mediumvioletred": 0xc71585,
"midnightblue": 0x191970,
"mintcream": 0xf5fffa,
"mistyrose": 0xffe4e1,
"moccasin": 0xffe4b5,
"navajowhite": 0xffdead,
"navy": 0x000080,
"oldlace": 0xfdf5e6,
"olive": 0x808000,
"olivedrab": 0x6b8e23,
"orange": 0xffa500,
"orangered": 0xff4500,
"orchid": 0xda70d6,
"palegoldenrod": 0xeee8aa,
"palegreen": 0x98fb98,
"paleturquoise": 0xafeeee,
"palevioletred": 0xdb7093,
"papayawhip": 0xffefd5,
"peachpuff": 0xffdab9,
"peru": 0xcd853f,
"pink": 0xffc0cb,
"plum": 0xdda0dd,
"powderblue": 0xb0e0e6,
"purple": 0x800080,
"rebeccapurple": 0x663399,
"red": 0xff0000,
"rosybrown": 0xbc8f8f,
"royalblue": 0x4169e1,
"saddlebrown": 0x8b4513,
"salmon": 0xfa8072,
"sandybrown": 0xf4a460,
"seagreen": 0x2e8b57,
"seashell": 0xfff5ee,
"sienna": 0xa0522d,
"silver": 0xc0c0c0,
"skyblue": 0x87ceeb,
"slateblue": 0x6a5acd,
"slategray": 0x708090,
"slategrey": 0x708090,
"snow": 0xfffafa,
"springgreen": 0x00ff7f,
"steelblue": 0x4682b4,
"tan": 0xd2b48c,
"teal": 0x008080,
"thistle": 0xd8bfd8,
"tomato": 0xff6347,
"turquoise": 0x40e0d0,
"violet": 0xee82ee,
"wheat": 0xf5deb3,
"white": 0xffffff,
"whitesmoke": 0xf5f5f5,
"yellow": 0xffff00,
"yellowgreen": 0x9acd32
]
open static let moveToAbsolute = "M"
open static let moveToRelative = "m"
open static let lineToAbsolute = "L"
open static let lineToRelative = "l"
open static let lineHorizontalAbsolute = "H"
open static let lineHorizontalRelative = "h"
open static let lineVerticalAbsolute = "V"
open static let lineVerticalRelative = "v"
open static let curveToAbsolute = "C"
open static let curveToRelative = "c"
open static let smoothCurveToAbsolute = "S"
open static let smoothCurveToRelative = "s"
open static let closePathAbsolute = "Z"
open static let closePathRelative = "z"
open static let pathCommands = [
moveToAbsolute,
moveToRelative,
lineToAbsolute,
lineToRelative,
lineHorizontalAbsolute,
lineHorizontalRelative,
lineVerticalAbsolute,
lineVerticalRelative,
curveToAbsolute,
curveToRelative,
smoothCurveToAbsolute,
smoothCurveToRelative,
closePathAbsolute,
closePathRelative
]
}
| mit | d0733f7e0e330c3858238477c2afaf5c | 29.736559 | 48 | 0.570579 | 2.948427 | false | false | false | false |
ZamzamInc/SwiftyPress | Sources/SwiftyPress/Repositories/Taxonomy/Services/TaxonomyFileCache.swift | 1 | 3422 | //
// TaxonomyFileCache.swift
// SwiftyPress
//
// Created by Basem Emara on 2018-06-04.
// Copyright © 2019 Zamzam Inc. All rights reserved.
//
public struct TaxonomyFileCache: TaxonomyCache {
private let seedService: DataSeed
init(seedService: DataSeed) {
self.seedService = seedService
}
}
public extension TaxonomyFileCache {
func fetch(id: Int, completion: @escaping (Result<Term, SwiftyPressError>) -> Void) {
fetch {
// Handle errors
guard case .success = $0 else {
completion(.failure($0.error ?? .unknownReason(nil)))
return
}
// Find match
guard case let .success(item) = $0,
let model = item.first(where: { $0.id == id }) else {
completion(.failure(.nonExistent))
return
}
completion(.success(model))
}
}
func fetch(slug: String, completion: @escaping (Result<Term, SwiftyPressError>) -> Void) {
fetch {
// Handle errors
guard case .success = $0 else {
completion(.failure($0.error ?? .unknownReason(nil)))
return
}
// Find match
guard case let .success(item) = $0,
let model = item.first(where: { $0.slug == slug }) else {
completion(.failure(.nonExistent))
return
}
completion(.success(model))
}
}
}
public extension TaxonomyFileCache {
func fetch(completion: @escaping (Result<[Term], SwiftyPressError>) -> Void) {
seedService.fetch {
guard case let .success(item) = $0 else {
completion(.failure($0.error ?? .unknownReason(nil)))
return
}
completion(.success(item.terms))
}
}
}
public extension TaxonomyFileCache {
func fetch(ids: Set<Int>, completion: @escaping (Result<[Term], SwiftyPressError>) -> Void) {
fetch {
guard case let .success(items) = $0 else {
completion($0)
return
}
let model = ids.reduce(into: [Term]()) { result, next in
guard let element = items.first(where: { $0.id == next }) else { return }
result.append(element)
}
completion(.success(model))
}
}
func fetch(by taxonomy: Taxonomy, completion: @escaping (Result<[Term], SwiftyPressError>) -> Void) {
fetch {
guard case let .success(items) = $0 else {
completion($0)
return
}
completion(.success(items.filter { $0.taxonomy == taxonomy }))
}
}
func fetch(by taxonomies: [Taxonomy], completion: @escaping (Result<[Term], SwiftyPressError>) -> Void) {
fetch {
guard case let .success(items) = $0 else {
completion($0)
return
}
completion(.success(items.filter { taxonomies.contains($0.taxonomy) }))
}
}
}
public extension TaxonomyFileCache {
func getID(bySlug slug: String) -> Int? {
fatalError("Not implemented")
}
}
| mit | 8273903f3232f6e1238abbe57e81f1b9 | 27.991525 | 109 | 0.499269 | 4.660763 | false | false | false | false |
phimage/Arithmosophi | Playgrounds/Arithmosophi.playground/Contents.swift | 1 | 2430 | //: ## Arithmosophi
//: A set of protocols for Arithmetic, Statistics and Logical operations
import Arithmosophi // 1 + 2 + 3 + 4
//: ### Arithmosophi.swift
[1, 2, 3, 4].sum
[1, 2, 3, 4].product // 1 * 2 * 3 * 4
["a", "b", "c", "d"].sum // "abcd" same as joinWithSeparator("")
[["a", "b"], ["c"], ["d"]].sum // ["a","b","c","d"] same as flatMap{$0}
//: ### Arithmos.swift
//[abs(-2.0), floor(1.1), ceil(1.1), round(1.1), fract(1.1)]
[(-2.0).abs(), (1.1).floor(), (1.1).ceil(), (1.1).round(), (1.1).fract()]
fract(1.1)
//[sqrt(2.0), cbrt(2.0), pow(2.0, 0.5)]
[(2.0).sqrt(), (2.0).cbrt(), (2.0).pow(0.5)]
//[exp(1.0), exp2(10.0), log(1.0), log2(1024.0), log10(1000.0), log1p(1.0)]
[(1.0).exp(), (10.0).exp2(), (1.0).log(), (1024.0).log2(), (1000.0).log10(), (1.0).log1p()]
//[cos(1.0), sin(1.0), tan(1.0), hypot(3.0, 4.0), 4.0*atan2(1.0, 1.0)]
[(1.0).cos(), (1.0).sin(), (1.0).tan(), (3.0).hypot(4.0), 4.0*(1.0).atan2(1.0)]
//[cosh(1.0), sinh(1.0), tanh(1.0)]
[(1.0).cosh(), (1.0).sinh(), (1.0).tanh()]
//[asin(0.5), acos(0.1), atan(1.0)]
[(0.5).asin(), (0.1).acos(), (1.0).atan()]
[Double.random(4.0), Double.random(1.0, 2.0), Double.random(1.0...2.0)]
[(1.1).clamp(3.0), (1.1).clamp(2.0, 3.0), (1.1).clamp(2.0...3.0)]
//: ### LogicalOperationsType.swift
var truth: Bool = true
truth &&= false
truth
truth ||= true
truth
//: ### Statheros.swift
//[cos(Double.π_2), sin(Double.π_2), cos(Double.π), sin(Double.π)]
[(Double.π_2).cos(), (Double.π_2).sin(), (Double.π).cos(), (Double.π).sin()]
//[log(Double.e)]
(Double.e).log()
//: ### MesosOros.swift
[1, 2, 3, 4].average // (1 + 2 + 3 + 4) / 4
[1, 11, 19, 4, -7].median // 4
[1.0, 11, 19.5, 4, 12, -7].medianLow // 4
[1, 11, 19, 4, 12, -7].medianHigh // 11
//: ### Sigma.swift
[1.0, 11, 19.5, 4, 12, -7].varianceSample
[1.0, 11, 19.5, 4, 12, -7].variancePopulation
[1.0, 11, 19.5, 4, 12, -7].standardDeviationSample
[1.0, 11, 19.5, 4, 12, -7].standardDeviationPopulation
[1.0, 11, 19.5, 4, 12, -7].skewness // or .moment.skewness
[1.0, 11, 19.5, 4, 12, -7].kurtosis // or .moment.kurtosis
[1, 2, 3.5, 3.7, 8, 12].covarianceSample([0.5, 1, 2.1, 3.4, 3.4, 4])
[1, 2, 3.5, 3.7, 8, 12].covariancePopulation([0.5, 1, 2.1, 3.4, 3.4, 4])
[1, 2, 3.5, 3.7, 8, 12].pearson([0.5, 1, 2.1, 3.4, 3.4, 4])
//: ### Complex.swift
let complex = Complex<Double>(real: 12.0, imaginary: 9.0)
complex.description
let result = complex + 8 // Complex(real: 20, imaginary: 9)
result.description
| mit | 701fdfbcdd21c4e3bacde1bb448a160e | 41.491228 | 91 | 0.547481 | 2.130167 | false | false | false | false |
tskulbru/NBMaterialDialogIOS | Pod/Classes/NBMaterialLoadingDialog.swift | 1 | 4463 | //
// NBMaterialLoadingDialog.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// 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.
/**
A simple loading dialog with text message
*/
@objc open class NBMaterialLoadingDialog : NBMaterialDialog {
open var dismissOnBgTap: Bool = false
internal override var kMinimumHeight: CGFloat {
return 72.0
}
/**
Displays a loading dialog with a loading spinner, and a message
- parameter message: The message displayed to the user while its loading
- returns: The Loading Dialog
*/
@discardableResult
open class func showLoadingDialogWithText(_ windowView: UIView, message: String) -> NBMaterialLoadingDialog {
let containerView = UIView()
let circularLoadingActivity = NBMaterialCircularActivityIndicator()
let loadingLabel = UILabel()
circularLoadingActivity.initialize()
circularLoadingActivity.translatesAutoresizingMaskIntoConstraints = false
circularLoadingActivity.lineWidth = 3.5
circularLoadingActivity.tintColor = NBConfig.AccentColor
containerView.addSubview(circularLoadingActivity)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.font = UIFont.robotoRegularOfSize(14)
loadingLabel.textColor = NBConfig.PrimaryTextDark
loadingLabel.text = message
// TODO: Add support for multiple lines, probably need to fix the dynamic dialog height todo first
loadingLabel.numberOfLines = 1
containerView.addSubview(loadingLabel)
// Setup constraints
let constraintViews = ["spinner": circularLoadingActivity, "label": loadingLabel]
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[spinner(==32)]-16-[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[spinner(==32)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// Center Y needs to be set manually, not through VFL
containerView.addConstraint(
NSLayoutConstraint(
item: circularLoadingActivity,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: containerView,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// Initialize dialog and display
let dialog = NBMaterialLoadingDialog().showDialog(windowView, title: nil, content: containerView)
// Start spinner
circularLoadingActivity.startAnimating()
return dialog
}
/**
We dont want to dismiss the loading dialog when user taps bg, so we override it and do nothing
*/
internal override func tappedBg() {
if dismissOnBgTap {
super.tappedBg()
}
}
}
| mit | 7062b9d91f1f2397cc65a8427e221dae | 42.754902 | 203 | 0.712973 | 5.238263 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Modules/Settings/Cells/SettingCell.swift | 1 | 665 | //
// SettingCell.swift
// SwiftHub
//
// Created by Sygnoos9 on 7/8/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import UIKit
class SettingCell: DefaultTableViewCell {
override func makeUI() {
super.makeUI()
leftImageView.contentMode = .center
leftImageView.cornerRadius = 0
leftImageView.snp.updateConstraints { (make) in
make.size.equalTo(30)
}
detailLabel.isHidden = true
attributedDetailLabel.isHidden = true
secondDetailLabel.textAlignment = .right
textsStackView.axis = .horizontal
textsStackView.distribution = .fillEqually
}
}
| mit | ce609d71c40c56f128cb962f16374e66 | 24.538462 | 59 | 0.656627 | 4.486486 | false | false | false | false |
simeonpp/home-hunt | ios-client/HomeHunt/Models/Extensions/AgentMappings.swift | 1 | 1609 | import Foundation
extension Agent {
convenience init(withDict dict: Dictionary<String, Any>) {
let id = dict["id"] as? Int
let firstName = dict["firstName"] as! String
let lastName = dict["lastName"] as! String
let phone = dict["phone"] as! String
let email = dict["email"] as? String
let company = dict["company"] as? String
let rating = dict["rating"] as! Float
let ratingCount = dict["ratingCount"] as! Int
let website = dict["website"] as? String
var notes: [String] = []
if (dict["notes"] != nil) {
let notesFromDict = dict["notes"] as! [Dictionary<String, Any>]
for note in notesFromDict {
notes.append(note["note"] as! String)
}
}
self.init(withId: id,
andFirstName: firstName,
andLastName: lastName,
andPhone: phone,
andEmail: email,
andCompany: company,
andRating: rating,
andRatingCount: ratingCount,
andWebsite: website,
andNotes: notes)
}
func toDict() -> Dictionary<String, Any> {
return [
"id": self.id,
"firstName": self.firstName,
"lastName": self.lastName,
"phone": self.phone,
"email": self.email,
"company": self.company,
"rating": self.rating,
"ratingCount": self.ratingCount,
"website": self.website
]
}
}
| mit | 4e9123727ead6e302102f71e46655ba1 | 32.520833 | 75 | 0.501554 | 4.650289 | false | false | false | false |
cotkjaer/SilverbackFramework | SilverbackFramework/NotificationHandlerManager.swift | 1 | 1952 | //
// NotificationManager.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 17/07/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import Foundation
/// A handler class to ease the bookkeeping associated with adding closure-based notification handling.
public class NotificationHandlerManager
{
/// The tokens managed by this manager
private var observerTokens = Array<AnyObject>()
private let notificationCenter : NSNotificationCenter
public required init(notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter())
{
self.notificationCenter = notificationCenter
}
deinit
{
deregisterAll()
}
public func deregisterAll()
{
while !observerTokens.isEmpty
{
notificationCenter.removeObserver(observerTokens.removeLast())
}
}
public func registerHandlerForNotification(name: String? = nil,
object: AnyObject? = nil,
queue: NSOperationQueue? = nil,
handler: ((notification: NSNotification) -> ()))
{
observerTokens.append(notificationCenter.addObserverForName(name, object: object, queue: queue, usingBlock: { handler(notification: $0) }))
}
}
public func postNotificationNamed(name: String, object: AnyObject? = nil)
{
NSNotificationCenter.defaultCenter().postNotificationName(name, object: object)
}
public func postNotificationNamed(name: String, object: AnyObject? = nil, keyValuePairs:(NSObject, AnyObject)...)
{
var userInfo = Dictionary<NSObject, AnyObject>()
for (key, value) in keyValuePairs
{
userInfo[key] = value
}
if userInfo.isEmpty
{
NSNotificationCenter.defaultCenter().postNotificationName(name, object: object)
}
else
{
NSNotificationCenter.defaultCenter().postNotificationName(name, object: object, userInfo: userInfo)
}
}
| mit | 0207a1ffa80f4cc630af25a1f7c9706c | 26.857143 | 147 | 0.686667 | 5.145119 | false | false | false | false |
NijiDigital/NetworkStack | Example/MoyaComparison/MoyaComparison/Services/ServicesClients/MoyaVideoWebServiceClient.swift | 1 | 2763 | //
// Copyright 2017 niji
//
// 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 RxSwift
import Moya
struct MoyaVideoWebServiceClient: VideoWebServiceClient {
internal func badAccess() -> Observable<Void> {
// return self.services.videoNetworkStack.sendRequestWithJSONResponse(requestParameters: RequestParameters(method: .get, route: Route.badAccess()))
// .flatMap({ (_, _) -> Observable<Void> in
// return Observable.empty()
// })
return Observable.empty()
}
var services: Services
func fetchAllVideos() -> Observable<[Video]> {
return self.services.customAPIProvider.rx.request(CustomAPI.getVideos())
.mapJSON().asObservable()
.flatMap({ (json: Any) -> Observable<[Video]> in
return self.services.serializationSwiftyJSON.parse(objects: json)
})
}
func fetchVideo(identifier: Int) -> Observable<Video> {
return self.services.customAPIProvider.rx.request(CustomAPI.getVideo(identifier: identifier))
.mapJSON().asObservable()
.flatMap({ (json: Any) -> Observable<Video> in
return self.services.serializationSwiftyJSON.parse(object: json)
})
}
func update(video: Video) -> Observable<Void> {
return self.services.customAPIProvider.rx.request(CustomAPI.putVideo(video: video))
.asObservable()
.flatMap({ _ -> Observable<Void> in
return Observable.empty()
})
}
func add(video: Video) -> Observable<Video> {
return self.services.customAPIProvider.rx.request(CustomAPI.postVideo(video: video))
.mapJSON().asObservable()
.flatMap({ (json: Any) -> Observable<Video> in
return self.services.serializationSwiftyJSON.parse(object: json)
})
}
func deleteVideo(identifier: Int) -> Observable<Void> {
return self.services.customAPIProvider.rx.request(CustomAPI.delVideo(identifier: identifier))
.asObservable()
.flatMap({ _ -> Observable<Void> in
return Observable.empty()
})
}
func fakeVideoToAdd() -> Video {
let video = Video()
video.title = "Moya network stack"
video.creationDate = Date()
video.hasSponsors.value = true
video.likeCounts = 10000
video.statusCode.value = 10
return video
}
}
| apache-2.0 | 99fe73b197bdefb591a7a800c6087008 | 33.111111 | 150 | 0.690916 | 4.18003 | false | false | false | false |
stepanhruda/PostgreSQL-Swift | Tests/QueryResultSpec.swift | 1 | 9806 | import Quick
import Nimble
@testable import PostgreSQL
class QueryResultSpec: QuickSpec {
override func spec() {
describe("rows") {
var connection: Connection!
var connectionErrorMessage: String?
beforeEach {
connectionErrorMessage = nil
do {
connection = try Database.connect()
} catch let error as ConnectionError {
switch error {
case .ConnectionFailed(message: let message):
connectionErrorMessage = message
}
} catch { connectionErrorMessage = "Unknown error" }
let createDatabase =
"CREATE TABLE spec (" +
"int16_column int2," +
"int32_column int4," +
"int64_column int8," +
"text_column text," +
"single_float_column float4," +
"double_float_column float8," +
"boolean_column boolean," +
"raw_byte_column bytea" +
");"
_ = try? connection.execute(Query(createDatabase))
}
afterEach {
_ = try? connection.execute("DROP TABLE spec;")
}
context("without query parameters") {
it("returns a selected a boolean") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (boolean_column) VALUES (true);")
let result = try! connection.execute("SELECT boolean_column FROM spec;")
expect(result.rows[0]["boolean_column"] as? Bool) == true
}
it("returns a selected 16-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int16_column) VALUES (42);")
let result = try! connection.execute("SELECT int16_column FROM spec;")
expect(result.rows[0]["int16_column"] as? Int16) == 42
}
it("returns a selected 32-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int32_column) VALUES (42);")
let result = try! connection.execute("SELECT int32_column FROM spec;")
expect(result.rows[0]["int32_column"] as? Int32) == 42
}
it("returns a selected 64-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int64_column) VALUES (42);")
let result = try! connection.execute("SELECT int64_column FROM spec;")
expect(result.rows[0]["int64_column"] as? Int64) == 42
}
it("returns a selected a string") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (text_column) VALUES ('indigo');")
let result = try! connection.execute("SELECT text_column FROM spec;")
expect(result.rows[0]["text_column"] as? String) == "indigo"
}
it("returns selected raw bytes") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (raw_byte_column) VALUES (E'\\\\xAFFFEF01FF01');")
let result = try! connection.execute("SELECT raw_byte_column FROM spec;")
expect(result.rows[0]["raw_byte_column"] as? [UInt8]) == [175, 255, 239, 1, 255, 1]
}
it("returns a selected a float") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (single_float_column) VALUES (54564.7654);")
let result = try! connection.execute("SELECT single_float_column FROM spec;")
expect(result.rows[0]["single_float_column"] as? Float) == 54564.7654
}
it("returns a selected a double") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (double_float_column) VALUES (4.99);")
let result = try! connection.execute("SELECT double_float_column FROM spec;")
expect(result.rows[0]["double_float_column"] as? Double) == 4.99
}
}
context("with typed query parameters") {
it("returns a selected a boolean") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (boolean_column) VALUES (true);")
let result = try! connection.execute("SELECT boolean_column FROM spec WHERE boolean_column = $1;", parameters: [true])
expect(result.rows[0]["boolean_column"] as? Bool) == true
}
it("returns a selected 16-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int16_column) VALUES (42);")
let result = try! connection.execute("SELECT int16_column FROM spec WHERE int16_column = $1;", parameters: [Int16(42)])
expect(result.rows[0]["int16_column"] as? Int16) == 42
}
it("returns a selected 32-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int32_column) VALUES (42);")
let result = try! connection.execute("SELECT int32_column FROM spec where int32_column = $1;", parameters: [Int32(42)])
expect(result.rows[0]["int32_column"] as? Int32) == 42
}
it("returns a selected 64-bit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int64_column) VALUES (42);")
let result = try! connection.execute("SELECT int64_column FROM spec WHERE int64_column = $1;", parameters: [Int64(42)])
expect(result.rows[0]["int64_column"] as? Int64) == 42
}
it("returns a selected implicit integer") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (int64_column) VALUES (42);")
let result = try! connection.execute("SELECT int64_column FROM spec WHERE int64_column = $1;", parameters: [42])
expect(result.rows[0]["int64_column"] as? Int64) == 42
}
it("returns a selected a string") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (text_column) VALUES ('indigo');")
let result = try! connection.execute("SELECT text_column FROM spec WHERE text_column = $1;", parameters: ["indigo"])
expect(result.rows[0]["text_column"] as? String) == "indigo"
}
//
// it("returns selected raw bytes") {
// guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
//
// _ = try! connection.execute("INSERT INTO spec (raw_byte_column) VALUES (E'\\\\xAFFFEF01FF01');")
//
// let result = try! connection.execute("SELECT raw_byte_column FROM spec WHERE raw_byte_column = $1;", params: [ [175, 255, 239, 1, 255, 1] ])
// expect(result.rows[0]["raw_byte_column"] as? [UInt8]) == [175, 255, 239, 1, 255, 1]
// }
it("returns a selected a float") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (single_float_column) VALUES (54564.7654);")
let result = try! connection.execute("SELECT single_float_column FROM spec WHERE single_float_column BETWEEN $1 AND $2;", parameters: [Float(54564.0), Float(54564.9)])
expect(result.numberOfRows) == 1
}
it("returns a selected a double") {
guard connectionErrorMessage == nil else { fail(connectionErrorMessage!); return }
_ = try! connection.execute("INSERT INTO spec (double_float_column) VALUES (54564.7654);")
let result = try! connection.execute("SELECT double_float_column FROM spec WHERE double_float_column BETWEEN $1 AND $2;", parameters: [54564.7653, 54564.7656])
expect(result.numberOfRows) == 1
}
}
}
}
}
| mit | f02b51f3c14903ae1e30cae8266569a9 | 47.068627 | 187 | 0.534163 | 4.905453 | false | false | false | false |
VicFrolov/Markit | iOS/Markit/Markit/ChatListViewController.swift | 1 | 5674 | //
// ChatViewController.swift
// Markit
//
// Created by Trixie on 11/29/16.
// Copyright © 2016 Victor Frolov. All rights reserved.
//
import UIKit
import Firebase
import PromiseKit
class ChatListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var chatTableView: UITableView!
var conversationKeys = [String]()
var conversationsList = [Conversation]()
var databaseRef: FIRDatabaseReference!
var userRef: FIRDatabaseReference!
var chatRef: FIRDatabaseReference!
var itemRef: FIRDatabaseReference!
var currentUser: String!
override func viewDidLoad() {
super.viewDidLoad()
currentUser = CustomFirebaseAuth().getCurrentUser()
databaseRef = FIRDatabase.database().reference()
userRef = databaseRef.child("users/\(currentUser!)")
chatRef = userRef.child("chats")
itemRef = databaseRef.child("items")
chatTableView.delegate = self
chatTableView.dataSource = self
getMessages()
// conversationsList.sort (by: { $0.lastSent?.compare($1.lastSent!) == .orderedAscending } )
chatTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getMessages() {
chatRef.observe(.value, with: { (snapshot) -> Void in
self.conversationsList = [Conversation]()
if let convoDictWithKeys = snapshot.value as! NSDictionary? {
for key in (convoDictWithKeys.allKeys) {
let convoDict = convoDictWithKeys[key] as! NSDictionary
let conversation = Conversation()
conversation.context = convoDict["context"] as? NSDictionary
conversation.messages = convoDict["messages"] as? NSDictionary
conversation.lastSent = Date().parse(dateString: (conversation.context?["latestPost"] as! String?)!)
self.conversationsList.append(conversation)
}
self.chatTableView.reloadData()
}
})
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversationsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "ChatCell"
let row = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ChatTableViewCell
let defaultImage = "https://media.giphy.com/media/mtaWx98w7mX7y/giphy-facebook_s.jpg"
let conversation = conversationsList[row]
let context = conversation.context!
let messages = conversation.messages!
let lastMessageKey = messages.allKeys[messages.count - 1] as! String
let latestMessage = messages[lastMessageKey] as! NSDictionary
let latestMessageText = latestMessage["text"]
cell.chatUsername?.text = context["otherUsername"] as! String?
cell.lastSent?.text = context["latestPost"] as! String?
cell.chatMessagePreview?.text = latestMessageText as! String?
let itemImageURL = context["itemImageURL"] as? String ?? defaultImage
if let url = URL(string: itemImageURL) {
if let data = NSData(contentsOf: url as URL) {
cell.chatImageView?.image = UIImage(data: data as Data)
// Change images to circles
cell.chatImageView.layer.borderWidth = 1.0
cell.chatImageView.layer.masksToBounds = false
cell.chatImageView.layer.borderColor = UIColor.white.cgColor
cell.chatImageView.layer.cornerRadius = cell.chatImageView.frame.height / 2
cell.chatImageView.clipsToBounds = true
}
}
return cell
}
// MARK: - Table view delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
chatTableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewRecentMessageSegue" {
if let indexPath = chatTableView.indexPathForSelectedRow {
let selectedRow = indexPath.row
let selectedConvo = conversationsList[selectedRow]
let context = selectedConvo.context
let messageVC = segue.destination as! ChatMessageViewController
messageVC.context = context?["conversationID"] as! String?
messageVC.senderId = currentUser
messageVC.itemID = context?["itemID"] as! String?
messageVC.otherUserID = context?["otherUser"] as! String?
let otherUserDefaultValue = context?["otherUser"] as! String?
messageVC.otherUserName = context?["otherUsername"] as! String? ?? otherUserDefaultValue
}
}
}
}
| apache-2.0 | c00798628c5099eb548646a8f9729619 | 39.521429 | 120 | 0.587696 | 5.475869 | false | false | false | false |
xudafeng/ios-app-bootstrap | ios-app-bootstrap/AppDelegate.swift | 1 | 2580 | //
// AppDelegate.swift
// ios-app-bootstrap
//
// Created by xdf on 9/4/15.
// Copyright (c) 2015 open source. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var loginController: LoginViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if (Utils.hasData("login")) {
window?.rootViewController = TabBarController()
} else {
loginController = LoginViewController()
let nav = UINavigationController(rootViewController: loginController!)
window!.rootViewController = nav
}
window?.backgroundColor = UIColor.white;
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 355a883374bfd85db629248f34ae6550 | 45.909091 | 285 | 0.730233 | 5.657895 | false | false | false | false |
iMetalk/TCZKit | TCZKitDemo/TCZPlainViewController.swift | 1 | 1192 | //
// TCZPlainViewController.swift
// TCZKitDemo
//
// Created by WangSuyan on 2016/11/29.
// Copyright © 2016年 WangSuyan. All rights reserved.
//
import UIKit
class TCZPlainViewController: TCZBaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "TCZFirstViewController"
self.isOpendDelete = true
loadData(isGroup: false)
}
override func configureData() {
super.configureData()
for index in 1...10 {
var item: TCZTableViewItem!
if index % 2 == 0 {
item = TCZTableViewItem(type: .Title)
item.title = "Hello world"
}
else{
item = TCZTableViewItem(type: .ImageTitle)
item.title = "Image title"
item.image = UIImage(named: "leftImage")
}
dataArray.append(item)
cellIndentifierSet.insert(item.type.cellName)
}
}
override func tczDidDelete(atIndexPath indexPath: IndexPath) {
tczDeleteLocalData(atIndexPath: indexPath, animation: .left)
}
}
| mit | 3a01c0543b7ff688309c4ae607f32642 | 24.847826 | 68 | 0.560135 | 4.644531 | false | false | false | false |
nodes-vapor/admin-panel | Sources/AdminPanel/Tags/RequireRoleTag.swift | 1 | 1140 | import Leaf
import Authentication
import Sugar
public final class RequireRoleTag<U: AdminPanelUserType>: TagRenderer {
public func render(tag: TagContext) throws -> Future<TemplateData> {
try tag.requireParameterCount(1)
let request = try tag.requireRequest()
let container = try request.privateContainer.make(CurrentUserContainer<U>.self)
let body = try tag.requireBody()
return tag.serializer.serialize(ast: body).map(to: TemplateData.self) { body in
guard
let roleString: String = tag.parameters[0].string,
let requiredRole = U.Role(roleString)
else {
throw tag.error(reason: "Invalid role requirement")
}
// User is either not logged in or not allowed to see content
guard
let userRole = container.user?.role,
userRole >= requiredRole
else {
return TemplateData.string("")
}
let parsedBody = String(data: body.data, encoding: .utf8) ?? ""
return .string(parsedBody)
}
}
}
| mit | 36be5bba59135d8cdd4b0ea6b8a8f103 | 34.625 | 87 | 0.59386 | 4.672131 | false | false | false | false |
larryhou/swift | ColorPicker/ColorPicker/ColorCell.swift | 1 | 2141 | //
// ColorCell.swift
// ColorPicker
//
// Created by larryhou on 22/09/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import Cocoa
class ColorCell: NSCollectionViewItem {
enum InfoStyle: Int {
case hex = 0, float, decimal
}
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var background: NSBox!
var style: InfoStyle = .hex {
didSet { renderStyle() }
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func mouseDown(with event: NSEvent) {
style = InfoStyle(rawValue: (style.rawValue + 1) % 3)!
}
func renderStyle() {
if let items = color.components {
switch style {
case .hex:
label.stringValue = String(format: "#%02X%02X%02X",
Int(round(items[0] * 255)),
Int(round(items[1] * 255)),
Int(round(items[2] * 255)))
case .decimal:
label.stringValue = String(format: "r:%03d g:%03d b:%03d",
Int(round(items[0] * 255)),
Int(round(items[1] * 255)),
Int(round(items[2] * 255)))
case .float:
label.stringValue = String(format: "r:%4.2f g:%4.2f b:%4.2f", items[0], items[1], items[2])
}
}
}
var color: CGColor = CGColor(red: 1, green: 1, blue: 0, alpha: 1) {
didSet {
let optColor = NSColor(cgColor: color)!.usingColorSpace(sharedColorSpace)!
background.borderColor = optColor
background.fillColor = optColor
self.color = optColor.cgColor
style = .hex
if let items = optColor.cgColor.components {
let components = items.map({$0 * 0.75})
label.textColor = NSColor(colorSpace: optColor.colorSpace, components: components, count: components.count)
}
}
}
}
| mit | 51c3fed302dc51804451e9c7212851bd | 31.923077 | 123 | 0.48785 | 4.476987 | false | false | false | false |
matthewpurcell/firefox-ios | Client/Frontend/Browser/FindInPageHelper.swift | 1 | 1775 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
protocol FindInPageHelperDelegate: class {
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int)
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int)
}
class FindInPageHelper: BrowserHelper {
weak var delegate: FindInPageHelperDelegate?
private weak var browser: Browser?
class func name() -> String {
return "FindInPage"
}
required init(browser: Browser) {
self.browser = browser
if let path = NSBundle.mainBundle().pathForResource("FindInPage", ofType: "js"), source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "findInPageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
let data = message.body as! [String: Int]
if let currentResult = data["currentResult"] {
delegate?.findInPageHelper(self, didUpdateCurrentResult: currentResult)
}
if let totalResults = data["totalResults"] {
delegate?.findInPageHelper(self, didUpdateTotalResults: totalResults)
}
}
}
| mpl-2.0 | 1afababf66e2ce6c682e96f15e53260b | 37.586957 | 177 | 0.722254 | 5.251479 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageCodec/RawBitmap/SlowDecode/_channel_to_double.swift | 1 | 7925 | //
// _channel_to_double.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.
//
extension Image {
@inlinable
@inline(__always)
mutating func _decode_channel_to_double(_ bitmap: RawBitmap, _ channel_idx: Int, _ is_opaque: Bool) {
let width = self.width
let height = self.height
guard bitmap.startsRow < height else { return }
let channel = bitmap.channels[channel_idx]
let bytesPerPixel = bitmap.bitsPerPixel >> 3
let bytesPerChannel = channel.bitRange.count >> 3
let channelBytesOffset = channel.bitRange.lowerBound >> 3
let channelBitsShift = channel.bitRange.lowerBound & 7
@inline(__always)
func read_pixel(_ source: UnsafePointer<UInt8>, _ offset: Int, _ i: Int) -> UInt8 {
switch bitmap.endianness {
case .big: return offset == 0 ? source[i] : (source[i] << offset) | (source[i + 1] >> (8 - offset))
case .little: return source[bytesPerPixel - i - 1]
}
}
@inline(__always)
func read_channel(_ source: UnsafePointer<UInt8>, _ offset: Int, _ i: Int, _ bits_count: Int) -> UInt8 {
switch channel.endianness {
case .big: return channelBitsShift + bits_count <= 8 ? read_pixel(source, offset, i + channelBytesOffset) << channelBitsShift : (read_pixel(source, offset, i + channelBytesOffset) << channelBitsShift) | (read_pixel(source, offset, i + 1 + channelBytesOffset) >> (8 - channelBitsShift))
case .little: return read_pixel(source, offset, bytesPerChannel - i - 1 + channelBytesOffset)
}
}
self.withUnsafeMutableTypePunnedBufferPointer(to: Double.self) {
guard var dest = $0.baseAddress else { return }
let row = Pixel.numberOfComponents * width
dest += bitmap.startsRow * row
var data = bitmap.data
var predictor_record: [UInt8] = Array(repeating: 0, count: bytesPerChannel + (channel.bitRange.count & 7 == 0 ? 0 : 1))
predictor_record.withUnsafeMutableBufferPointer { predictor_record in
for _ in bitmap.startsRow..<height {
let _length = min(bitmap.bytesPerRow, data.count)
guard _length != 0 else { return }
data.popFirst(bitmap.bytesPerRow).withUnsafeBufferPointer { _source in
guard let source = _source.baseAddress else { return }
var destination = dest
let dataBitSize = _length << 3
var _bitsOffset = 0
if bitmap.predictor != .none {
memset(predictor_record.baseAddress!, 0, predictor_record.count)
}
for _ in 0..<width {
guard _bitsOffset + bitmap.bitsPerPixel <= dataBitSize else { return }
let _destination = destination + channel.index
let _d: UInt64
switch bitmap.predictor {
case .none:
var bitPattern: UInt64 = 0
for i in 0..<8 {
bitPattern = (bitPattern << 8) | UInt64(read_channel(source + _bitsOffset >> 3, _bitsOffset & 7, i, 8))
}
_d = bitPattern
case .subtract:
var overflow = false
for i in 0..<predictor_record.count {
let byte: UInt8
if i == 0 && channel.bitRange.count & 7 != 0 {
let mask = ~((0xFF as UInt8) >> (channel.bitRange.count & 7))
byte = read_channel(source + _bitsOffset >> 3, _bitsOffset & 7, predictor_record.count - i - 1, channel.bitRange.count & 7) & mask
} else {
byte = read_channel(source + _bitsOffset >> 3, _bitsOffset & 7, predictor_record.count - i - 1, 8)
}
if overflow {
let (_add, _overflow) = predictor_record[i].addingReportingOverflow(1)
(predictor_record[i], overflow) = _add.addingReportingOverflow(byte)
overflow = _overflow || overflow
} else {
(predictor_record[i], overflow) = predictor_record[i].addingReportingOverflow(byte)
}
}
var bitPattern: UInt64 = 0
for byte in predictor_record.reversed().prefix(8) {
bitPattern = (bitPattern << 8) | UInt64(byte)
}
_d = bitPattern
}
switch channel.format {
case .unsigned: _destination.pointee = Image._denormalized(channel.index, Double(_d) / Double(UInt64.max))
case .signed: _destination.pointee = Image._denormalized(channel.index, Double(UInt64(bitPattern: Int64(bitPattern: _d) &- Int64.min)) / Double(UInt64.max))
default: break
}
if is_opaque {
destination[Pixel.numberOfComponents - 1] = 1
}
destination += Pixel.numberOfComponents
_bitsOffset += bitmap.bitsPerPixel
}
dest += row
}
}
}
}
}
}
| mit | 99f44c24eea1b30b3eb8014e84239d90 | 49.158228 | 297 | 0.463091 | 5.577058 | false | false | false | false |
blg-andreasbraun/ProcedureKit | Sources/Network/NetworkSupport.swift | 2 | 8047 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
// MARK: - URLSession
public protocol URLSessionTaskProtocol {
func resume()
func cancel()
}
public protocol URLSessionDataTaskProtocol: URLSessionTaskProtocol { }
public protocol URLSessionDownloadTaskProtocol: URLSessionTaskProtocol { }
public protocol URLSessionUploadTaskProtocol: URLSessionTaskProtocol { }
public protocol URLSessionTaskFactory {
associatedtype DataTask: URLSessionDataTaskProtocol
associatedtype DownloadTask: URLSessionDownloadTaskProtocol
associatedtype UploadTask: URLSessionUploadTaskProtocol
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTask
func downloadTask(with request: URLRequest, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> DownloadTask
func uploadTask(with request: URLRequest, from bodyData: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> UploadTask
}
extension URLSessionTask: URLSessionTaskProtocol { }
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
extension URLSessionDownloadTask: URLSessionDownloadTaskProtocol { }
extension URLSessionUploadTask: URLSessionUploadTaskProtocol { }
extension URLSession: URLSessionTaskFactory { }
extension URL: ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self.init(string: value)!
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(string: value)!
}
public init(stringLiteral value: String) {
self.init(string: value)!
}
}
// MARK: - Input & Output wrapper types
public protocol HTTPPayloadResponseProtocol: Equatable {
associatedtype Payload: Equatable
var payload: Payload? { get }
var response: HTTPURLResponse { get }
}
public struct HTTPPayloadResponse<Payload: Equatable>: HTTPPayloadResponseProtocol {
public static func == (lhs: HTTPPayloadResponse<Payload>, rhs: HTTPPayloadResponse<Payload>) -> Bool {
return lhs.payload == rhs.payload && lhs.response == rhs.response
}
public var payload: Payload?
public var response: HTTPURLResponse
public init(payload: Payload, response: HTTPURLResponse) {
self.payload = payload
self.response = response
}
}
public struct HTTPPayloadRequest<Payload: Equatable>: Equatable {
public static func == (lhs: HTTPPayloadRequest <Payload>, rhs: HTTPPayloadRequest <Payload>) -> Bool {
return lhs.payload == rhs.payload && lhs.request == rhs.request
}
public var request: URLRequest
public var payload: Payload?
public init(payload: Payload? = nil, request: URLRequest) {
self.payload = payload
self.request = request
}
}
// MARK: - Error Handling
struct ProcedureKitNetworkError: Error {
let underlyingError: Error
var errorCode: Int {
return (underlyingError as NSError).code
}
var isTransientError: Bool {
switch errorCode {
case NSURLErrorNetworkConnectionLost:
return true
default:
return false
}
}
var isTimeoutError: Bool {
guard let procedureKitError = underlyingError as? ProcedureKitError else { return false }
guard case .timedOut(with: _) = procedureKitError.context else { return false }
return true
}
var waitForReachabilityChangeBeforeRetrying: Bool {
switch errorCode {
case NSURLErrorNotConnectedToInternet, NSURLErrorInternationalRoamingOff, NSURLErrorCallIsActive, NSURLErrorDataNotAllowed:
return true
default:
return false
}
}
init(error: Error) {
self.underlyingError = error
}
}
struct ProcedureKitNetworkResponse {
let response: HTTPURLResponse?
let error: ProcedureKitNetworkError?
var httpStatusCode: HTTPStatusCode? {
return response?.code
}
init(response: HTTPURLResponse? = nil, error: Error? = nil) {
self.response = response
self.error = error.map { ProcedureKitNetworkError(error: $0) }
}
}
public protocol NetworkOperation {
var networkError: Error? { get }
var urlResponse: HTTPURLResponse? { get }
}
public enum HTTPStatusCode: Int, CustomStringConvertible {
case `continue` = 100
case switchingProtocols = 101
case processing = 102
case checkpoint = 103
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
case multiStatus = 207
case alreadyReported = 208
case imUsed = 226
case multipleChoices = 300
case movedPermenantly = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case temporaryRedirect = 307
case permanentRedirect = 308
case badRequest = 400
case unauthorized = 401
case paymentRequired = 402
case forbidden = 403
case notFound = 404
case methodNotAllowed = 405
case notAcceptable = 406
case proxyAuthenticationRequired = 407
case requestTimeout = 408
case conflict = 409
case gone = 410
case lengthRequired = 411
case preconditionFailed = 412
case payloadTooLarge = 413
case uriTooLong = 414
case unsupportedMediaType = 415
case rangeNotSatisfiable = 416
case expectationFailed = 417
case imATeapot = 418
case misdirectedRequest = 421
case unprocesssableEntity = 422
case locked = 423
case failedDependency = 424
case urpgradeRequired = 426
case preconditionRequired = 428
case tooManyRequests = 429
case requestHeadersFieldTooLarge = 431
case iisLoginTimeout = 440
case nginxNoResponse = 444
case iisRetryWith = 449
case blockedByWindowsParentalControls = 450
case unavailableForLegalReasons = 451
case nginxSSLCertificateError = 495
case nginxHTTPToHTTPS = 497
case tokenExpired = 498
case nginxClientClosedRequest = 499
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
case variantAlsoNegotiates = 506
case insufficientStorage = 507
case loopDetected = 508
case bandwidthLimitExceeded = 509
case notExtended = 510
case networkAuthenticationRequired = 511
case siteIsFrozen = 530
public var isInformational: Bool {
switch rawValue {
case 100..<200: return true
default: return false
}
}
public var isSuccess: Bool {
switch rawValue {
case 200..<300: return true
default: return false
}
}
public var isRedirection: Bool {
switch rawValue {
case 300..<400: return true
default: return false
}
}
public var isClientError: Bool {
switch rawValue {
case 400..<500: return true
default: return false
}
}
public var isServerError: Bool {
switch rawValue {
case 500..<600: return true
default: return false
}
}
public var localizedReason: String {
return HTTPURLResponse.localizedString(forStatusCode: rawValue)
}
public var description: String {
return "\(rawValue) \(localizedReason)"
}
}
// MARK: - Extensions
public extension HTTPURLResponse {
public var code: HTTPStatusCode? {
return HTTPStatusCode(rawValue: statusCode)
}
}
extension NetworkOperation {
func makeNetworkResponse() -> ProcedureKitNetworkResponse {
return ProcedureKitNetworkResponse(response: urlResponse, error: networkError)
}
}
extension NetworkOperation where Self: OutputProcedure, Self.Output: HTTPPayloadResponseProtocol {
public var urlResponse: HTTPURLResponse? {
return output.success?.response
}
}
| mit | 41c4c18c8d0590779cc6e9a109f51e07 | 26.274576 | 149 | 0.693264 | 5.131378 | false | false | false | false |
pirishd/InstantMock | Example.playground/Contents.swift | 1 | 2921 | import InstantMock
// MARK: Definitions
/// Class representing a traveler going on holidays
class Traveler {
private let name: String
private let vehicule: Vehicule
init(name: String, vehicule: Vehicule) {
self.name = name
self.vehicule = vehicule
}
/// Traveler goes to some destination
func travel(to destination: String) {
// he needs to start a vehicule…
self.vehicule.starts()
// …then goes to the destination with a few halts…
let went = self.vehicule.goes(to: destination, numberOfHalts: 2)
// …when arrived to destination…
if went {
// …he stops the vehicule…
self.vehicule.stops(onStop: {
// …and when stopped, he notifies his friends!
return "I'm arrived!"
})
}
}
}
/// Protocol representing a vehicule that brings a traveler to a destination
protocol Vehicule {
func starts()
func goes(to: String, numberOfHalts: Int) -> Bool
func stops(onStop: @escaping () -> String)
}
/// Mock class for the vehicule
class VehiculeMock: Mock, Vehicule {
func starts() {
super.call()
}
func goes(to destination: String, numberOfHalts: Int) -> Bool {
return super.call(destination, numberOfHalts)!
}
func stops(onStop: @escaping () -> String) {
super.call(onStop)
}
}
// MARK: Examples
/// Let's go to holidays!
// James is going first
let jamesVehiculeMock = VehiculeMock()
let james = Traveler(name: "James", vehicule: jamesVehiculeMock)
// Expect James' vehicule to start
jamesVehiculeMock.expect().call(jamesVehiculeMock.starts())
// Unfortunately, specify that James' vehicule won't go to destination
jamesVehiculeMock.stub().call(
jamesVehiculeMock.goes(to: Arg.any(), numberOfHalts: Arg.eq(2))
).andReturn(false)
// So, don't expect James to stop the vehicule when arriving
jamesVehiculeMock.reject().call(jamesVehiculeMock.stops(onStop: Arg.closure()))
// Let's test James' travel!
james.travel(to: "Paris")
// Verify expectations
jamesVehiculeMock.verify()
// Pat is going next!
let patVehiculeMock = VehiculeMock()
let pat = Traveler(name: "Pat", vehicule: patVehiculeMock)
// For him, capture the number of halts he does, and the notification he sends when arriving
let numberOfHaltsCaptor = ArgumentCaptor<Int>()
let closureCaptor = ArgumentClosureCaptor<() -> String>()
patVehiculeMock.stub().call(
patVehiculeMock.goes(to: Arg.eq("New York"), numberOfHalts: numberOfHaltsCaptor.capture())
).andReturn(true)
patVehiculeMock.expect().call(patVehiculeMock.stops(onStop: closureCaptor.capture()))
// Let's test Pat's travel!
pat.travel(to: "New York")
// Verify expectations
patVehiculeMock.verify()
// Display the captured values
numberOfHaltsCaptor.value! // 2 halts
closureCaptor.value!() // call arriving notification
| mit | c33519b3f30887b72439eca97eb2acb9 | 23.208333 | 94 | 0.681928 | 3.555692 | false | false | false | false |
DeepLearningKit/DeepLearningKit | tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/DeepNetwork.swift | 5 | 2326 | //
// DeepNetwork.swift
// MemkiteMetal
//
// Created by Amund Tveit on 24/11/15.
// Copyright © 2015 memkite. All rights reserved.
//
import Foundation
import Metal
public class DeepNetwork {
var gpuCommandLayers: [MTLCommandBuffer] = []
var namedDataLayers: [(String, MTLBuffer)] = []
var imageBuffer: MTLBuffer!
var metalDevice: MTLDevice!
var metalDefaultLibrary: MTLLibrary!
var metalCommandQueue: MTLCommandQueue!
var deepNetworkAsDict: NSDictionary! // for debugging perhaps
var layer_data_caches: [Dictionary<String,MTLBuffer>] = []
var pool_type_caches: [Dictionary<String,String>] = []
var dummy_image: [Float]!
var previous_shape: [Float]!
var blob_cache: [Dictionary<String,([Float],[Float])>] = []
public init() {
setupMetal()
deepNetworkAsDict = nil
}
public func loadDeepNetworkFromJSON(networkName: String, inputImage: [Float], inputShape:[Float], caching_mode:Bool) {
print(" ==> loadDeepNetworkFromJSON(networkName=\(networkName)")
if deepNetworkAsDict == nil {
print("loading json file!")
deepNetworkAsDict = loadJSONFile(networkName)!
}
// IMAGE INPUT HANDLING START - TODO: hardcode input dimensions,
// and have random data, and then later overwrite the first buffer
//let imageLayer = loadJSONFile("conv1")!
//let imageData: [Float] = imageLayer["input"] as! [Float]
print(inputImage.count)
let imageTensor = createMetalBuffer(inputImage, metalDevice: metalDevice)
// preLoadMetalShaders(metalDevice, metalDefaultLibrary:metalDefaultLibrary)
setupNetworkFromDict(deepNetworkAsDict, inputimage: imageTensor, inputshape: inputShape, caching_mode:caching_mode )
}
func setupMetal() {
// Get access to iPhone or iPad GPU
metalDevice = MTLCreateSystemDefaultDevice()
// Queue to handle an ordered list of command buffers
metalCommandQueue = metalDevice.newCommandQueue()
print("metalCommandQueue = \(unsafeAddressOf(metalCommandQueue))")
// Access to Metal functions that are stored in Shaders.metal file, e.g. sigmoid()
metalDefaultLibrary = metalDevice.newDefaultLibrary()
}
}
| apache-2.0 | 6a84e2910a5f78d565048deef3307c81 | 35.904762 | 124 | 0.665806 | 4.659319 | false | false | false | false |
4taras4/totp-auth | TOTP/ViperModules/AddFolderItems/Module/View/AddFolderItemsViewController.swift | 1 | 1941 | //
// AddFolderItemsAddFolderItemsViewController.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import UIKit
import Firebase
import GoogleMobileAds
class AddFolderItemsViewController: UITableViewController {
// MARK: -
// MARK: Properties
var output: AddFolderItemsViewOutput!
var bannerView: GADBannerView!
// MARK: -
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = output
tableView.dataSource = output
output.viewIsReady()
setupAddsViewElements()
}
func setupAddsViewElements() {
bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
addBannerViewToView(bannerView)
bannerView.adUnitID = Constants.adds.bannerId
bannerView.rootViewController = self
bannerView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
bannerView.load(GADRequest())
}
static func instantiate(with folder: Folder) -> AddFolderItemsViewController {
let viewController = AddFolderItemsViewController.instantiate(useSwinject: true)
let output = container.resolve(AddFolderItemsPresenter.self, arguments: viewController, folder)
viewController.output = output
return viewController
}
}
// MARK: -
// MARK: AddFolderItemsViewInput
extension AddFolderItemsViewController: AddFolderItemsViewInput {
func showError(error: Error) {
UIManager.shared.showAlert(title: "", message: error.localizedDescription)
}
func reloadTable() {
tableView.reloadData()
}
func setupInitialState() {
}
}
extension AddFolderItemsViewController: NibIdentifiable {
static var nibNameIdentifier: String {
return "Main"
}
static var controllerIdentifier: String {
return "AddFolderItemsViewController"
}
}
| mit | ecddd32517c66d4afa70a8d9ee0546cf | 24.526316 | 103 | 0.701546 | 4.825871 | false | false | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay-Tests/TestUUID.swift | 1 | 6614 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
class TestUUID : XCTestCase {
func test_NS_Equality() {
let uuidA = NSUUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F")
let uuidB = NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")
let uuidC = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f])
let uuidD = NSUUID()
XCTAssertEqual(uuidA, uuidB, "String case must not matter.")
XCTAssertEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.")
XCTAssertNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.")
}
func test_Equality() {
let uuidA = UUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F")
let uuidB = UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")
let uuidC = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f))
let uuidD = UUID()
XCTAssertEqual(uuidA, uuidB, "String case must not matter.")
XCTAssertEqual(uuidA, uuidC, "A UUID initialized with a string must be equal to the same UUID initialized with its UnsafePointer<UInt8> equivalent representation.")
XCTAssertNotEqual(uuidC, uuidD, "Two different UUIDs must not be equal.")
}
func test_NS_InvalidUUID() {
let uuid = NSUUID(uuidString: "Invalid UUID")
XCTAssertNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.")
}
func test_InvalidUUID() {
let uuid = UUID(uuidString: "Invalid UUID")
XCTAssertNil(uuid, "The convenience initializer `init?(uuidString string:)` must return nil for an invalid UUID string.")
}
func test_NS_uuidString() {
let uuid = NSUUID(uuidBytes: [0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f])
XCTAssertEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F")
}
func test_uuidString() {
let uuid = UUID(uuid: uuid_t(0xe6,0x21,0xe1,0xf8,0xc3,0x6c,0x49,0x5a,0x93,0xfc,0x0c,0x24,0x7a,0x3e,0x6e,0x5f))
XCTAssertEqual(uuid.uuidString, "E621E1F8-C36C-495A-93FC-0C247A3E6E5F")
}
func test_description() {
let uuid = UUID()
XCTAssertEqual(uuid.description, uuid.uuidString, "The description must be the same as the uuidString.")
}
func test_roundTrips() {
let ref = NSUUID()
let valFromRef = ref as UUID
var bytes: [UInt8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
let valFromBytes = bytes.withUnsafeMutableBufferPointer { buffer -> UUID in
ref.getBytes(buffer.baseAddress!)
return UUID(uuid: UnsafeRawPointer(buffer.baseAddress!).load(as: uuid_t.self))
}
let valFromStr = UUID(uuidString: ref.uuidString)
XCTAssertEqual(ref.uuidString, valFromRef.uuidString)
XCTAssertEqual(ref.uuidString, valFromBytes.uuidString)
XCTAssertNotNil(valFromStr)
XCTAssertEqual(ref.uuidString, valFromStr!.uuidString)
}
func test_hash() {
guard #available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) else { return }
let values: [UUID] = [
// This list takes a UUID and tweaks every byte while
// leaving the version/variant intact.
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a63baa1c-b4f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53caa1c-b4f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53bab1c-b4f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1d-b4f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b5f5-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f6-48db-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-49db-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48dc-9467-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9567-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9468-9786b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9886b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9787b76b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9786b86b256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9786b76c256c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9786b76b266c")!,
UUID(uuidString: "a53baa1c-b4f5-48db-9467-9786b76b256d")!,
]
checkHashable(values, equalityOracle: { $0 == $1 })
}
func test_AnyHashableContainingUUID() {
let values: [UUID] = [
UUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!,
UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!,
UUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!,
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(UUID.self, type(of: anyHashables[0].base))
expectEqual(UUID.self, type(of: anyHashables[1].base))
expectEqual(UUID.self, type(of: anyHashables[2].base))
XCTAssertNotEqual(anyHashables[0], anyHashables[1])
XCTAssertEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSUUID() {
let values: [NSUUID] = [
NSUUID(uuidString: "e621e1f8-c36c-495a-93fc-0c247a3e6e5f")!,
NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!,
NSUUID(uuidString: "f81d4fae-7dec-11d0-a765-00a0c91e6bf6")!,
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(UUID.self, type(of: anyHashables[0].base))
expectEqual(UUID.self, type(of: anyHashables[1].base))
expectEqual(UUID.self, type(of: anyHashables[2].base))
XCTAssertNotEqual(anyHashables[0], anyHashables[1])
XCTAssertEqual(anyHashables[1], anyHashables[2])
}
}
| apache-2.0 | 07023ee584f95045059f30e836533af6 | 48.729323 | 172 | 0.645751 | 3.069142 | false | true | false | false |
EZ-NET/ESSwim | ESSwimTests/TreeTest.swift | 1 | 92943 | //
// TreeTest.swift
// ESSwim
//
// Created by 熊谷 友宏 on H26/12/19.
//
//
import XCTest
import Swim
class TreeTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func treeCheck<Tree : MultiBranchTreeType>(tree:Tree, height:Int?, totalNodes:Int?, hasRootNode:Bool?) -> Bool {
var errorFlag = Swim.Flag()
if let v = height {
let s = nodeHeight(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Tree '\(tree)' height (\(s)) is not equal to ('\(v)').")
}
if let v = totalNodes {
let s = nodeSize(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Total number of nodes of Tree '\(tree)' (\(s)) is not equal to ('\(v)').")
}
if let v = hasRootNode {
let s = Swim.hasRootNode(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Tree '\(tree)' has root node (\(s)) is not equal to ('\(v)').")
}
return !errorFlag
}
func treeCheck<Tree : BinaryTreeType>(tree:Tree, height:Int?, totalNodes:Int?, hasRootNode:Bool?) -> Bool {
var errorFlag = Swim.Flag()
if let v = height {
let s = nodeHeight(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Tree '\(tree)' height (\(s)) is not equal to ('\(v)').")
}
if let v = totalNodes {
let s = nodeSize(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Total number of nodes of Tree '\(tree)' (\(s)) is not equal to ('\(v)').")
}
if let v = hasRootNode {
let s = Swim.hasRootNode(tree)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Tree '\(tree)' has root node (\(s)) is not equal to ('\(v)').")
}
return !errorFlag
}
func nodeCheck<Node:BinaryTreeNodeType, NodeValue where Node.NodeValue == NodeValue, NodeValue: Equatable>(node:Node, value:NodeValue??, depth:Int?, height:Int?, totalNodes:Int?, isRoot:Bool?, isLeaf:Bool?, isInternal:Bool?, isExternal:Bool?, isDescendantOf:(Node,Bool)?, isAncestorOf:(Node,Bool)?, hasChild:Bool?, parent:Node??, degree:Int?) -> Bool {
var errorFlag = Swim.Flag()
if let v = degree {
let s = node.degree
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Degree (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
if let v = parent {
let s = node.parentNode
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Parent node (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
if let v = value {
let s = node.value
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' value (\(s)) is not equal to ('\(v)').")
}
if let v = depth {
let s = Swim.nodeDepth(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' depth (\(s)) is not equal to ('\(v)').")
}
if let v = height {
let s = Swim.nodeHeight(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' height (\(s)) is not equal to ('\(v)').")
}
if let v = totalNodes {
let s = Swim.nodeSize(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Total number of nodes in Node '\(node)' (\(s)) is not equal to ('\(v)').")
}
if let v = isRoot {
let s = isRootNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is root node (\(s)) is not equal to ('\(v)').")
}
if let v = isLeaf {
let s = isLeafNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is leaf node (\(s)) is not equal to ('\(v)').")
}
if let v = isInternal {
let s = isInternalNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is internal node (\(s)) is not equal to ('\(v)').")
}
if let v = isExternal {
let s = isExternalNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is external node (\(s)) is not equal to ('\(v)').")
}
if let v = isDescendantOf {
let s = isDescendant(node, of: v.0)
XCTAssertTrue(errorFlag.setIfFalse(s == v.1), "Node '\(node)' is descendant of node '\(v.0)' : (\(s)) is not equal to ('\(v.1)').")
}
if let v = isAncestorOf {
let s = isAncestor(node, of: v.0)
XCTAssertTrue(errorFlag.setIfFalse(s == v.1), "Node '\(node)' is ancester of node '\(v.0)' : (\(s)) is not equal to ('\(v.1)').")
}
return !errorFlag
}
func bnodeCheck<Node : BinaryTreeNodeType, NodeValue where Node == Node.Generator.Element, NodeValue == Node.NodeValue, NodeValue : Equatable>(node:Node, value:NodeValue??, depth:Int?, height:Int?, totalNodes:Int?, isRoot:Bool?, isLeaf:Bool?, isInternal:Bool?, isExternal:Bool?, isDescendantOf:(Node,Bool)?, isAncestorOf:(Node,Bool)?, hasChild:Bool?, parent:Node??, leftChild:Node??, rightChild:Node??, degree:Int?) -> Bool {
var errorFlag = Swim.Flag()
errorFlag.setIfFalse(nodeCheck(node, value: value, depth: depth, height: height, totalNodes: totalNodes, isRoot: isRoot, isLeaf: isLeaf, isInternal: isInternal, isExternal: isExternal, isDescendantOf: isDescendantOf, isAncestorOf: isAncestorOf, hasChild: hasChild, parent: parent, degree: degree))
if let v = leftChild {
let s = node.leftChildNode
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Left child node (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
if let v = rightChild {
let s = node.rightChildNode
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Right child node (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
return !errorFlag
}
func nodeCheck<Node : MultiBranchTreeNodeType, NodeValue where Node == Node.Generator.Element, NodeValue == Node.NodeValue, NodeValue : Equatable>(node:Node, value:Node.NodeValue??, depth:Int?, height:Int?, totalNodes:Int?, isRoot:Bool?, isLeaf:Bool?, isInternal:Bool?, isExternal:Bool?, isDescendantOf:(Node,Bool)?, isAncestorOf:(Node,Bool)?, hasChild:Bool?, parent:Node??, degree:Int?) -> Bool {
var errorFlag = Swim.Flag()
if let v = degree {
let s = node.degree
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Degree (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
if let v = parent {
let s = node.parentNode
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Parent node (\(s)) of Node '\(node)' is not equal to ('\(v)').")
}
if let v = value {
let s = node.value
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' value (\(s)) is not equal to ('\(v)').")
}
if let v = depth {
let s = Swim.nodeDepth(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' depth (\(s)) is not equal to ('\(v)').")
}
if let v = height {
let s = Swim.nodeHeight(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' height (\(s)) is not equal to ('\(v)').")
}
if let v = totalNodes {
let s = Swim.nodeSize(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Total number of nodes in Node '\(node)' (\(s)) is not equal to ('\(v)').")
}
if let v = isRoot {
let s = isRootNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is root node (\(s)) is not equal to ('\(v)').")
}
if let v = isLeaf {
let s = isLeafNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is leaf node (\(s)) is not equal to ('\(v)').")
}
if let v = isInternal {
let s = isInternalNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is internal node (\(s)) is not equal to ('\(v)').")
}
if let v = isExternal {
let s = isExternalNode(node)
XCTAssertTrue(errorFlag.setIfFalse(s == v), "Node '\(node)' is external node (\(s)) is not equal to ('\(v)').")
}
if let v = isDescendantOf {
let s = isDescendant(node, of: v.0)
XCTAssertTrue(errorFlag.setIfFalse(s == v.1), "Node '\(node)' is descendant of node '\(v.0)' : (\(s)) is not equal to ('\(v.1)').")
}
if let v = isAncestorOf {
let s = isAncestor(node, of: v.0)
XCTAssertTrue(errorFlag.setIfFalse(s == v.1), "Node '\(node)' is ancester of node '\(v.0)' : (\(s)) is not equal to ('\(v.1)').")
}
return !errorFlag
}
func testGenerator() {
typealias BTree = Swim.BinaryTree<String>
typealias BNode = BTree.Node
let btree1 = BTree()
_ = BNode()
let bnode1 = BNode("2")
let bnode2 = BNode("7")
let bnode3 = BNode("5")
let bnode4 = BNode("2")
let bnode5 = BNode("6")
let bnode6 = BNode("9")
btree1.rootNode = bnode1
bnode1.leftChildNode = bnode2
bnode1.rightChildNode = bnode3
bnode2.leftChildNode = bnode4
bnode2.rightChildNode = bnode5
bnode3.rightChildNode = bnode6
let nodeCheck = { (generator:Swim.TreeNodeGenerator<BNode>) -> (node:BNode) -> Swim.ContinuousState in
return { (node:BNode) -> Swim.ContinuousState in
if let nextNode = generator.next() {
return node == nextNode ? .Continue : .Abort
}
else {
return .Abort
}
}
}
let generatorInOrder = Swim.TreeNodeInOrderGenerator(btree1.rootNode)
let stateInOrder = btree1.rootNode!.traverseByInOrder(nodeCheck(generatorInOrder))
XCTAssertTrue(stateInOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorInOrder.next() == nil, "巡回していないノードが残っています。")
let generatorPreOrder = Swim.TreeNodePreOrderGenerator(btree1.rootNode)
let statePreOrder = btree1.rootNode!.traverseByPreOrder(nodeCheck(generatorPreOrder))
XCTAssertTrue(statePreOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorPreOrder.next() == nil, "巡回していないノードが残っています。")
let generatorPostOrder = Swim.TreeNodePostOrderGenerator(btree1.rootNode)
let statePostOrder = btree1.rootNode!.traverseByPostOrder(nodeCheck(generatorPostOrder))
XCTAssertTrue(statePostOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorPostOrder.next() == nil, "巡回していないノードが残っています。")
let generatorLevelOrder = Swim.TreeNodeLevelOrderGenerator(btree1.rootNode)
let stateLevelOrder = btree1.rootNode!.traverseByLevelOrder(nodeCheck(generatorLevelOrder))
XCTAssertTrue(stateLevelOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorLevelOrder.next() == nil, "巡回していないノードが残っています。")
let generatorInOrderWithNil = Swim.TreeNodeInOrderGenerator<BNode>(nil)
XCTAssertTrue(generatorInOrderWithNil.next() == nil)
// MARK: 😞 Cannot implement in Xcode 6.1.1, because 'Command failed due to signal: Abort trap: 6' at build time.
// MARK: Please use `TreeNodeInOrderGenerator` instead of this.
// let generatorOfTreeInOrder = Swim.TreeInOrderGenerator(btree1)
let generatorOfTreeInOrder = Swim.TreeNodeInOrderGenerator(btree1.rootNode)
let stateOfTreeInOrder = btree1.rootNode!.traverseByInOrder(nodeCheck(generatorOfTreeInOrder))
XCTAssertTrue(stateOfTreeInOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorOfTreeInOrder.next() == nil, "巡回していないノードが残っています。")
let generatorOfTreePreOrder = Swim.TreePreOrderGenerator(btree1)
let stateOfTreePreOrder = btree1.rootNode!.traverseByPreOrder(nodeCheck(generatorOfTreePreOrder))
XCTAssertTrue(stateOfTreePreOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorOfTreePreOrder.next() == nil, "巡回していないノードが残っています。")
let generatorOfTreePostOrder = Swim.TreePostOrderGenerator(btree1)
let stateOfTreePostOrder = btree1.rootNode!.traverseByPostOrder(nodeCheck(generatorOfTreePostOrder))
XCTAssertTrue(stateOfTreePostOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorOfTreePostOrder.next() == nil, "巡回していないノードが残っています。")
let generatorOfTreeLevelOrder = Swim.TreeLevelOrderGenerator(btree1)
let stateOfTreeLevelOrder = btree1.rootNode!.traverseByLevelOrder(nodeCheck(generatorOfTreeLevelOrder))
XCTAssertTrue(stateOfTreeLevelOrder.passed, "巡回中に一致しないノードを検出しました。")
XCTAssertTrue(generatorOfTreeLevelOrder.next() == nil, "巡回していないノードが残っています。")
// MARK: Generator Test using `generate` function.
// In-Order
XCTAssertTrue(generatorInOrder.next() == nil, "generate メソッドで新規に Generator を取得できることを確認するために、next メソッドで巡回済のものを使うようにしてください。")
let generatorInOrder2 = Swim.TreeNodeInOrderGenerator(btree1.rootNode)
for node in generatorInOrder {
XCTAssertEqual(node, generatorInOrder2.next()!)
}
XCTAssertTrue(generatorInOrder2.next() == nil, "巡回していないノードが残っています。")
// Pre-Order
XCTAssertTrue(generatorPreOrder.next() == nil, "generate メソッドで新規に Generator を取得できることを確認するために、next メソッドで巡回済のものを使うようにしてください。")
let generatorPreOrder2 = Swim.TreeNodePreOrderGenerator(btree1.rootNode)
for node in generatorPreOrder {
XCTAssertEqual(node, generatorPreOrder2.next()!)
}
XCTAssertTrue(generatorPreOrder2.next() == nil, "巡回していないノードが残っています。")
// Post-Order
XCTAssertTrue(generatorPostOrder.next() == nil, "generate メソッドで新規に Generator を取得できることを確認するために、next メソッドで巡回済のものを使うようにしてください。")
let generatorPostOrder2 = Swim.TreeNodePostOrderGenerator(btree1.rootNode)
for node in generatorPostOrder {
XCTAssertEqual(node, generatorPostOrder2.next()!)
}
XCTAssertTrue(generatorPostOrder2.next() == nil, "巡回していないノードが残っています。")
// Level-Order
XCTAssertTrue(generatorLevelOrder.next() == nil, "generate メソッドで新規に Generator を取得できることを確認するために、next メソッドで巡回済のものを使うようにしてください。")
let generatorLevelOrder2 = Swim.TreeNodeLevelOrderGenerator(btree1.rootNode)
for node in generatorLevelOrder {
XCTAssertEqual(node, generatorLevelOrder2.next()!)
}
XCTAssertTrue(generatorLevelOrder2.next() == nil, "巡回していないノードが残っています。")
}
func testBinaryTree() {
typealias BTree = Swim.BinaryTree<String>
typealias BNode = BTree.Node
let btree1 = BTree()
XCTAssertTrue(treeCheck(btree1, height: 0, totalNodes: 0, hasRootNode: false))
let bnode0 = BNode()
let bnode1 = BNode("2")
XCTAssertTrue(nodeCheck(bnode0, value:String?(), depth:0, height:0, totalNodes:1, isRoot:true, isLeaf:true, isInternal:false, isExternal:false, isDescendantOf:(bnode0,false), isAncestorOf:(bnode0,false), hasChild:false, parent:BNode?(), degree:0))
XCTAssertTrue(nodeCheck(bnode1, value:"2", depth:0, height:0, totalNodes:1, isRoot:true, isLeaf:true, isInternal:false, isExternal:false, isDescendantOf:(bnode1,false), isAncestorOf:(bnode1,false), hasChild:false, parent:BNode?(), degree:0))
btree1.rootNode = bnode1
XCTAssertTrue(treeCheck(btree1, height: 0, totalNodes: 1, hasRootNode: true))
let bnode2 = BNode("7")
XCTAssertTrue(isRootNode(bnode1))
XCTAssertTrue(isRootNode(bnode2))
bnode1.leftChildNode = bnode2
XCTAssertTrue(isRootNode(bnode1))
XCTAssertFalse(isRootNode(bnode2))
let bnodeValue1 = bnode1.value!
let bnodeValue2 = bnode2.value!
XCTAssertTrue(bnodeValue1 == "2")
XCTAssertTrue(bnodeValue2 == "7")
let descendant_1_2 = isDescendant(bnode1, of: bnode2)
let ancestor_1_2 = isAncestor(bnode1, of: bnode2)
XCTAssertFalse(descendant_1_2)
XCTAssertTrue(ancestor_1_2)
let descendant_2_1 = isDescendant(bnode2, of: bnode1)
XCTAssertTrue(descendant_2_1)
XCTAssertTrue(treeCheck(btree1, height: 1, totalNodes: 2, hasRootNode: true))
XCTAssertTrue(nodeCheck(bnode1, value: nil, depth: 0, height: 1, totalNodes: 2, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (bnode2, false), isAncestorOf: (bnode2, true), hasChild: true, parent:BNode?(), degree:1))
let bnode3 = BNode("5")
XCTAssertTrue(bnode3.parentNode == nil)
bnode1.rightChildNode = bnode3
XCTAssertTrue(bnode3.parentNode == bnode1)
XCTAssertTrue(treeCheck(btree1, height: 1, totalNodes: 3, hasRootNode: true))
XCTAssertTrue(nodeCheck(bnode1, value: nil, depth: 0, height: 1, totalNodes: 3, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (bnode2, false), isAncestorOf: (bnode2, true), hasChild: true, parent:BNode?(), degree:2))
let bnode4 = BNode("2")
let bnode5 = BNode("6")
let bnode6 = BNode("9")
bnode2.leftChildNode = bnode4
bnode2.rightChildNode = bnode5
bnode3.rightChildNode = bnode6
XCTAssertTrue(treeCheck(btree1, height: 2, totalNodes: 6, hasRootNode: true))
XCTAssertTrue(nodeCheck(bnode1, value: "2", depth: 0, height: 2, totalNodes: 6, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: nil, isAncestorOf: nil, hasChild: true, parent:BNode?(), degree:2))
XCTAssertTrue(nodeCheck(bnode2, value: "7", depth: 1, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (bnode1, true), isAncestorOf: (bnode4, true), hasChild: true, parent:bnode1, degree:2))
XCTAssertTrue(nodeCheck(bnode3, value: "5", depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (bnode1, true), isAncestorOf: (bnode6, true), hasChild: true, parent:bnode1, degree:1))
XCTAssertTrue(nodeCheck(bnode4, value: "2", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode3, false), isAncestorOf: (bnode2, false), hasChild: false, parent:bnode2, degree:0))
XCTAssertTrue(nodeCheck(bnode5, value: "6", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode2, true), isAncestorOf: (bnode1, false), hasChild: false, parent:bnode2, degree:0))
XCTAssertTrue(nodeCheck(bnode6, value: "9", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode3, true), isAncestorOf: (bnode5, false), hasChild: false, parent:bnode3, degree:0))
let bnode7 = BNode("5")
let bnode8 = BNode("11")
let bnode9 = BNode("4")
bnode5.leftChildNode = bnode7
bnode5.rightChildNode = bnode8
bnode6.leftChildNode = bnode9
XCTAssertTrue(treeCheck(btree1, height: 3, totalNodes: 9, hasRootNode: true))
XCTAssertTrue(nodeCheck(bnode1, value: "2", depth: 0, height: 3, totalNodes: 9, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: nil, isAncestorOf: nil, hasChild: true, parent:BNode?(), degree:2))
XCTAssertTrue(nodeCheck(bnode7, value: "5", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode1, true), isAncestorOf: (bnode4, false), hasChild: false, parent:bnode5, degree:0))
XCTAssertTrue(nodeCheck(bnode8, value: "11", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode3, false), isAncestorOf: (bnode6, false), hasChild: false, parent:bnode5, degree:0))
XCTAssertTrue(nodeCheck(bnode9, value: "4", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (bnode3, true), isAncestorOf: (bnode2, false), hasChild: false, parent:bnode6, degree:0))
XCTAssertEqual(nodeHeight(btree1), nodeHeight(bnode1))
XCTAssertTrue(nodeDepth(bnode1) == 0)
XCTAssertTrue(nodeHeight(bnode1) == 3)
XCTAssertEqual(nodeSize(btree1), nodeSize(bnode1))
let degrees = Swim.mapByLevelOrder(btree1.rootNode!) { $0.degree }
XCTAssertEqual(degrees, [ 2, 2, 1, 0, 2, 1, 0, 0, 0])
let bnodesFilteredByPreOrder = Swim.filterByPreOrder(bnode1) { Int($0.value ?? "0")! > 5 }
let bnodesFilteredByPostOrder = Swim.filterByPostOrder(bnode1) { Int($0.value ?? "0")! > 5 }
let bnodesFilteredByInOrder = Swim.filterByInOrder(bnode1) { Int($0.value ?? "0")! > 5 }
let bnodesFilteredByLevelOrder = Swim.filterByLevelOrder(bnode1) { Int($0.value ?? "0")! > 5 }
XCTAssertTrue(bnodesFilteredByPreOrder.count == 4)
XCTAssertTrue(bnodesFilteredByPostOrder.count == 4)
XCTAssertTrue(bnodesFilteredByInOrder.count == 4)
XCTAssertTrue(bnodesFilteredByLevelOrder.count == 4)
XCTAssertEqual(bnodesFilteredByPreOrder.map { $0.value! }, [ "7", "6", "11", "9" ])
XCTAssertEqual(bnodesFilteredByPostOrder.map { $0.value! }, [ "11", "6", "7", "9" ])
XCTAssertEqual(bnodesFilteredByInOrder.map { $0.value! }, [ "7", "6", "11", "9" ])
XCTAssertEqual(bnodesFilteredByLevelOrder.map { $0.value! }, [ "7", "6", "9", "11" ])
let bnodeValuesByPreOrder = Swim.mapByPreOrder(bnode1) { $0.value! }
let bnodeValuesByPostOrder = Swim.mapByPostOrder(bnode1) { $0.value! }
let bnodeValuesByInOrder = Swim.mapByInOrder(bnode1) { $0.value! }
let bnodeValuesByLevelOrder = Swim.mapByLevelOrder(bnode1) { $0.value! }
XCTAssertEqual(bnodeValuesByPreOrder, [ "2", "7", "2", "6", "5", "11", "5", "9", "4" ])
XCTAssertEqual(bnodeValuesByPostOrder, [ "2", "5", "11", "6", "7", "4", "9", "5", "2" ])
XCTAssertEqual(bnodeValuesByInOrder, [ "2", "7", "5", "6", "11", "2", "5", "4", "9" ])
XCTAssertEqual(bnodeValuesByLevelOrder, [ "2", "7", "5", "2", "6", "9", "5", "11", "4" ])
let stringByPreOrder = Swim.reduceByPreOrder(bnode1, "") { $0 + $1.value! }
let stringByPostOrder = Swim.reduceByPostOrder(bnode1, "") { $0 + $1.value! }
let stringByInOrder = Swim.reduceByInOrder(bnode1, "") { $0 + $1.value! }
let stringByLevelOrder = Swim.reduceByLevelOrder(bnode1, "") { $0 + $1.value! }
XCTAssertTrue(stringByPreOrder == "2726511594")
XCTAssertTrue(stringByPostOrder == "2511674952")
XCTAssertTrue(stringByInOrder == "2756112549")
XCTAssertTrue(stringByLevelOrder == "2752695114")
let ownership = traverseByInOrder(bnode1) {
if let parentNode = $0.parentNode {
return parentNode.contains($0) ? .Continue : .Abort
}
else {
return $0 == bnode1 ? .Continue : .Abort
}
}
XCTAssertTrue(ownership.passed)
}
func testMultiBranchTree() {
typealias MTree = Swim.MultiBranchTree<String>
typealias MNode = MTree.Node
let mtree1 = MTree()
XCTAssertTrue(treeCheck(mtree1, height: 0, totalNodes: 0, hasRootNode: false))
let mnode0 = MNode()
let mnode1 = MNode("A")
XCTAssertTrue(nodeCheck(mnode0, value:String?(), depth:0, height:0, totalNodes:1, isRoot:true, isLeaf:true, isInternal:false, isExternal:false, isDescendantOf:(mnode0,false), isAncestorOf:(mnode0,false), hasChild:false, parent:MNode?(), degree: 0))
XCTAssertTrue(nodeCheck(mnode1, value:"A", depth:0, height:0, totalNodes:1, isRoot:true, isLeaf:true, isInternal:false, isExternal:false, isDescendantOf:(mnode1,false), isAncestorOf:(mnode1,false), hasChild:false, parent:MNode?(), degree: 0))
mtree1.rootNode = mnode1
XCTAssertTrue(treeCheck(mtree1, height: 0, totalNodes: 1, hasRootNode: true))
let mnode2 = MNode("B")
mnode1.append(mnode2)
XCTAssertTrue(treeCheck(mtree1, height: 1, totalNodes: 2, hasRootNode: true))
XCTAssertTrue(nodeCheck(mnode1, value: "A", depth: 0, height: 1, totalNodes: 2, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (mnode2, false), isAncestorOf: (mnode2, true), hasChild: true, parent:MNode?(), degree: 1))
let mnode3 = MNode("C")
XCTAssertTrue(mnode3.parentNode == nil)
mnode1.append(mnode3)
XCTAssertTrue(mnode3.parentNode == mnode1)
XCTAssertTrue(treeCheck(mtree1, height: 1, totalNodes: 3, hasRootNode: true))
XCTAssertTrue(nodeCheck(mnode1, value: nil, depth: 0, height: 1, totalNodes: 3, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (mnode2, false), isAncestorOf: (mnode2, true), hasChild: true, parent:MNode?(), degree: 2))
let mnode4 = MNode("D")
let mnode5 = MNode("E")
let mnode6 = MNode("F")
let mnode7 = MNode("G")
let mnode8 = MNode("H")
mnode2.append(mnode4)
mnode2.append(mnode5)
mnode3.append(mnode6)
mnode3.append(mnode7)
mnode3.append(mnode8)
XCTAssertTrue(treeCheck(mtree1, height: 2, totalNodes: 8, hasRootNode: true))
XCTAssertTrue(nodeCheck(mnode1, value: "A", depth: 0, height: 2, totalNodes: 8, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: nil, isAncestorOf: nil, hasChild: true, parent:MNode?(), degree: 2))
XCTAssertTrue(nodeCheck(mnode2, value: "B", depth: 1, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (mnode1, true), isAncestorOf: (mnode4, true), hasChild: true, parent:mnode1, degree: 2))
XCTAssertTrue(nodeCheck(mnode3, value: "C", depth: 1, height: 1, totalNodes: 4, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (mnode1, true), isAncestorOf: (mnode6, true), hasChild: true, parent:mnode1, degree: 3))
XCTAssertTrue(nodeCheck(mnode4, value: "D", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, false), isAncestorOf: (mnode2, false), hasChild: false, parent:mnode2, degree: 0))
XCTAssertTrue(nodeCheck(mnode5, value: "E", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode2, true), isAncestorOf: (mnode1, false), hasChild: false, parent:mnode2, degree: 0))
XCTAssertTrue(nodeCheck(mnode6, value: "F", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, true), isAncestorOf: (mnode5, false), hasChild: false, parent:mnode3, degree: 0))
XCTAssertTrue(nodeCheck(mnode7, value: "G", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode2, false), isAncestorOf: (mnode1, false), hasChild: false, parent:mnode3, degree: 0))
XCTAssertTrue(nodeCheck(mnode8, value: "H", depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, true), isAncestorOf: (mnode5, false), hasChild: false, parent:mnode3, degree: 0))
let mnode9 = MNode("I")
let mnode10 = MNode("J")
let mnode11 = MNode("K")
let mnode12 = MNode("L")
let mnode13 = MNode("M")
let mnode14 = MNode("N")
let mnode15 = MNode("O")
let mnode16 = MNode("P")
mnode4.append(mnode9)
mnode5.append(mnode10)
mnode5.append(mnode11)
mnode5.append(mnode12)
mnode6.append(mnode13)
mnode7.append(mnode14)
mnode7.append(mnode15)
mnode8.append(mnode16)
XCTAssertTrue(treeCheck(mtree1, height: 3, totalNodes: 16, hasRootNode: true))
XCTAssertTrue(nodeCheck(mnode1, value: "A", depth: 0, height: 3, totalNodes: 16, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: nil, isAncestorOf: nil, hasChild: true, parent:MNode?(), degree: 2))
XCTAssertTrue(nodeCheck(mnode9, value: "I", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode1, true), isAncestorOf: (mnode4, false), hasChild: false, parent:mnode4, degree: 0))
XCTAssertTrue(nodeCheck(mnode10, value: "J", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, false), isAncestorOf: (mnode6, false), hasChild: false, parent:mnode5, degree: 0))
XCTAssertTrue(nodeCheck(mnode11, value: "K", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode2, true), isAncestorOf: (mnode2, false), hasChild: false, parent:mnode5, degree: 0))
XCTAssertTrue(nodeCheck(mnode12, value: "L", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode1, true), isAncestorOf: (mnode4, false), hasChild: false, parent:mnode5, degree: 0))
XCTAssertTrue(nodeCheck(mnode13, value: "M", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, true), isAncestorOf: (mnode6, false), hasChild: false, parent:mnode6, degree: 0))
XCTAssertTrue(nodeCheck(mnode14, value: "N", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, true), isAncestorOf: (mnode2, false), hasChild: false, parent:mnode7, degree: 0))
XCTAssertTrue(nodeCheck(mnode15, value: "O", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode1, true), isAncestorOf: (mnode4, false), hasChild: false, parent:mnode7, degree: 0))
XCTAssertTrue(nodeCheck(mnode16, value: "P", depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (mnode3, true), isAncestorOf: (mnode6, false), hasChild: false, parent:mnode8, degree: 0))
XCTAssertEqual(nodeHeight(mtree1), nodeHeight(mnode1))
XCTAssertTrue(nodeDepth(mnode1) == 0)
XCTAssertTrue(nodeHeight(mnode1) == 3)
XCTAssertEqual(nodeSize(mtree1), nodeSize(mnode1))
XCTAssertTrue(Swim.isDescendant(mnode2, of:mnode1) == true)
XCTAssertTrue(Swim.isDescendant(mnode2, of:mnode4) == false)
XCTAssertTrue(Swim.isDescendant(mnode6, of:mnode1) == true)
XCTAssertTrue(Swim.isDescendant(mnode6, of:mnode3) == true)
XCTAssertTrue(Swim.isDescendant(mnode6, of:mnode2) == false)
XCTAssertTrue(Swim.isDescendant(mnode8, of:mnode3) == true)
XCTAssertTrue(Swim.isDescendant(mnode5, of:mnode2) == true)
XCTAssertTrue(Swim.isDescendant(mnode10, of:mnode7) == false)
XCTAssertTrue(Swim.isDescendant(mnode7, of:mnode7) == false)
XCTAssertTrue(Swim.isAncestor(mnode2, of:mnode1) == false)
XCTAssertTrue(Swim.isAncestor(mnode2, of:mnode4) == true)
XCTAssertTrue(Swim.isAncestor(mnode6, of:mnode13) == true)
XCTAssertTrue(Swim.isAncestor(mnode6, of:mnode3) == false)
XCTAssertTrue(Swim.isAncestor(mnode4, of:mnode2) == false)
XCTAssertTrue(Swim.isAncestor(mnode4, of:mnode9) == true)
XCTAssertTrue(Swim.isAncestor(mnode8, of:mnode3) == false)
XCTAssertTrue(Swim.isAncestor(mnode8, of:mnode16) == true)
XCTAssertTrue(Swim.isAncestor(mnode7, of:mnode15) == true)
let degrees = Swim.mapByLevelOrder(mtree1.rootNode!) { $0.degree }
XCTAssertEqual(degrees, [ 2, 2, 3, 1, 3, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0])
let mnodesFilteredByPreOrder = Swim.filterByPreOrder(mnode1) { ($0.value ?? "") > "C" }
let mnodesFilteredByPostOrder = Swim.filterByPostOrder(mnode1) { ($0.value ?? "") > "C" }
let mnodesFilteredByLevelOrder = Swim.filterByLevelOrder(mnode1) { ($0.value ?? "") > "C" }
XCTAssertTrue(mnodesFilteredByPreOrder.count == 13)
XCTAssertTrue(mnodesFilteredByPostOrder.count == 13)
XCTAssertTrue(mnodesFilteredByLevelOrder.count == 13)
XCTAssertEqual(mnodesFilteredByPreOrder.map { $0.value! }, [ "D", "I", "E", "J", "K", "L", "F", "M", "G", "N", "O", "H", "P" ])
XCTAssertEqual(mnodesFilteredByPostOrder.map { $0.value! }, [ "I", "D", "J", "K", "L", "E", "M", "F", "N", "O", "G", "P", "H" ])
XCTAssertEqual(mnodesFilteredByLevelOrder.map { $0.value! }, [ "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P" ])
let mnodeValuesByPreOrder = Swim.mapByPreOrder(mnode1) { $0.value! }
let mnodeValuesByPostOrder = Swim.mapByPostOrder(mnode1) { $0.value! }
let mnodeValuesByLevelOrder = Swim.mapByLevelOrder(mnode1) { $0.value! }
XCTAssertEqual(mnodeValuesByPreOrder, [ "A", "B", "D", "I", "E", "J", "K", "L", "C", "F", "M", "G", "N", "O", "H", "P" ])
XCTAssertEqual(mnodeValuesByPostOrder, [ "I", "D", "J", "K", "L", "E", "B", "M", "F", "N", "O", "G", "P", "H", "C", "A" ])
XCTAssertEqual(mnodeValuesByLevelOrder, [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P" ])
let stringByPreOrder = Swim.reduceByPreOrder(mnode1, "") { $0 + $1.value! }
let stringByPostOrder = Swim.reduceByPostOrder(mnode1, "") { $0 + $1.value! }
let stringByLevelOrder = Swim.reduceByLevelOrder(mnode1, "") { $0 + $1.value! }
XCTAssertTrue(stringByPreOrder == "ABDIEJKLCFMGNOHP")
XCTAssertTrue(stringByPostOrder == "IDJKLEBMFNOGPHCA")
XCTAssertTrue(stringByLevelOrder == "ABCDEFGHIJKLMNOP")
let m3sibFirst = firstSibling(mnode3)
let m3sibLast = lastSibling(mnode3)
XCTAssertTrue(m3sibFirst! == mnode2)
XCTAssertTrue(m3sibLast! == mnode3)
let m6sibFirst = firstSibling(mnode6)
let m6sibLast = lastSibling(mnode6)
XCTAssertTrue(m6sibFirst! == mnode6)
XCTAssertTrue(m6sibLast! == mnode8)
let m9sibFirst = firstSibling(mnode9)
let m9sibLast = lastSibling(mnode9)
XCTAssertTrue(m9sibFirst! == m9sibLast!)
let m1sibFirst = firstSibling(mnode1)
let m1sibLast = lastSibling(mnode1)
XCTAssertTrue(m1sibFirst == nil)
XCTAssertTrue(m1sibLast == nil)
let m7sibPrev = previousSibling(mnode7)
let m7sibNext = nextSibling(mnode7)
let m6sibPrev = previousSibling(mnode6)
let m6sibNext = nextSibling(mnode6)
let m8sibPrev = previousSibling(mnode8)
let m8sibNext = nextSibling(mnode8)
XCTAssertTrue(m7sibPrev! == mnode6)
XCTAssertTrue(m7sibNext! == mnode8)
XCTAssertTrue(m6sibPrev == nil)
XCTAssertTrue(m6sibNext! == mnode7)
XCTAssertTrue(m8sibPrev! == mnode7)
XCTAssertTrue(m8sibNext == nil)
let m2fChild = firstChild(mnode2)
let m2lChild = lastChild(mnode2)
XCTAssertEqual(m2fChild!, mnode4)
XCTAssertEqual(m2lChild!, mnode5)
let m3fChild = firstChild(mnode3)
let m3lChild = lastChild(mnode3)
XCTAssertEqual(m3fChild!, mnode6)
XCTAssertEqual(m3lChild!, mnode8)
let m8fChild = firstChild(mnode8)
let m8lChild = lastChild(mnode8)
XCTAssertEqual(m8fChild!, mnode16)
XCTAssertEqual(m8lChild!, mnode16)
let m16fChild = firstChild(mnode16)
let m16lChild = lastChild(mnode16)
XCTAssertTrue(m16fChild == nil)
XCTAssertTrue(m16lChild == nil)
let ownership = Swim.traverseByPreOrder(mnode1) {
if let parentNode = $0.parentNode {
return parentNode.contains($0) ? .Continue : .Abort
}
else {
return $0 == mnode1 ? .Continue : .Abort
}
}
XCTAssertTrue(ownership.passed)
let mnode1Size = nodeSize(mnode1)
let mnode7Size = nodeSize(mnode7)
XCTAssertTrue(mnode7.parentNode != nil)
XCTAssertTrue(nodeCheck(mnode7, value: "G", depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (mnode1, true), isAncestorOf: (mnode14, true), hasChild: true, parent:mnode3, degree: 2))
XCTAssertTrue(nodeCheck(mnode3, value: "C", depth: 1, height: 2, totalNodes: 8, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (mnode1, true), isAncestorOf: (mnode7, true), hasChild: true, parent:mnode1, degree: 3))
mnode7.removeFromParentNode()
XCTAssertTrue(mnode7.parentNode == nil)
XCTAssertEqual(nodeSize(mnode1), mnode1Size - mnode7Size, "削除したノードに所属していたノード数だけ減少しているはずです。")
XCTAssertEqual(nodeSize(mnode7), mnode7Size, "削除されたノード自身のノード数は変わりません。")
XCTAssertTrue(nodeCheck(mnode7, value: "G", depth: 0, height: 1, totalNodes: 3, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (mnode1, false), isAncestorOf: (mnode14, true), hasChild: true, parent:MNode?(), degree: 2))
XCTAssertTrue(nodeCheck(mnode3, value: "C", depth: 1, height: 2, totalNodes: 5, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (mnode1, true), isAncestorOf: (mnode7, false), hasChild: true, parent:mnode1, degree: 2))
let found5 = mtree1.search(mnode5)
let found7 = mtree1.search(mnode7)
let found1 = mtree1.search(mnode1)
switch found5.state {
case .NotFound:
XCTFail()
case .FoundAsRootNode:
XCTFail()
case .Found:
let parent = found5.parent!
let index = found5.index!
let child = parent.childNodes[index]
XCTAssertEqual(child, mnode5)
}
switch found7.state {
case .NotFound:
break
case .FoundAsRootNode:
XCTFail()
case .Found:
XCTFail()
}
switch found1.state {
case .NotFound:
XCTFail()
case .FoundAsRootNode:
break
case .Found:
XCTFail()
}
let found5ByPredicate = mtree1.search { $0.value == mnode5.value }
let found7ByPredicate = mtree1.search { $0 == mnode7 }
let found1ByPredicate = mtree1.search { $0 == mnode1 }
switch found5ByPredicate.state {
case .NotFound:
XCTFail()
case .FoundAsRootNode:
XCTFail()
case .Found:
let parent = found5.parent!
let index = found5.index!
let child = parent.childNodes[index]
XCTAssertEqual(child, mnode5)
}
switch found7ByPredicate.state {
case .NotFound:
break
case .FoundAsRootNode:
XCTFail()
case .Found:
XCTFail()
}
switch found1ByPredicate.state {
case .NotFound:
XCTFail()
case .FoundAsRootNode:
break
case .Found:
XCTFail()
}
}
func testBinarySearchTree() {
typealias Tree = Swim.BinarySearchTree<Int>
let tree = Tree()
let string = { (tree:Tree) -> String in
tree.reduce("") { $0 + "/" + String($1.value!) }
}
let levelOrder = { (tree:Tree) -> String in
switch tree.rootNode {
case let .Some(node):
return Swim.reduceByLevelOrder(node, "") { $0 + "/" + String($1.value!) }
case .None:
return ""
}
}
XCTAssertTrue(string(tree) == "")
XCTAssertTrue(levelOrder(tree) == "")
XCTAssertTrue(treeCheck(tree, height: 0, totalNodes: 0, hasRootNode: false))
let node8 = tree.insert(8)
XCTAssertTrue(node8.value! == 8 )
XCTAssertTrue(string(tree) == "/8")
XCTAssertTrue(levelOrder(tree) == "/8")
XCTAssertTrue(treeCheck(tree, height: 0, totalNodes: 1, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node8, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node3 = tree.insert(3)
XCTAssertTrue(string(tree) == String("/3/8"))
XCTAssertTrue(levelOrder(tree) == String("/8/3"))
XCTAssertTrue(treeCheck(tree, height: 1, totalNodes: 2, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 1, totalNodes: 2, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node3, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node10 = tree.insert(10)
XCTAssertTrue(string(tree) == String("/3/8/10"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10"))
XCTAssertTrue(treeCheck(tree, height: 1, totalNodes: 3, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 1, totalNodes: 3, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node3, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node6 = tree.insert(6)
XCTAssertTrue(string(tree) == String("/3/6/8/10"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/6"))
XCTAssertTrue(treeCheck(tree, height: 2, totalNodes: 4, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 2, totalNodes: 4, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node6, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node6, true), hasChild: true, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:node6, degree: 1))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node4 = tree.insert(4)
XCTAssertTrue(string(tree) == String("/3/4/6/8/10"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/6/4"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 5, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 3, totalNodes: 5, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node4, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node6, true), hasChild: true, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:node6, degree: 1))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node4, true), hasChild: true, parent:node3, leftChild:node4, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node7 = tree.insert(7)
XCTAssertTrue(string(tree) == String("/3/4/6/7/8/10"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/6/4/7"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 6, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 3, totalNodes: 6, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node4, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 4, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node6, true), hasChild: true, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:node6, degree: 1))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node1 = tree.insert(1)
XCTAssertTrue(string(tree) == String("/1/3/4/6/7/8/10"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/1/6/4/7"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 7, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 3, totalNodes: 7, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node1, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 5, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node1, true), hasChild: true, parent:node8, leftChild:node1, rightChild:node6, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node8, true), isAncestorOf: (node8, false), hasChild: false, parent:node8, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node14 = tree.insert(14)
XCTAssertTrue(string(tree) == String("/1/3/4/6/7/8/10/14"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/1/6/14/4/7"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 8, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 3, totalNodes: 8, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node14, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 5, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node1, true), hasChild: true, parent:node8, leftChild:node1, rightChild:node6, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node14, true), hasChild: true, parent:node8, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node10, true), isAncestorOf: (node8, false), hasChild: false, parent:node10, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let node13 = tree.insert(13)
XCTAssertTrue(string(tree) == String("/1/3/4/6/7/8/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/8/3/10/1/6/14/4/7/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 9, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 3, totalNodes: 9, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 5, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node1, true), hasChild: true, parent:node8, leftChild:node1, rightChild:node6, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, true), isAncestorOf: (node13, true), hasChild: true, parent:node8, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let nodeF5 = tree.search(5)
let nodeF6 = tree.search(6)
XCTAssertTrue(nodeF5.isEmpty)
XCTAssertEqual(nodeF6!, node6)
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
XCTAssertTrue(bnodeCheck(nodeF6!, value: 6, depth: 2, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, true), hasChild: true, parent:node3, leftChild:node4, rightChild:node7, degree: 2))
let maxNode = tree.maxNode!
let minNode = tree.minNode!
XCTAssertEqual(maxNode, node14)
XCTAssertEqual(minNode, node1)
XCTAssertNotEqual(maxNode, node13)
XCTAssertNotEqual(minNode, node7)
tree.remove(8)
XCTAssertTrue(string(tree) == String("/1/3/4/6/7/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/7/3/10/1/6/14/4/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 8, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 2, totalNodes: 4, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node1, true), hasChild: true, parent:node7, leftChild:node1, rightChild:node6, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, true), hasChild: true, parent:node7, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, true), isAncestorOf: (node7, false), hasChild: true, parent:node3, leftChild:node4, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 3, totalNodes: 8, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node10, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
tree.remove(7)
XCTAssertTrue(string(tree) == String("/1/3/4/6/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/6/3/10/1/4/14/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 7, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node1, true), hasChild: true, parent:node6, leftChild:node1, rightChild:node4, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node13, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 3, totalNodes: 7, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node10, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node3, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
tree.remove(1)
XCTAssertTrue(string(tree) == String("/3/4/6/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/6/3/10/4/14/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 6, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node1, false), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:node4, degree: 1))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node13, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 3, totalNodes: 6, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node1, false), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node3, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
let newNode1 = tree.insert(1)
let retest1 = isAncestor(node3, of: node1)
XCTAssertFalse(retest1, "基準 (of:) の node1 が消されたあと、新しい node1 が追加されている状態で実行されます。現行では、既存の node1 の値以外の状態を更新できないため、新しい「1」をたどれません。そのため、ノードを削除した後は、新しいノードに差し替える必要があります。child を NodeValue で持てば対応できるかもしれません。対応できるとここが True 判定になり、新しいノードへの差し替えをせずに、node1 を使い続けられるようになります。")
XCTAssertTrue(string(tree) == String("/1/3/4/6/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/6/3/10/1/4/14/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 7, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 1, height: 1, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (newNode1, true), hasChild: true, parent:node6, leftChild:node1, rightChild:node4, degree: 2))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node13, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 3, totalNodes: 7, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node10, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:node3, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node3, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, true), isAncestorOf: (node8, false), hasChild: false, parent:node3, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
tree.remove(3)
XCTAssertTrue(string(tree) == String("/1/4/6/10/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/6/1/10/4/14/13"))
XCTAssertTrue(treeCheck(tree, height: 3, totalNodes: 6, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 1, height: 2, totalNodes: 3, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node13, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild: node14, degree: 1))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 3, totalNodes: 6, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node10, true), hasChild: true, parent:Optional<Tree.Node>(), leftChild:newNode1, rightChild:node10, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, false), isAncestorOf: (node3, false), hasChild: false, parent:newNode1, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 2, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, true), hasChild: true, parent:node10, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 3, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, true), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node4, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:node4, degree: 1))
tree.remove(10)
XCTAssertTrue(string(tree) == String("/1/4/6/13/14"))
XCTAssertTrue(levelOrder(tree) == String("/6/1/14/4/13"))
XCTAssertTrue(treeCheck(tree, height: 2, totalNodes: 5, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 2, totalNodes: 5, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node10, false), hasChild: true, parent:Optional<Tree.Node>(), leftChild:newNode1, rightChild:node14, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, false), isAncestorOf: (node3, false), hasChild: false, parent:newNode1, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node10, false), isAncestorOf: (node13, true), hasChild: true, parent:node6, leftChild:node13, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node10, false), isAncestorOf: (node8, false), hasChild: false, parent:node14, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node4, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:node4, degree: 1))
tree.remove(14)
XCTAssertTrue(string(tree) == String("/1/4/6/13"))
XCTAssertTrue(levelOrder(tree) == String("/6/1/13/4"))
XCTAssertTrue(treeCheck(tree, height: 2, totalNodes: 4, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 2, totalNodes: 4, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node14, false), hasChild: true, parent:Optional<Tree.Node>(), leftChild:newNode1, rightChild:node13, degree: 2))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, false), isAncestorOf: (node3, false), hasChild: false, parent:newNode1, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node14, false), isAncestorOf: (node8, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node4, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:node4, degree: 1))
tree.remove(13)
XCTAssertTrue(string(tree) == String("/1/4/6"))
XCTAssertTrue(levelOrder(tree) == String("/6/1/4"))
XCTAssertTrue(treeCheck(tree, height: 2, totalNodes: 3, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 2, totalNodes: 3, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, false), hasChild: true, parent:Optional<Tree.Node>(), leftChild:newNode1, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 2, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node3, false), isAncestorOf: (node3, false), hasChild: false, parent:newNode1, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 1, height: 1, totalNodes: 2, isRoot: false, isLeaf: false, isInternal: true, isExternal: false, isDescendantOf: (node6, true), isAncestorOf: (node4, true), hasChild: true, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:node4, degree: 1))
tree.remove(4)
XCTAssertTrue(string(tree) == String("/1/6"))
XCTAssertTrue(levelOrder(tree) == String("/6/1"))
XCTAssertTrue(treeCheck(tree, height: 1, totalNodes: 2, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 1, totalNodes: 2, isRoot: true, isLeaf: false, isInternal: false, isExternal: false, isDescendantOf: (node3, false), isAncestorOf: (node13, false), hasChild: true, parent:Optional<Tree.Node>(), leftChild:newNode1, rightChild:Optional<Tree.Node>(), degree: 1))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 1, height: 0, totalNodes: 1, isRoot: false, isLeaf: true, isInternal: false, isExternal: true, isDescendantOf: (node6, true), isAncestorOf: (node4, false), hasChild: false, parent:node6, leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
tree.remove(6)
XCTAssertTrue(string(tree) == String("/1"))
XCTAssertTrue(levelOrder(tree) == String("/1"))
XCTAssertTrue(treeCheck(tree, height: 0, totalNodes: 1, hasRootNode: true))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node6, false), isAncestorOf: (node4, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertEqual(tree.rootNode!, newNode1)
tree.remove(1)
XCTAssertTrue(tree.rootNode == nil)
XCTAssertTrue(string(tree) == String(""))
XCTAssertTrue(levelOrder(tree) == String(""))
XCTAssertTrue(treeCheck(tree, height: 0, totalNodes: 0, hasRootNode: false))
XCTAssertTrue(bnodeCheck(node8, value: 8, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node7, value: 7, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node3, value: 3, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node10, value: 10, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node14, value: 14, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node13, value: 13, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node4, value: 4, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(node6, value: 6, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
XCTAssertTrue(bnodeCheck(newNode1, value: 1, depth: 0, height: 0, totalNodes: 1, isRoot: true, isLeaf: true, isInternal: false, isExternal: false, isDescendantOf: (node8, false), isAncestorOf: (node13, false), hasChild: false, parent:Optional<Tree.Node>(), leftChild:Optional<Tree.Node>(), rightChild:Optional<Tree.Node>(), degree: 0))
}
}
| mit | 4bd1af0dd099e46912449a25f9493d93 | 71.259494 | 426 | 0.716716 | 3.194572 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Main/Controller/MainTabBarController.swift | 1 | 3290 | //
// MainTabBarController.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/21.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
// MARK:- 懒加载
fileprivate lazy var tabbar : STTabBar = {[weak self] in
let tabbar = STTabBar()
tabbar.delegate = self
tabbar.frame = self!.tabBar.bounds
return tabbar
}()
// MARK:- 生命周期
override func viewDidLoad() {
super.viewDidLoad()
// 1 自定义tabBar
setupTabBar()
// 2 添加子控制器
setupAddChildViewController()
// 3 去除tabBar上的线
removeImageViewLine()
}
/// 去除系统的item
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
for subView in tabBar.subviews{
guard subView is UIControl else { continue }
subView.removeFromSuperview()
}
}
}
extension MainTabBarController {
fileprivate func setupTabBar() {
tabBar.addSubview(tabbar)
}
fileprivate func setupAddChildViewController() {
addChildVc(HomeViewController(), title: "", normalImageName: "tabbar_icon_homepage_normal", selectedImageName: "tabbar_icon_homepage_pressed")
addChildVc(SubscriptionViewController(), title: "", normalImageName: "tabbar_icon_Rss_normal", selectedImageName: "tabbar_icon_Rss_pressed")
addChildVc(FindViewController(), title: "", normalImageName: "tabbar_icon_find_normal", selectedImageName: "tabbar_icon_find_pressed")
addChildVc(MeViewController(), title: "", normalImageName: "tabbar_icon_my_normal", selectedImageName: "tabbar_icon_my_pressed")
}
fileprivate func removeImageViewLine() {
let rect = CGRect(x: 0, y: 0, width: stScreenW, height: stScreenH);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
context?.setFillColor(UIColor.clear.cgColor);
context?.fill(rect);
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
tabBar.backgroundImage = img
tabBar.shadowImage = img
}
// 子控制器实现
fileprivate func addChildVc(_ childVc : UIViewController, title : String, normalImageName : String, selectedImageName : String){
// 标题
childVc.title = title
// 图片
childVc.tabBarItem.image = UIImage(named: normalImageName)
guard let selectedImage = UIImage(named: selectedImageName) else { return }
if iOS7{
childVc.tabBarItem.selectedImage = selectedImage.withRenderingMode(.alwaysOriginal)
}else{
childVc.tabBarItem.selectedImage = selectedImage
}
let mainNav = MainNavigationController(rootViewController: childVc)
addChildViewController(mainNav)
tabbar.creatTabbarItem(childVc.tabBarItem)
}
}
extension MainTabBarController : STTabbarDelegate {
func didSelectButtonAtIndex(_ stTabbar: STTabBar, index: Int) {
selectedIndex = index
}
}
| mit | 96e0557ef12756c0f44e05db66397cfb | 28.768519 | 150 | 0.63577 | 5.236156 | false | false | false | false |
derekcoder/SwiftDevHints | SwiftDevHints/Classes/StringExtensions.swift | 2 | 4087 | //
// StringExtensions.swift
// SwiftDevHints
//
// Created by ZHOU DENGFENG on 10/8/17.
// Copyright © 2017 ZHOU DENGFENG DEREK. All rights reserved.
//
import Foundation
import CommonCrypto
import CoreGraphics
public extension String {
/// The safe way to return string slice based on specified half-open range.
///
/// let string = "Hello, Swift!"
/// string[safe: 0..<5] // "Hello"
/// string[safe: 0..<14] // nil
///
/// - Parameter range: The half-open range.
subscript(safe range: CountableRange<Int>) -> String? {
guard let lowerIdx = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIdx = index(lowerIdx, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil }
return String(self[lowerIdx..<upperIdx])
}
/// The safe way to return string slice based on specified closed range.
///
/// let string = "Hello, Swift!"
/// string[safe: 0...4] // "Hello"
/// string[safe: 0...13] // nil
///
/// - Parameter range: The closed range.
subscript(safe range: ClosedRange<Int>) -> String? {
guard let lowerIdx = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIdx = index(lowerIdx, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil }
return String(self[lowerIdx..<upperIdx])
}
/// Generate MD5
///
/// let string = "Swift".md5 // ae832e9b5bda2699db45f3fa6aa8c556
///
// var md5: String {
// let data = self.data(using:.utf8)!
// var md5 = Data(count: Int(CC_MD5_DIGEST_LENGTH))
// md5.withUnsafeMutableBytes { md5Buffer in
// data.withUnsafeBytes { buffer in
// let _ = CC_MD5(buffer.baseAddress!, CC_LONG(buffer.count), md5Buffer.bindMemory(to: UInt8.self).baseAddress)
// }
// }
// return md5.map { String(format: "%02hhx", $0) }.joined()
// }
/// Return a string with first letter capitalized
///
/// let string = "hello world".capitalizingFirstLetter()
/// print(string) // "Hello world"
///
func capitalizingFirstLetter() -> String {
guard !isEmpty else { return "" }
return prefix(1).uppercased() + dropFirst()
}
/// Capitalize the first letter
///
/// var string = "hello world"
/// string.capitalizeFirstLetter()
/// print(string) // "Hello world"
///
mutating func capitalizeFirstLetter() {
self = capitalizingFirstLetter()
}
/// Convert hex string to int
///
/// print("FF".intBaseHex) // 255
/// print("Ff".intBaseHex) // 255
/// print("fF".intBaseHex) // 255
/// print("ff".intBaseHex) // 255
/// print("0xff".intBaseHex) // 255
/// print("fg".intBaseHex) // nil
///
var intBaseHex: Int? {
guard contains("0x") else {
return Int(self, radix: 16)
}
return Int(dropFirst(2), radix: 16)
}
/// Return nil if string is empty
///
/// let string = "Swift".nilIfEmpty // String?: "Swift"
/// let string = "".nilIfEmpty // String?: nil
///
var nilIfEmpty: String? {
guard !isEmpty else { return nil }
return self
}
var isBlank: Bool {
return trimmed().isEmpty
}
func trimmed() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
mutating func trimming() {
self = trimmed()
}
}
public extension String {
var int: Int? {
return Int(self)
}
var int32: Int32? {
return Int32(self)
}
var float: Float? {
return Float(self)
}
var double: Double? {
return Double(self)
}
var cgFloat: CGFloat? {
guard let double = double else { return nil }
return CGFloat(double)
}
}
| mit | 82899b6695c27086492994b9cf4d93d9 | 29.266667 | 136 | 0.567548 | 3.982456 | false | false | false | false |
icecoffin/GlossLite | GlossLite/Views/AddEditWord/WordInputView.swift | 1 | 1964 | //
// WordInputView.swift
// GlossLite
//
// Created by Daniel on 03/10/16.
// Copyright © 2016 icecoffin. All rights reserved.
//
import UIKit
class WordInputView: UIView {
private let titleLabel = UILabel()
private let textFieldContainerView = UIView()
private let textField = UITextField()
var text: String {
get {
return textField.text ?? ""
}
set {
textField.text = newValue
}
}
init() {
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
addTitleLabel()
addTextFieldContainerView()
addTextField()
}
private func addTitleLabel() {
addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(16)
make.leading.equalToSuperview().offset(24)
}
titleLabel.font = Fonts.openSansSemibold(size: 16)
titleLabel.text = NSLocalizedString("Word", comment: "")
titleLabel.textColor = .black
}
private func addTextFieldContainerView() {
addSubview(textFieldContainerView)
textFieldContainerView.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.leading.equalToSuperview().offset(16)
make.trailing.equalToSuperview().offset(-16)
make.bottom.equalToSuperview()
}
textFieldContainerView.backgroundColor = .groupTableViewBackground
textFieldContainerView.layer.cornerRadius = 10
}
private func addTextField() {
textFieldContainerView.addSubview(textField)
textField.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(8)
}
textField.textColor = .black
textField.font = Fonts.openSans(size: 16)
textField.placeholder = NSLocalizedString("Enter your word here", comment: "")
}
override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
}
| mit | fe19f31545bbfd1f639bdb72ae102a53 | 23.848101 | 82 | 0.693836 | 4.533487 | false | false | false | false |
tomerciucran/space-game | spacegame/GameViewController.swift | 1 | 686 | //
// GameViewController.swift
// spacegame
//
// Created by Tomer Ciucran on 1/18/16.
// Copyright (c) 2016 Tomer Ciucran. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var scene:GameScene!
override func viewDidLoad() {
super.viewDidLoad()
scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
scene.scaleMode = .resizeFill
skView.presentScene(scene)
}
override var prefersStatusBarHidden : Bool {
return true
}
}
| mit | e67473245e08cd2d72f67783a8387540 | 21.866667 | 58 | 0.64723 | 4.425806 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.